Files
ProjectDashboard/public/app.js

3743 lines
210 KiB
JavaScript
Raw Normal View History

2026-11-12 09:32:23 +01:00
/* Project dashboard UI: board (kanban), gallery and list views, a side panel
to edit a project, see its git/storage/tool info and start actions.
Icons come from the Lucide sprite served at /icons.svg. */
const STATUS = [
{ key: 'idea', label: 'Idee', icon: 'lightbulb', color: '#94a3b8' },
{ key: 'active', label: 'Aktiv', icon: 'rocket', color: '#22c55e' },
{ key: 'paused', label: 'Pausiert', icon: 'circle-pause', color: '#f59e0b' },
{ key: 'done', label: 'Fertig', icon: 'circle-check', color: '#3b82f6' },
{ key: 'archived', label: 'Archiviert', icon: 'archive', color: '#8b5cf6' },
]
const STATUS_BY = Object.fromEntries(STATUS.map((s) => [s.key, s]))
const PRIO_ORDER = { high: 0, medium: 1, low: 2 }
const PRIO_LABEL = { high: 'Hoch', medium: 'Mittel', low: 'Niedrig' }
const TECH_ICON = {
Unity: 'box', Node: 'hexagon', Electron: 'atom', Expo: 'smartphone', Capacitor: 'smartphone', Vite: 'zap',
React: 'atom', '.NET': 'code-xml', Flutter: 'feather', Android: 'smartphone', 'C++/CMake': 'cpu',
Python: 'square-terminal', Web: 'globe', Arduino: 'circuit-board',
}
const GIT_ICON = { green: 'cloud-check', yellow: 'cloud-upload', red: 'cloud-off' }
// label/hint/short come from the dictionary (tier.<key>.*); here only style + icon
2026-11-12 09:32:23 +01:00
const TIER = {
Cache: { cls: 'ok', icon: 'recycle' },
Release: { cls: 'warn', icon: 'package' },
Output: { cls: 'warn', icon: 'images' },
}
// use window.I18N.t (not the global t) – these run inside .map((t)=>…) where t is shadowed
const tierLabel = (k) => window.I18N.t('tier.' + k + '.label')
const tierHint = (k) => window.I18N.t('tier.' + k + '.hint')
const tierShort = (k) => window.I18N.t('tier.' + k + '.short')
2026-11-12 09:32:23 +01:00
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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}
// Small, dependency-free Markdown -> HTML for a project's README. Everything is escaped first, so no
// raw HTML from the file can run; then a safe subset is formatted. Links only for http(s), open extern.
function renderMarkdown(src) {
const esc = escapeHtml(String(src ?? '').replace(/\r\n?/g, '\n'))
const inline = (s) => s
.replace(/`([^`]+)`/g, (_, c) => `<code>${c}</code>`)
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, (_, txt, url) => `<a href="${url}" target="_blank" rel="noopener">${txt}</a>`)
.replace(/(^|[^*])\*\*([^*\n]+)\*\*/g, '$1<strong>$2</strong>')
.replace(/(^|[^*_])[*_]([^*_\n]+)[*_]/g, '$1<em>$2</em>')
const lines = esc.split('\n')
let html = '', i = 0
const closeList = (stack) => { while (stack.length) html += stack.pop() }
const listStack = []
while (i < lines.length) {
const line = lines[i]
// fenced code block
if (/^\s*```/.test(line)) { closeList(listStack); i++; const buf = []; while (i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]); i++; html += `<pre><code>${buf.join('\n')}</code></pre>`; continue }
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) { closeList(listStack); html += '<hr>'; i++; continue }
const h = line.match(/^(#{1,6})\s+(.*)$/)
if (h) { closeList(listStack); html += `<h${h[1].length}>${inline(h[2].trim())}</h${h[1].length}>`; i++; continue }
const q = line.match(/^\s*&gt;\s?(.*)$/) // '>' was escaped to &gt;
if (q) { closeList(listStack); const buf = []; let m = q; while (i < lines.length && (m = lines[i].match(/^\s*&gt;\s?(.*)$/))) { buf.push(m[1]); i++ } html += `<blockquote>${inline(buf.join(' '))}</blockquote>`; continue }
const li = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/)
if (li) { const ordered = /\d/.test(li[2]); const want = ordered ? '</ol>' : '</ul>'; if (listStack[listStack.length - 1] !== want) { closeList(listStack); html += ordered ? '<ol>' : '<ul>'; listStack.push(want) } html += `<li>${inline(li[3].trim())}</li>`; i++; continue }
if (!line.trim()) { closeList(listStack); i++; continue }
// paragraph: gather until blank
closeList(listStack); const buf = [line]; i++; while (i < lines.length && lines[i].trim() && !/^\s*(#|&gt;|```|[-*+]\s|\d+\.\s|---|\*\*\*)/.test(lines[i])) buf.push(lines[i++])
html += `<p>${inline(buf.join(' '))}</p>`
}
closeList(listStack)
return html
}
2026-11-12 09:32:23 +01:00
function timeAgo(iso) {
if (!iso) return ''
const days = Math.floor((Date.now() - new Date(iso)) / 86400000)
if (days <= 0) return t('time.today')
if (days === 1) return t('time.yesterday')
if (days < 30) return t('time.daysAgo', { n: days })
if (days < 365) return t('time.monthsAgo', { n: Math.floor(days / 30) })
return t('time.yearsAgo', { n: Math.floor(days / 365) })
2026-11-12 09:32:23 +01:00
}
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
const isToday = (iso) => { if (!iso) return false; const d = new Date(iso), n = new Date(); return d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate() }
2026-11-12 09:32:23 +01:00
function fmtDate(iso, withYear = true) {
if (!iso) return '–'
return new Date(iso).toLocaleDateString(I18N.locale(), withYear ? { day: '2-digit', month: '2-digit', year: '2-digit' } : { day: '2-digit', month: '2-digit' })
2026-11-12 09:32:23 +01:00
}
function changeTitle(p) {
const at = lastActivity(p)
const when = new Date(at).toLocaleString(I18N.locale(), { dateStyle: 'full', timeStyle: 'short' })
if (p.lastChange) return `${t('change.last', { when })}\n${p.lastChange.file}${p.lastChange.partial ? '\n' + t('change.partial') : ''}`
return p.lastChange === undefined ? t('change.detecting', { when }) : t('change.last', { when })
2026-11-12 09:32:23 +01:00
}
function sizeTitle(p) {
if (p.storage?.sizeMB == null) return t('size.unscanned')
return t('size.scanned', { size: fmtMB(p.storage.sizeMB), ago: timeAgo(p.storage.at) }) + (deletableMB(p) >= 1 ? ' · ' + t('size.cleanable', { size: fmtMB(deletableMB(p)) }) : '')
2026-11-12 09:32:23 +01:00
}
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 ? t('git.' + git.level) : gitLabel(git)
return `<span class="git ${git.level}" title="${escapeHtml(gitLabel(git))}">${ic(GIT_ICON[git.level], 'sm')}<span class="gl">${escapeHtml(label)}</span></span>`
}
// Git status line in the current language, built from the server's raw fields (lib/git.js)
function gitLabel(g) {
if (!g) return ''
if (!g.isRepo) return t('gitl.noGit')
if (g.label === 'Git nicht installiert') return t('gitl.notInstalled')
const parts = []
if (g.dirty) parts.push(t('gitl.changed', { n: g.dirty }))
if (g.ahead) parts.push(t('gitl.unpushed', { n: g.ahead }))
if (g.behind) parts.push(t('gitl.behind', { n: g.behind }))
if (!g.remote) return [t('gitl.noRemote'), ...parts].join(' · ')
if (!g.upstream) return [t('gitl.noUpstream'), ...parts].join(' · ')
return parts.length ? parts.join(' · ') : t('gitl.saved')
2026-11-12 09:32:23 +01:00
}
// Backup state of one project (p.lastBackup from the server: own or full backup, newer one)
2026-11-12 14:03:53 +01:00
// days after which an un-backed-up change counts as "Backup fällig" (Einstellungen → Backup)
let BACKUP_FRESH_DAYS = 7
2026-11-12 09:32:23 +01:00
function cloudInfo(p) {
const l = p.lastBackup
if (!l) return { level: 'red', short: t('cloud.never'), label: t('cloud.neverLong') }
2026-11-12 09:32:23 +01:00
const days = (Date.now() - new Date(l.at)) / 86400000
const when = new Date(l.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' })
2026-11-12 09:32:23 +01:00
const level = l.ok === false ? 'red' : days > BACKUP_FRESH_DAYS ? 'yellow' : 'green'
const extra = l.ok === false ? ' – ' + t('cloud.incomplete') : days > BACKUP_FRESH_DAYS ? ' – ' + t('cloud.olderThan', { n: BACKUP_FRESH_DAYS }) : ''
const due = backupDue(p) ? ' · ' + t('cloud.dueSince') : ''
return { level, short: timeAgo(l.at), label: t('cloud.savedAt', { when, how: l.how }) + extra + due }
2026-11-12 14:03:53 +01:00
}
// changed since the last backup (or never backed up) and that backup is older than the reminder time
function backupDue(p) {
const changed = p.lastChange?.at
if (!changed || p.folder === '_Tools') return false
const l = p.lastBackup
if (!l) return true
return changed > l.at && Date.now() - new Date(l.at) > BACKUP_FRESH_DAYS * 86400000
2026-11-12 09:32:23 +01:00
}
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 ? t('pub.title', { title: x.title ? ': ' + x.title : '', src: x.source === 'manual' ? t('pub.manual') : t('pub.auto') }) : ''
2026-11-12 09:32:23 +01:00
}
// favorites: a star to toggle (tiles, panel) or a small mark (cards, rows)
const favMark = (p) => (p.favorite ? `<span class="favmark" title="${t('fav.is')}">${ic('star', 'sm')}</span>` : '')
const favBtn = (p, cls = '') => `<button type="button" class="favbtn ${p.favorite ? 'on' : ''} ${cls}" data-fav title="${p.favorite ? t('fav.remove') : t('fav.add')}" aria-pressed="${!!p.favorite}">${ic('star')}</button>`
async function toggleFavorite(p) {
try {
const res = await fetch(`/api/projects/${encodeURIComponent(p.name)}`, {
method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ favorite: !p.favorite }),
})
const r = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(r.error ?? t('err.saveFailed'))
for (const x of [p, projects.find((y) => y.name === p.name), editing?.name === p.name ? editing : null]) if (x) x.favorite = r.favorite
render()
if (editing?.name === p.name) {
const el = document.getElementById('pFav')
el.innerHTML = favBtn(editing)
wireFav(el, editing)
}
toast(r.favorite ? t('fav.now', { name: p.name }) : t('fav.not', { name: p.name }), 'star')
} catch (e) { toast(e.message, 'triangle-alert') }
}
function wireFav(el, p) {
for (const b of el.querySelectorAll('[data-fav]')) {
b.onclick = (e) => { e.stopPropagation(); toggleFavorite(p) }
b.addEventListener('mousedown', (e) => e.stopPropagation())
}
}
2026-11-12 09:32:23 +01:00
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')}${t('status.' + s.key)}</span>`
2026-11-12 09:32:23 +01:00
}
function prioHtml(prio) {
const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal'
return `<span class="prio ${prio}" title="${t('prio.titled', { p: t('prio.' + prio) })}">${ic(icon, 'sm')}${t('prio.' + prio)}</span>`
2026-11-12 09:32:23 +01:00
}
// Which projects folder a project is from - only shown when several are on screen.
2026-11-12 20:23:53 +01:00
// A project from a subfolder (scanner) also names the folder it lies in.
2026-11-12 09:32:23 +01:00
function rootTag(p, short = false) {
2026-11-12 20:23:53 +01:00
const parent = p.parent
? `<span class="rtag ptag" title="${t('rtag.sub', { f: escapeHtml(p.parent) })}">${ic('folder-tree', 'sm')}${short ? '' : ' '}${escapeHtml(p.parent.split('\\').pop())}</span>`
2026-11-12 20:23:53 +01:00
: ''
if (!multiRoot() || !p.rootName) return parent
2026-11-12 09:32:23 +01:00
const path = roots.find((r) => r.id === p.root)?.path ?? ''
return `<span class="rtag" title="${t('rtag.folder', { f: escapeHtml(p.rootName) })}${path ? ` (${escapeHtml(path)})` : ''}">${ic('folder', 'sm')}${short ? '' : ' '}${escapeHtml(p.rootName)}</span>${parent}`
2026-11-12 09:32:23 +01:00
}
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="${t('warn.cleanTitle', { cache: fmtMB(p.storage.deletable.Cache), builds: fmtMB(p.storage.deletable.Release), raw: fmtMB(p.storage.deletable.Output) })}">${ic('brush-cleaning', 'sm')}${fmtMB(deletableMB(p))}</span>`)
2026-11-12 09:32:23 +01:00
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')}${t('warn.genCopy')}</span>`)
2026-11-12 09:32:23 +01:00
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')}${t('warn.noIcon')}</span>`)
2026-11-12 09:32:23 +01:00
return b.join('')
}
/* ── data ─────────────────────────────────────────────────────────────── */
let rootDir = '' // first shown projects folder
let rootPaths = [] // all shown projects folders
let roots = [] // registered projects folders [{ id, name, path }]
let activeRoots = [] // ids of the shown ones (several possible)
const multiRoot = () => activeRoots.length > 1
let noneShown = false // deliberately no folder shown (dropdown "Keinen anzeigen")
2026-11-12 20:58:18 +01:00
// optional features (Einstellungen → Allgemein → Funktionen)
let FEATURES = { itch: false }
const itchOn = () => !!FEATURES.itch
2026-11-12 09:32:23 +01:00
// demo edition (server: edition.json): { limit, total, buyUrl } or null in the full version
let DEMO = null
const demoFull = () => !!DEMO && DEMO.total >= DEMO.limit
function renderDemo() {
const on = !!DEMO
document.getElementById('demoBanner').hidden = !on
document.getElementById('spDemo').hidden = !on
document.getElementById('spBuy').hidden = !on
if (!on) return
document.getElementById('demoText').textContent = DEMO.total > DEMO.limit
? t('demo.banner', { n: DEMO.limit, total: DEMO.total })
: t('demo.bannerUpTo', { n: DEMO.limit })
for (const id of ['demoBuy', 'spBuy']) document.getElementById(id).href = DEMO.buyUrl
}
// "New" / "Clone" in the demo once the limit is reached: hint instead of the dialog
function demoBlocksNew() {
if (!demoFull()) return false
toast(t('demo.newBlocked', { n: DEMO.limit }), 'rocket', () => window.open(DEMO.buyUrl, '_blank'))
return true
}
2026-11-12 09:32:23 +01:00
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] : [])
2026-11-12 14:03:53 +01:00
BACKUP_FRESH_DAYS = data.remindDays ?? 7
noneShown = !!data.noneShown
document.getElementById('noneBox').hidden = !noneShown
2026-11-12 20:58:18 +01:00
FEATURES = data.features ?? { itch: false }
DEMO = data.demo ?? null
renderDemo()
2026-11-12 20:58:18 +01:00
document.body.classList.toggle('no-itch', !itchOn())
2026-11-12 09:32:23 +01:00
renderRootPicker()
if (editing) editing = projects.find((p) => p.name === editing.name) ?? editing
render()
2026-11-12 14:03:53 +01:00
renderBackupButton()
fitHeader() // folder name / backup count may have changed the width
2026-11-12 14:03:53 +01:00
// "last change" dates are all known → the backup reminder can count
if (!data.activityPending && backup) remindBackup()
2026-11-12 09:32:23 +01:00
if (scanState?.running) pollScan()
// last-change dates are still being collected in the background → refresh once more
clearTimeout(load.again)
if (data.activityPending > 0) load.again = setTimeout(load, 2500)
// first start: choose the projects folder – with the guided setup tour (once per session)
if (data.setupNeeded) {
const opening = openSettings(true)
if (!load.setupToured) { load.setupToured = true; Promise.resolve(opening).then(() => setTimeout(() => startTour('setup'), 400)) }
}
2026-11-12 20:23:53 +01:00
// projects found in subfolders that were never looked at: one hint per session
if (data.nestedHint > 0 && !load.nestedHinted && !data.setupNeeded) {
load.nestedHinted = true
setTimeout(() => toast(t(data.nestedHint === 1 ? 'nested.found1' : 'nested.foundN', { n: data.nestedHint }), 'folder-tree', openNested), 1500)
2026-11-12 20:23:53 +01:00
}
2026-11-12 09:32:23 +01:00
}
/* ── new project / clone ──────────────────────────────────────────────── */
const newDlg = document.getElementById('newDlg')
function openNewProject(from = '') {
closeEditor()
const sel = document.getElementById('nFrom')
sel.innerHTML = `<option value="">${t('new.empty')}</option>` +
[...projects].sort((a, b) => a.name.localeCompare(b.name, 'de')).map((p) => `<option value="${escapeHtml(p.name)}">${t('new.cloneOf', { name: escapeHtml(p.name) })}</option>`).join('')
2026-11-12 09:32:23 +01:00
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}${t('new.copySuffix')}` : ''
2026-11-12 09:32:23 +01:00
document.getElementById('nError').style.display = 'none'
syncNewDlg()
newDlg.showModal()
document.getElementById('nName').select()
}
function syncNewDlg() {
const clone = !!document.getElementById('nFrom').value
document.getElementById('nCloneOpts').hidden = !clone
document.getElementById('nEmptyHint').hidden = clone
document.getElementById('newTitle').textContent = clone ? t('dlg.new.titleClone') : t('dlg.new.title')
document.querySelector('#nOk span').textContent = clone ? t('dlg.new.clone') : t('dlg.new.create')
2026-11-12 09:32:23 +01:00
}
document.getElementById('nFrom').addEventListener('change', () => {
const from = document.getElementById('nFrom').value
const name = document.getElementById('nName')
// keep a typed name, replace only the suggested one
const suffix = t('new.copySuffix')
const sfxRe = new RegExp(suffix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$')
if (!name.value.trim() || sfxRe.test(name.value)) name.value = from ? `${from}${suffix}` : ''
2026-11-12 09:32:23 +01:00
syncNewDlg()
})
document.getElementById('nCancel').onclick = () => newDlg.close()
document.getElementById('btnNew').onclick = () => { if (!demoBlocksNew()) openNewProject('') }
document.getElementById('btnClone').onclick = () => { if (editing && !demoBlocksNew()) openNewProject(editing.name) }
2026-11-12 14:03:53 +01:00
/* ── rename / move a project ──────────────────────────────────────────── */
const moveDlg = document.getElementById('moveDlg')
let moving = null
const driveOf = (p) => (p.match(/^([A-Za-z]:|\\\\[^\\]+\\[^\\]+)/)?.[1] ?? '').toLowerCase()
function openMove(p) {
moving = p
const from = roots.find((r) => r.id === p.root)
document.getElementById('mvFrom').textContent = t('move.now', { path: `${from ? `${from.path}\\` : ''}${p.folder ?? p.name}` })
2026-11-12 14:03:53 +01:00
document.getElementById('mvName').value = p.folder ?? p.name
document.getElementById('mvRoot').innerHTML = roots.map((r) => `<option value="${escapeHtml(r.id)}">${escapeHtml(r.name)} – ${escapeHtml(r.path)}</option>`).join('')
document.getElementById('mvRoot').value = p.root ?? activeRoots[0] ?? ''
document.getElementById('mvCopyOk').checked = false
document.getElementById('mvError').style.display = 'none'
syncMove()
moveDlg.showModal()
document.getElementById('mvName').select()
}
function syncMove() {
const from = roots.find((r) => r.id === moving?.root)
const to = roots.find((r) => r.id === document.getElementById('mvRoot').value)
document.getElementById('mvCopy').hidden = !(from && to && driveOf(from.path) !== driveOf(to.path))
}
document.getElementById('mvRoot').addEventListener('change', syncMove)
document.getElementById('mvCancel').onclick = () => moveDlg.close()
document.getElementById('btnMove').onclick = () => { if (editing) openMove(editing) }
document.getElementById('moveForm').addEventListener('submit', async (e) => {
e.preventDefault()
const err = document.getElementById('mvError')
err.style.display = 'none'
if (!document.getElementById('mvCopy').hidden && !document.getElementById('mvCopyOk').checked) {
err.innerHTML = `${ic('triangle-alert')}<div>${t('move.confirmCopy')}</div>`
2026-11-12 14:03:53 +01:00
err.style.display = ''
return
}
const ok = document.getElementById('mvOk')
ok.disabled = true
ok.querySelector('span').textContent = document.getElementById('mvCopy').hidden ? t('move.renaming') : t('move.copying')
2026-11-12 14:03:53 +01:00
try {
const r = await postJson(api(moving.name, 'move'), { name: document.getElementById('mvName').value, root: document.getElementById('mvRoot').value })
moveDlg.close()
closeEditor()
toast(r.shown ? t('move.okShown', { name: r.name, root: r.rootName }) : t('move.okHidden', { name: r.name, root: r.rootName }), 'folder-pen')
2026-11-12 14:03:53 +01:00
await load()
const p = r.shown && 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 = t('common.apply')
2026-11-12 14:03:53 +01:00
}
})
2026-11-12 09:32:23 +01:00
document.getElementById('newForm').addEventListener('submit', async (e) => {
e.preventDefault()
const ok = document.getElementById('nOk')
const err = document.getElementById('nError')
const from = document.getElementById('nFrom').value
const root = document.getElementById('nRoot').value
err.style.display = 'none'
ok.disabled = true
const label = ok.querySelector('span').textContent
ok.querySelector('span').textContent = from ? t('move.copying') : t('new.creating')
2026-11-12 09:32:23 +01:00
try {
const r = await postJson('/api/projects/new', {
name: document.getElementById('nName').value, root, from,
withGit: document.getElementById('nGit').checked, skipBuild: document.getElementById('nSkipBuild').checked,
})
newDlg.close()
toast(t(r.cloned ? 'new.clonedOk' : 'new.createdOk', { name: r.name }), 'folder-plus')
2026-11-12 09:32:23 +01:00
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 ? (roots.length ? t('root.none') : t('root.projects')) : cur.length === 1 ? cur[0].name : cur.length === roots.length && cur.length > 2 ? t('root.allN', { n: cur.length }) : cur.map((r) => r.name).join(' + ')
rootBtn.title = cur.length ? t('root.shown', { list: cur.map((r) => r.path).join('\n') }) : t('root.switch')
2026-11-12 09:32:23 +01:00
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 ? t('root.hide') : t('root.add')}">${ic(on ? 'square-check' : 'square', 'sm')}</button>
<button type="button" role="option" data-root="${escapeHtml(r.id)}" aria-selected="${on}" title="${t('root.only')}">
2026-11-12 09:32:23 +01:00
<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>${t('root.showAll')}</button>` : '') +
(activeRoots.length ? `<button type="button" data-root-none><span class="chk">${ic('square-dashed', 'sm')}</span>${t('root.showNone')}</button>` : '') +
2026-11-12 09:32:23 +01:00
`${roots.length ? '<div class="sep"></div>' : ''}` +
(hasPicker ? `<button type="button" data-root-add><span class="chk">${ic('folder-plus', 'sm')}</span>${t('root.addFolder')}</button>` : '') +
`<button type="button" data-root-import><span class="chk">${ic('folders', 'sm')}</span>${t('root.import')}</button>
<button type="button" data-root-nested><span class="chk">${ic('folder-tree', 'sm')}</span>${t('root.nested')}</button>
<button type="button" data-root-manage><span class="chk">${ic('settings', 'sm')}</span>${t('root.manage')}</button>`
2026-11-12 09:32:23 +01:00
}
// Adds folders via the server and (optionally) switches to the first new one.
async function addRoots(paths, activate) {
const r = await postJson('/api/roots/add', { paths, activate })
settingsCache = r
if (!r.added.length) { toast(t('root.already'), 'info'); return r }
2026-11-12 09:32:23 +01:00
if (activate) { closeEditor(); searchTerm = ''; document.getElementById('search').value = '' }
await load()
if (activate) await loadBackup()
toast(r.added.length === 1 ? t('root.added1', { name: r.added[0].name }) : t('root.addedN', { n: r.added.length }), 'folder-plus')
2026-11-12 09:32:23 +01:00
return r
}
// "Ordner hinzufügen…" (desktop app): folder dialog → add → switch to it
async function addRootByPicker() {
const chosen = await pickFolder(t('pick.projectsFolder'), rootDir)
2026-11-12 09:32:23 +01:00
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(t('pick.parentFolder'), input.value)
2026-11-12 09:32:23 +01:00
if (chosen) { input.value = chosen; listRootImport() }
}
document.getElementById('rdClose').onclick = () => rootDlg.close()
function toggleRootMenu(open = rootMenu.hidden) {
rootMenu.hidden = !open
rootBtn.setAttribute('aria-expanded', String(open))
if (open) (rootMenu.querySelector('[aria-selected="true"]') ?? rootMenu.querySelector('button'))?.focus()
}
// Shows the given folders (ids, in list order). keepOpen: the menu stays open (ticking boxes).
async function showRoots(ids, keepOpen = false) {
if (!keepOpen) toggleRootMenu(false)
ids = roots.map((r) => r.id).filter((id) => ids.includes(id))
if (ids.join('|') === activeRoots.join('|')) return // [] = show no folder (empty dashboard)
2026-11-12 09:32:23 +01:00
const prev = activeRoots
activeRoots = ids // tick right away; the projects follow when loaded
renderRootPicker()
try {
await postJson('/api/roots/active', { ids })
closeEditor()
searchTerm = ''
document.getElementById('search').value = ''
await load()
await loadBackup()
if (!keepOpen) toast(ids.length ? t('root.showing', { list: roots.filter((r) => ids.includes(r.id)).map((r) => r.name).join(' + ') }) : t('root.noneShown'), 'folder-open')
2026-11-12 09:32:23 +01:00
} 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 }
2026-11-12 20:23:53 +01:00
if (b.hasAttribute('data-root-nested')) { toggleRootMenu(false); openNested(); return }
2026-11-12 09:32:23 +01:00
if (b.hasAttribute('data-root-all')) { showRoots(roots.map((r) => r.id)); return }
if (b.hasAttribute('data-root-none')) { showRoots([]); return }
2026-11-12 09:32:23 +01:00
const t = b.dataset.rootToggle
if (t) {
const next = activeRoots.includes(t) ? activeRoots.filter((x) => x !== t) : [...activeRoots, t]
showRoots(next, true)
return
}
showRoots([b.dataset.root])
})
rootMenu.addEventListener('keydown', (e) => {
const items = [...rootMenu.querySelectorAll('button')]
const i = items.indexOf(document.activeElement)
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus() }
if (e.key === 'Escape') { e.stopPropagation(); toggleRootMenu(false); rootBtn.focus() }
})
document.addEventListener('click', () => { if (!rootMenu.hidden) toggleRootMenu(false) })
/* ── settings (projects folder, backup target) ────────────────────────── */
let settingsCache = null
let settingsSetup = false
// In the desktop app (WebView2) the exe shows a real folder dialog; in a
// normal browser the user types the path.
const hasPicker = !!window.chrome?.webview
const pickWaiters = new Map()
if (hasPicker) {
window.chrome.webview.addEventListener('message', (e) => {
const m = e.data
if ((m?.type === 'folderPicked' || m?.type === 'filePicked') && pickWaiters.has(m.id)) { pickWaiters.get(m.id)(m.path ?? ''); pickWaiters.delete(m.id) }
if (m?.type === 'appSettings') showAppSettings(m)
2026-11-12 09:32:23 +01:00
})
} else document.body.classList.add('no-picker')
// window options of the desktop app (tray, autostart) - kept by the launcher, not in settings.json
let appSettingsSent = null
function showAppSettings(m) {
document.getElementById('appWin').hidden = false
document.getElementById('fTray').checked = !!m.tray
document.getElementById('fAutostart').checked = !!m.autostart
if (appSettingsSent) {
const what = appSettingsSent
appSettingsSent = null
toast(what === 'tray' ? (m.tray ? t('tray.on') : t('tray.off')) : (m.autostart ? t('autostart.on') : t('autostart.off')), 'app-window')
}
}
if (hasPicker) {
for (const id of ['fTray', 'fAutostart']) {
document.getElementById(id).addEventListener('change', (e) => {
e.stopPropagation()
appSettingsSent = id === 'fTray' ? 'tray' : 'autostart'
window.chrome.webview.postMessage({ type: 'appSettings', [appSettingsSent]: e.target.checked })
})
}
}
2026-11-12 09:32:23 +01:00
function pickDialog(type, title, initial) {
return new Promise((resolve) => {
const id = Math.random().toString(36).slice(2)
pickWaiters.set(id, resolve)
window.chrome.webview.postMessage({ type, id, title, initial })
})
}
const pickFolder = (title, initial) => pickDialog('pickFolder', title, initial)
const pickFile = (title, initial) => pickDialog('pickFile', title, initial)
async function openSettings(setup) {
settingsSetup = !!setup
closeEditor(); closeBackup()
try { settingsCache = await (await fetch('/api/settings')).json() } catch {}
if (hasPicker) window.chrome.webview.postMessage({ type: 'getAppSettings' })
2026-11-12 09:32:23 +01:00
const s = settingsCache ?? { roots: [], backup: { targets: [], excludeDirs: [] } }
2026-11-12 14:03:53 +01:00
shownRootIds = s.activeRoots ?? [s.activeRoot]
document.getElementById('fRoots').innerHTML = (s.roots ?? []).map((r) => rootRow(r)).join('') || rootRow()
2026-11-12 09:32:23 +01:00
document.getElementById('fImport').hidden = true
document.getElementById('fImportBody').innerHTML = ''
2026-11-12 14:03:53 +01:00
document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('')
setExDirs(s.backup?.excludeDirs ?? [])
document.getElementById('fRemind').value = s.backup?.remindDays ?? 7
const au = s.backup?.auto ?? { interval: 'off', time: '20:00', weekday: 5, target: 'all' }
document.getElementById('fAutoInt').value = au.interval
document.getElementById('fAutoTime').value = au.time
document.getElementById('fAutoDay').value = String(au.weekday)
document.getElementById('fAutoTarget').innerHTML = `<option value="all">${t('set.auto.allTargets')}</option>` +
2026-11-12 14:03:53 +01:00
(s.backup?.targets ?? []).map((t) => `<option value="${escapeHtml(t.id)}">${escapeHtml(t.name)}</option>`).join('')
document.getElementById('fAutoTarget').value = au.target
if (!document.getElementById('fAutoTarget').value) document.getElementById('fAutoTarget').value = 'all'
syncAuto()
renderAutoStatus()
2026-11-12 09:32:23 +01:00
document.getElementById('fItchProfile').value = s.itchProfile ?? ''
2026-11-12 20:58:18 +01:00
document.getElementById('fFeatItch').checked = !!s.features?.itch
syncFeatures()
if (s.features?.itch) loadItchStatus()
2026-11-12 14:03:53 +01:00
document.getElementById('spData').innerHTML = s.dataDir
? `<div>${t('data.settings')}</div><div><code>${escapeHtml(s.dataDir)}</code></div>
<div>${t('data.scanBackup')}</div><div>${t('data.sameFolder')}</div>
<div>${t('data.appearance')}</div><div>${t('data.appearanceVal')}</div>`
2026-11-12 14:03:53 +01:00
: ''
2026-11-12 09:32:23 +01:00
document.getElementById('spWelcome').style.display = setup ? '' : 'none'
document.getElementById('spTitle').textContent = setup ? t('set.setup') : t('set.title')
2026-11-12 09:32:23 +01:00
document.getElementById('spError').style.display = 'none'
2026-11-12 14:03:53 +01:00
for (const b of document.querySelectorAll('#spTabs button')) b.classList.remove('has-err')
setSettingsTab('folders')
refreshSettingsRows()
2026-11-12 09:32:23 +01:00
const panel = document.getElementById('spanel')
2026-11-12 14:03:53 +01:00
panel.classList.remove('dirty')
2026-11-12 09:32:23 +01:00
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')
2026-11-12 14:03:53 +01:00
el.className = 'spstatus'
el.innerHTML = `${ic('loader')}<div>${t('itch.reading')}</div>`
2026-11-12 09:32:23 +01:00
try {
const r = refresh ? await postJson('/api/itch/refresh', {}) : await (await fetch('/api/itch')).json()
2026-11-12 14:03:53 +01:00
if (!r.profile) { el.innerHTML = ''; return }
2026-11-12 09:32:23 +01:00
const un = r.unmatched ?? []
2026-11-12 14:03:53 +01:00
el.className = `spstatus ${r.error ? 'err' : 'ok'}`
2026-11-12 09:32:23 +01:00
el.innerHTML = r.error
2026-11-12 14:03:53 +01:00
? `${ic('triangle-alert')}<div>${escapeHtml(r.error)}</div>`
: `${ic('circle-check')}<div>${t('itch.found', { n: r.games.length })}` +
(un.length ? ' ' + t('itch.unmatched', { list: un.map((g) => `<a href="${escapeHtml(g.url)}" target="_blank">${escapeHtml(g.title)}</a>`).join(', ') }) : ' ' + t('itch.allMatched')) + '</div>'
2026-11-12 14:03:53 +01:00
} catch (e) { el.className = 'spstatus err'; el.textContent = e.message }
2026-11-12 09:32:23 +01:00
}
document.getElementById('btnItchRefresh').onclick = async () => { await loadItchStatus(true); load() }
function closeSettings() {
if (settingsSetup) return // the projects folder is required
const panel = document.getElementById('spanel')
if (!panel.classList.contains('open')) return
panel.classList.remove('open')
panel.setAttribute('aria-hidden', 'true')
if (!editing && !document.getElementById('bpanel').classList.contains('open')) document.getElementById('overlay').classList.remove('open')
if (tour?.def === TOURS.setup) endTour() // saved / closed: the setup tour is done
2026-11-12 09:32:23 +01:00
}
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()),
2026-11-12 14:03:53 +01:00
excludeDirs: getExDirs(),
remindDays: Number(document.getElementById('fRemind').value) || 7,
auto: {
interval: document.getElementById('fAutoInt').value,
time: document.getElementById('fAutoTime').value || '20:00',
weekday: Number(document.getElementById('fAutoDay').value),
target: document.getElementById('fAutoTarget').value || 'all',
},
2026-11-12 09:32:23 +01:00
itchProfile: document.getElementById('fItchProfile').value,
2026-11-12 20:58:18 +01:00
features: { itch: document.getElementById('fFeatItch').checked },
2026-11-12 09:32:23 +01:00
}
2026-11-12 14:03:53 +01:00
const btn = document.getElementById('spSave')
btn.disabled = true
2026-11-12 09:32:23 +01:00
try {
settingsCache = await postJson('/api/settings', body)
const firstSetup = settingsSetup
2026-11-12 09:32:23 +01:00
settingsSetup = false
2026-11-12 14:03:53 +01:00
document.getElementById('spanel').classList.remove('dirty')
2026-11-12 09:32:23 +01:00
closeSettings()
toast(t('set.saved'), 'save')
2026-11-12 09:32:23 +01:00
await loadBackup()
await load()
// first start done: show "Help & overview" so a new user learns the tool right away
if (firstSetup) setTimeout(() => { helpPage = 0; renderHelp(); document.getElementById('helpDlg').showModal() }, 500)
2026-11-12 09:32:23 +01:00
} catch (e) {
err.innerHTML = `${ic('triangle-alert')}<div>${escapeHtml(e.message)}</div>`
err.style.display = ''
2026-11-12 14:03:53 +01:00
// mark (and show) the tab the error belongs to
const tab = /Backup-Ziel/.test(e.message) ? 'backup' : /itch/i.test(e.message) ? 'itch' : 'folders'
for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('has-err', b.dataset.stab === tab)
setSettingsTab(tab)
} finally {
btn.disabled = false
2026-11-12 09:32:23 +01:00
}
}
2026-11-12 14:03:53 +01:00
/* automatic backup (settings → Backup) */
function syncAuto() {
const v = document.getElementById('fAutoInt').value
document.getElementById('fAutoTimeWrap').hidden = !['daily', 'weekly'].includes(v)
document.getElementById('fAutoDayWrap').hidden = v !== 'weekly'
document.getElementById('fAutoTargetWrap').hidden = v === 'off' || (settingsCache?.backup?.targets?.length ?? 0) < 2
}
document.getElementById('fAutoInt').addEventListener('change', syncAuto)
// "heute 20:00", "morgen 20:00", "Fr., 14.11. 20:00"
function fmtWhen(iso) {
const d = new Date(iso), now = new Date()
const time = d.toLocaleTimeString(I18N.locale(), { hour: '2-digit', minute: '2-digit' })
if (d - now < 60000) return t('when.soon')
2026-11-12 14:03:53 +01:00
const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
const diff = Math.round((day(d) - day(now)) / 86400000)
return diff === 0 ? t('when.today', { time }) : diff === 1 ? t('when.tomorrow', { time }) : `${d.toLocaleDateString(I18N.locale(), { weekday: 'short', day: 'numeric', month: 'numeric' })} ${time}`
2026-11-12 14:03:53 +01:00
}
function renderAutoStatus() {
const el = document.getElementById('spAuto')
const sch = backup?.schedule
if (!sch || sch.interval === 'off') { el.className = 'spstatus'; el.innerHTML = ''; return }
const r = sch.lastResult
const last = r ? (r.ok ? t('auto.lastOk', { ago: timeAgo(r.at) }) : t('auto.lastFail', { ago: timeAgo(r.at), detail: escapeHtml(r.targets.filter((x) => !x.ok).map((x) => `${x.name}: ${x.error ?? t('auto.error')}`).join('; ')) })) : t('auto.never')
2026-11-12 14:03:53 +01:00
el.className = `spstatus ${r && !r.ok ? 'err' : r ? 'ok' : ''}`
el.innerHTML = `${ic(sch.running ? 'loader' : r && !r.ok ? 'triangle-alert' : 'calendar-clock')}<div>${sch.running ? '<b>' + t('auto.running') + '</b> ' : sch.next ? t('auto.next', { when: `<b>${fmtWhen(sch.next)}</b>` }) + ' ' : ''}${last}</div>`
2026-11-12 14:03:53 +01:00
}
/* settings tabs, dirty marker, Ctrl+S */
2026-11-12 20:58:18 +01:00
// the itch.io tab follows the switch right away (saved with "Speichern")
function syncFeatures() {
const on = document.getElementById('fFeatItch').checked
const btn = document.querySelector('#spTabs button[data-stab="itch"]')
btn.style.display = on ? '' : 'none'
if (!on && btn.classList.contains('active')) setSettingsTab('general')
}
document.getElementById('fFeatItch').addEventListener('change', () => {
syncFeatures()
if (document.getElementById('fFeatItch').checked) loadItchStatus()
})
2026-11-12 14:03:53 +01:00
function setSettingsTab(tab) {
for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('active', b.dataset.stab === tab)
for (const p of document.querySelectorAll('#spanel [data-spane]')) p.hidden = p.dataset.spane !== tab
}
for (const b of document.querySelectorAll('#spTabs button')) b.onclick = () => setSettingsTab(b.dataset.stab)
const markSettingsDirty = () => document.getElementById('spanel').classList.add('dirty')
document.getElementById('spanel').addEventListener('input', (e) => { if (!e.target.closest('#fImport, #appWin') && e.target.id !== 'fLang') markSettingsDirty() })
2026-11-12 14:03:53 +01:00
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && document.getElementById('spanel').classList.contains('open')) {
e.preventDefault()
saveSettings()
}
})
document.getElementById('spOpenData').onclick = async () => {
try { await postJson('/api/datadir/open') } catch (e) { toast(e.message, 'triangle-alert') }
}
/* settings backup / restore / reset (Einstellungen → Allgemein → Daten) */
document.getElementById('spExport').onclick = async () => {
try {
const data = await (await fetch('/api/settings/export')).json()
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = `project-dashboard-settings-${new Date().toISOString().slice(0, 10)}.json`
a.click()
setTimeout(() => URL.revokeObjectURL(a.href), 2000)
toast(t('set.exported'), 'download')
} catch (e) { toast(e.message, 'triangle-alert') }
}
document.getElementById('spImport').onclick = () => document.getElementById('spImportFile').click()
document.getElementById('spImportFile').onchange = async (e) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
try {
const data = JSON.parse(await file.text())
if (!confirm(t('set.importConfirm'))) return
await postJson('/api/settings/import', { data })
toast(t('set.imported'), 'upload')
setTimeout(() => location.reload(), 600)
} catch (ex) { toast(t('set.importBad') + ' ' + (ex.message ?? ''), 'triangle-alert') }
}
document.getElementById('spReset').onclick = async () => {
if (!confirm(t('set.resetConfirm'))) return
try {
const r = await postJson('/api/settings/reset')
toast(r.backupFile ? t('set.resetDone', { file: r.backupFile }) : t('set.resetDoneNoBackup'), 'refresh-cw')
setTimeout(() => location.reload(), 900)
} catch (e) { toast(e.message, 'triangle-alert') }
}
2026-11-12 09:32:23 +01:00
// "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')
2026-11-12 14:03:53 +01:00
if (name && !name.value) { name.value = row.classList.contains('rrow') ? folderName(chosen) : shortTargetName(chosen); name.size = nameSize(name.value) }
if (row) { markSettingsDirty(); refreshSettingsRows() }
2026-11-12 09:32:23 +01:00
if (b.dataset.for === 'fImportPath') listImport()
})
2026-11-12 14:03:53 +01:00
// One list entry (projects folder or backup target): [icon] name + badges / path / info line [actions]
2026-11-12 09:32:23 +01:00
const folderName = (p) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || p
2026-11-12 14:03:53 +01:00
let shownRootIds = [] // folders shown on the board (badge "angezeigt")
// the name field grows with its text, so the badges sit right after it
const nameSize = (v) => Math.min(40, Math.max(10, (v ?? '').length + 2))
function settingsItem(kind, x, placeholder) {
const isRoot = kind === 'root'
return `<div class="sitem ${isRoot ? 'rrow' : 'trow'}" data-id="${escapeHtml(x.id)}">
<div class="fico">${ic(isRoot ? 'folder' : 'hard-drive')}</div>
<div class="smeta">
<div class="snm"><input type="text" class="tname" placeholder="${isRoot ? t('row.name') : t('row.nameTarget')}" value="${escapeHtml(x.name)}" size="${nameSize(x.name)}" aria-label="${t('row.name')}"><span class="sbadges"></span></div>
<input type="text" class="tpath" placeholder="${escapeHtml(placeholder)}" value="${escapeHtml(x.path)}" aria-label="${t('row.path')}">
2026-11-12 14:03:53 +01:00
<div class="sstat"></div>
</div>
<div class="sacts">
<button class="ibtn pickbtn" type="button" data-title="${isRoot ? t('pick.projectsFolder') : t('pick.backupFolder')}" title="${t('row.chooseFolder')}">${ic('folder-search')}</button>
<button class="ibtn" type="button" data-up title="${isRoot ? t('row.upRoot') : t('row.upTarget')}">${ic('arrow-up')}</button>
<button class="ibtn rm" type="button" data-rm title="${isRoot ? t('row.rmRoot') : t('row.rmTarget')}">${ic('x')}</button>
2026-11-12 14:03:53 +01:00
</div>
2026-11-12 09:32:23 +01:00
</div>`
}
const rootRow = (r = { id: '', name: '', path: '' }) => settingsItem('root', r, t('row.phRoot'))
const targetRow = (x = { id: '', name: '', path: '' }) => settingsItem('target', x, t('row.phTarget'))
2026-11-12 14:03:53 +01:00
// badges and info lines depend on the order (first = main folder / default target)
function refreshSettingsRows() {
const rows = [...document.querySelectorAll('#fRoots .rrow')]
rows.forEach((row, i) => {
const id = row.dataset.id
const name = row.querySelector('.tname').value.trim() || folderName(row.querySelector('.tpath').value.trim())
const n = id && shownRootIds.includes(id) ? projects.filter((p) => p.root === id).length : null
row.querySelector('.sbadges').innerHTML =
(i === 0 ? `<span class="sbadge main">${ic('star')}${t('row.main')}</span> ` : '') +
(id && shownRootIds.includes(id) ? `<span class="sbadge on">${ic('eye')}${t('row.shown')}</span>` : '')
2026-11-12 14:03:53 +01:00
row.querySelector('.sstat').innerHTML = row.querySelector('.tpath').value.trim()
? `${n != null ? `<span>${t('row.nProjects', { n })}</span>` : ''}<span>${i === 0 ? t('row.backupDirect') : t('row.backupSub', { name: escapeHtml(name) })}</span>`
: `<span>${t('row.enterPath')}</span>`
2026-11-12 14:03:53 +01:00
row.querySelector('[data-up]').disabled = i === 0
})
const trows = [...document.querySelectorAll('#fTargets .trow')]
trows.forEach((row, i) => {
const st = backup?.targets?.find((x) => x.id === row.dataset.id)
2026-11-12 14:03:53 +01:00
const last = st?.last
row.querySelector('.sbadges').innerHTML =
(i === 0 ? `<span class="sbadge main">${t('row.default')}</span> ` : '') +
(!row.dataset.id ? '' : last ? `<span class="sbadge ${last.ok ? 'ok' : 'warn'}">${last.ok ? t('row.saved') : t('row.incomplete')} ${timeAgo(last.at)}</span>` : `<span class="sbadge warn">${t('row.neverComplete')}</span>`)
row.querySelector('.sstat').innerHTML = row.dataset.id ? '' : `<span>${t('row.newChecked')}</span>`
2026-11-12 14:03:53 +01:00
row.querySelector('[data-up]').disabled = i === 0
})
document.getElementById('spnFolders').textContent = rows.length || ''
document.getElementById('spnTargets').textContent = trows.length || ''
}
2026-11-12 09:32:23 +01:00
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))
2026-11-12 14:03:53 +01:00
markSettingsDirty()
refreshSettingsRows()
2026-11-12 09:32:23 +01:00
return box.lastElementChild
}
document.getElementById('fAddRoot').onclick = () => addRootRow().querySelector('.tpath').focus()
2026-11-12 14:03:53 +01:00
// ↑ / ✕ in both lists
for (const id of ['fRoots', 'fTargets']) {
const list = document.getElementById(id)
list.addEventListener('click', (e) => {
const row = e.target.closest('.sitem')
if (!row) return
if (e.target.closest('[data-rm]')) row.remove()
else if (e.target.closest('[data-up]') && row.previousElementSibling) row.parentNode.insertBefore(row, row.previousElementSibling)
else return
markSettingsDirty()
refreshSettingsRows()
})
list.addEventListener('input', (e) => {
if (e.target.classList.contains('tname')) e.target.size = nameSize(e.target.value)
refreshSettingsRows()
})
}
// "Nicht sichern" as chips: Enter or comma adds, ✕ removes, Backspace in the empty field removes the last
const exBox = document.getElementById('fExDirs')
const exInput = document.getElementById('fExInput')
function addExChip(v) {
v = v.trim()
if (!v || getExDirs(false).some((x) => x.toLowerCase() === v.toLowerCase())) return
exInput.insertAdjacentHTML('beforebegin', `<span class="xchip" data-v="${escapeHtml(v)}">${escapeHtml(v)}<button type="button" title="${t('common.remove')}">${ic('x', 'sm')}</button></span>`)
2026-11-12 14:03:53 +01:00
}
function setExDirs(list) {
for (const c of exBox.querySelectorAll('.xchip')) c.remove()
exInput.value = ''
for (const v of list) addExChip(v)
}
// withPending: also what is still typed in the field
function getExDirs(withPending = true) {
const list = [...exBox.querySelectorAll('.xchip')].map((c) => c.dataset.v)
if (withPending) for (const v of exInput.value.split(',')) if (v.trim() && !list.includes(v.trim())) list.push(v.trim())
return list
}
exInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ',') {
e.preventDefault()
for (const v of exInput.value.split(',')) addExChip(v)
exInput.value = ''
markSettingsDirty()
} else if (e.key === 'Backspace' && !exInput.value) {
exBox.querySelector('.xchip:last-of-type')?.remove()
markSettingsDirty()
}
})
exBox.addEventListener('click', (e) => {
const rm = e.target.closest('.xchip button')
if (rm) { rm.closest('.xchip').remove(); markSettingsDirty(); return }
exInput.focus()
2026-11-12 09:32:23 +01:00
})
// "Mehrere einlesen…": list the subfolders of a folder, tick the ones to add
document.getElementById('fImportOpen').onclick = () => {
const box = document.getElementById('fImport')
box.hidden = !box.hidden
if (!box.hidden) document.getElementById('fImportPath').focus()
}
document.getElementById('fImportList').onclick = () => listImport()
document.getElementById('fImportPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listImport() } })
function listImport() {
return importList({
dir: document.getElementById('fImportPath').value,
body: document.getElementById('fImportBody'),
have: rowRootPaths(),
onAdd: (picked) => {
for (const p of picked) addRootRow({ id: '', name: folderName(p), path: p })
document.getElementById('fImport').hidden = true
toast(t('import.addedRemember', { n: picked.length }), 'folder-plus')
2026-11-12 09:32:23 +01:00
},
})
}
// 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')} ${t('import.reading')}</div>`
2026-11-12 09:32:23 +01:00
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) ? t('import.already') : extra}</span></label>`
2026-11-12 09:32:23 +01:00
body.innerHTML = `<div class="implist">
${item({ path: r.path }, `<i>${t('import.thisFolder')}</i> (${escapeHtml(folderName(r.path))})`, t('import.nProjects', { n: r.folders.length }), true)}
${r.folders.map((f) => item(f, escapeHtml(f.name), t('import.nSub', { n: f.count }))).join('') || `<div class="hint">${t('import.noSub')}</div>`}
2026-11-12 09:32:23 +01:00
</div>
<div class="rowbtns">
<button class="btn" type="button" data-imp-all>${ic('list-checks')}${t('import.allSub')}</button>
<button class="btn primary" type="button" data-imp-add>${ic('plus')}${t('import.addSelected')}</button>
2026-11-12 09:32:23 +01:00
</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(t('import.nothingSelected'), 'info')
2026-11-12 09:32:23 +01:00
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>`
}
}
2026-11-12 14:03:53 +01:00
// short display name of a backup target: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup
2026-11-12 09:32:23 +01:00
const shortTargetName = (p) => p.match(/^\\\\([^\\]+)/)?.[1] ?? (p.match(/^([A-Za-z]:)/) ? `${p.slice(0, 2)} ${p.split('\\').filter(Boolean).pop() ?? ''}`.trim() : p.split('\\').pop())
document.getElementById('fAddTarget').onclick = () => {
document.getElementById('fTargets').insertAdjacentHTML('beforeend', targetRow())
2026-11-12 14:03:53 +01:00
markSettingsDirty()
refreshSettingsRows()
2026-11-12 09:32:23 +01:00
document.querySelector('#fTargets .trow:last-child .tpath').focus()
}
document.getElementById('btnSettings').onclick = () => openSettings(false)
document.getElementById('btnCloseSettings').onclick = closeSettings
/* help / overview dialog – paged, one topic group per page (native <dialog>: Esc closes it) */
const HELP_PAGES = [
{ id: 'views', t: 'help.g.views', rows: [['kanban', 'help.board'], ['layout-grid', 'help.gallery'], ['list', 'help.list'], ['list-checks', 'help.tasks'], ['activity', 'help.activity'], ['hard-drive', 'help.storage']] },
{ id: 'find', t: 'help.g.find', rows: [['sliders-horizontal', 'help.mode'], ['search', 'help.search'], ['funnel', 'help.filters']] },
{ id: 'project', t: 'help.g.project', rows: [['pencil', 'help.edit'], ['info', 'help.info'], ['play', 'help.actions'], ['folder-open', 'help.quick']] },
{ id: 'backup', t: 'help.g.backup', rows: [['hard-drive-upload', 'help.backup'], ['clock-alert', 'help.due']] },
{ id: 'misc', t: 'help.g.misc', rows: [['folders', 'help.folders'], ['languages', 'help.lang'], ['keyboard', 'help.keys']] },
{ id: 'setup', t: 'help.g.setup', rows: [['folders', 'tour.setup.folders'], ['hard-drive-upload', 'tour.setup.backup'], ['sliders-horizontal', 'tour.setup.general']] },
]
let helpPage = 0
function renderHelp() {
helpPage = Math.max(0, Math.min(HELP_PAGES.length - 1, helpPage))
document.getElementById('helpNav').innerHTML = HELP_PAGES.map((p, i) => `<button type="button" class="hnav ${i === helpPage ? 'active' : ''}" data-hp="${i}">${t(p.t)}</button>`).join('')
document.getElementById('helpBody').innerHTML =
`<button type="button" class="btn primary helpshow" id="helpShow">${ic('play', 'sm')}${t('help.show')}</button>` +
HELP_PAGES[helpPage].rows.map(([icon, k]) => `<div class="helprow"><span class="hc">${ic(icon)}</span><div>${t(k)}</div></div>`).join('')
document.getElementById('helpShow').onclick = () => startTour(HELP_PAGES[helpPage].id)
document.getElementById('helpDots').innerHTML = HELP_PAGES.map((_, i) => `<i class="${i === helpPage ? 'on' : ''}"></i>`).join('')
document.getElementById('helpPrev').disabled = helpPage === 0
document.getElementById('helpNext').disabled = helpPage === HELP_PAGES.length - 1
document.getElementById('helpBody').scrollTop = 0
}
const gotoHelp = (i) => { helpPage = i; renderHelp() }
document.getElementById('btnHelp').onclick = () => { helpPage = 0; renderHelp(); document.getElementById('helpDlg').showModal() }
document.getElementById('helpClose').onclick = () => document.getElementById('helpDlg').close()
document.getElementById('helpNav').onclick = (e) => { const b = e.target.closest('[data-hp]'); if (b) gotoHelp(+b.dataset.hp) }
document.getElementById('helpPrev').onclick = () => gotoHelp(helpPage - 1)
document.getElementById('helpNext').onclick = () => gotoHelp(helpPage + 1)
document.getElementById('helpDlg').addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight' && helpPage < HELP_PAGES.length - 1) gotoHelp(helpPage + 1)
if (e.key === 'ArrowLeft' && helpPage > 0) gotoHelp(helpPage - 1)
})
/* ── interactive tour: spotlight walks over the real UI, section by section ── */
// Each step points at a real element (sel). before() may switch view/mode or open
// a project so the element exists; steps whose element is missing are skipped.
const TOURS = {
views: { before: () => applyUiMode('advanced'), steps: [
{ sel: '#tabs [data-view="board"]', key: 'help.board' },
{ sel: '#tabs [data-view="gallery"]', key: 'help.gallery' },
{ sel: '#tabs [data-view="list"]', key: 'help.list' },
{ sel: '#tabs [data-view="tasks"]', key: 'help.tasks' },
{ sel: '#tabs [data-view="activity"]', key: 'help.activity' },
{ sel: '#tabs [data-view="storage"]', key: 'help.storage' },
] },
find: { before: () => { applyUiMode('advanced'); setView('board') }, steps: [
{ sel: '#modeSeg', key: 'help.mode' },
{ sel: '.searchbox', key: 'help.search' },
{ sel: '#chipfilters', key: 'help.filters' },
] },
project: { before: () => { applyUiMode('advanced'); setView('board') }, steps: [
{ sel: '#board .card .qsg', key: 'help.quick' },
{ before: () => { const p = visibleProjects()[0] || projects[0]; if (p) { tour.openedEditor = true; openEditor(p) } }, wait: 480, sel: '#ptabs [data-sec="edit"]', key: 'help.edit' },
{ sel: '#ptabs [data-sec="info"]', key: 'help.info' },
{ sel: '#ptabs [data-sec="actions"]', key: 'help.actions' },
] },
backup: { before: () => applyUiMode('advanced'), steps: [
{ sel: '#btnBackup', key: 'help.backup' },
{ sel: '#chipfilters [data-q="due"]', key: 'help.due' },
] },
misc: { before: () => applyUiMode('advanced'), steps: [
{ sel: '#rootBtn', key: 'help.folders' },
{ sel: '#btnSettings', key: 'help.lang' },
{ sel: '#btnHelp', key: 'help.keys' },
] },
// first start (and Help → Setup): walks through the settings panel; manual pace, user types meanwhile
setup: { auto: false, keepView: true, before: () => (document.getElementById('spanel').classList.contains('open') ? null : openSettings(false)), steps: [
{ key: 'tour.setup.welcome' },
{ before: () => setSettingsTab('folders'), wait: 150, sel: '#fRoots', key: 'tour.setup.folders' },
{ sel: '#fImportOpen', key: 'tour.setup.import' },
{ before: () => setSettingsTab('backup'), wait: 150, sel: '#fTargets:not(:empty), #fAddTarget', key: 'tour.setup.backup' },
{ sel: '#fAutoInt', key: 'tour.setup.auto' },
{ before: () => setSettingsTab('general'), wait: 150, sel: '#fLang', key: 'tour.setup.general' },
{ sel: '.featrow:has(#fFeatItch)', key: 'tour.setup.features' },
{ before: () => setSettingsTab('folders'), wait: 150, sel: '#spSave', key: 'tour.setup.save' },
] },
}
const AUTO_MS = 3400
let tour = null
async function startTour(id) {
const def = TOURS[id]
if (!def) return
document.getElementById('helpDlg').close()
tour = { def, steps: def.steps, i: -1, playing: def.auto !== false, timer: null, prevView: activeView, prevMode: uiMode, openedEditor: false }
try { await def.before?.() } catch {}
if (!tour) return
document.getElementById('tour').hidden = false
setTimeout(() => tourGo(1), 320) // let a view/mode switch (or the panel sliding in) render first
}
// only elements that are actually on screen (hidden sections are skipped)
const tourTarget = (s) => {
if (!s.sel) return null
const el = document.querySelector(s.sel)
return el && el.getClientRects().length ? el : null
}
async function tourGo(dir) {
if (!tour) return
clearTimeout(tour.timer)
let i = tour.i
for (;;) {
i += dir
if (i < 0) { i = 0; break }
if (i >= tour.steps.length) { endTour(); return }
const s = tour.steps[i]
if (s.before) { try { s.before() } catch {} }
if (s.wait) await new Promise((r) => setTimeout(r, s.wait))
if (!tour) return // closed meanwhile
if (!s.sel || tourTarget(s)) break // usable step (has target or is centered)
}
tour.i = i
tourShow()
}
function tourShow() {
if (!tour) return
const s = tour.steps[tour.i]
positionSpot(tourTarget(s))
document.getElementById('tourText').innerHTML = t(s.key)
document.getElementById('tourStep').textContent = `${tour.i + 1} / ${tour.steps.length}`
document.getElementById('tourPrev').disabled = tour.i === 0
document.querySelector('#tourNext span').textContent = tour.i === tour.steps.length - 1 ? t('tour.finish') : t('help.next')
document.querySelector('#tourPause use').setAttribute('href', `/icons.svg#${tour.playing ? 'pause' : 'play'}`)
clearTimeout(tour.timer)
if (tour.playing) tour.timer = setTimeout(() => tourGo(1), AUTO_MS)
}
function positionSpot(el) {
const spot = document.getElementById('tourSpot')
const bubble = document.getElementById('tourBubble')
if (el) {
try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }) } catch {}
const r = el.getBoundingClientRect(), pad = 6
spot.style.top = (r.top - pad) + 'px'
spot.style.left = (r.left - pad) + 'px'
spot.style.width = (r.width + pad * 2) + 'px'
spot.style.height = (r.height + pad * 2) + 'px'
const bw = Math.min(320, innerWidth - 24), bh = bubble.offsetHeight || 150
let top = r.bottom + 12
if (top + bh > innerHeight - 10) top = Math.max(10, r.top - bh - 12)
let left = Math.max(12, Math.min(innerWidth - bw - 12, r.left + r.width / 2 - bw / 2))
bubble.style.top = top + 'px'
bubble.style.left = left + 'px'
} else {
spot.style.width = spot.style.height = '0px'
spot.style.top = innerHeight / 2 + 'px'
spot.style.left = innerWidth / 2 + 'px'
bubble.style.top = Math.max(12, innerHeight / 2 - 90) + 'px'
bubble.style.left = (innerWidth / 2 - Math.min(320, innerWidth - 24) / 2) + 'px'
}
}
function endTour() {
if (!tour) return
clearTimeout(tour.timer)
const opened = tour.openedEditor, pv = tour.prevView, pm = tour.prevMode, keep = tour.def.keepView
tour = null
document.getElementById('tour').hidden = true
if (opened) try { closeEditor() } catch {}
if (keep) return
try { applyUiMode(pm) } catch {}
try { setView(pv) } catch {}
}
document.getElementById('tourClose').onclick = endTour
document.getElementById('tourPrev').onclick = () => tourGo(-1)
document.getElementById('tourNext').onclick = () => tourGo(1)
document.getElementById('tourPause').onclick = () => {
if (!tour) return
tour.playing = !tour.playing
tourShow()
}
addEventListener('resize', () => { if (tour) tourShow() })
addEventListener('keydown', (e) => {
if (!tour) return
if (e.target.closest?.('input, textarea, select, [contenteditable]')) return // typing a path etc.
if (e.key === 'Escape') { e.preventDefault(); endTour() }
else if (e.key === 'ArrowRight') tourGo(1)
else if (e.key === 'ArrowLeft') tourGo(-1)
})
2026-11-12 09:32:23 +01:00
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 {}
2026-11-12 14:03:53 +01:00
if (!res.ok) {
// a route the running server doesn't know yet: it's older than this page
if (res.status === 404 && !data.error) { checkVersion(); throw new Error(t('err.serverStale')) }
2026-11-12 14:03:53 +01:00
throw new Error(data.error ?? `HTTP ${res.status}`)
}
2026-11-12 09:32:23 +01:00
return data
}
2026-11-12 14:03:53 +01:00
/* ── update banner: server code or page changed since start ───────────── */
let uiStampAtLoad = null
async function checkVersion() {
let v
try {
const res = await fetch('/api/version', { cache: 'no-store' })
// 404: a server from before this check - certainly older than this page
v = res.status === 404 ? { stale: true } : await res.json()
} catch { return }
if (uiStampAtLoad === null) uiStampAtLoad = v.uiStamp ?? 0
if (v.version) { const el = document.getElementById('spVersion'); if (el) el.textContent = 'v' + v.version }
2026-11-12 14:03:53 +01:00
const banner = document.getElementById('updBanner')
const btn = document.getElementById('updBtn')
if (v.stale) {
document.getElementById('updText').textContent = t('upd.serverStale')
btn.innerHTML = `${ic('refresh-cw')}${t('upd.restart')}`
2026-11-12 14:03:53 +01:00
btn.onclick = restartServer
banner.hidden = false
} else if (v.uiStamp > uiStampAtLoad) {
document.getElementById('updText').textContent = t('upd.uiNew')
btn.innerHTML = `${ic('refresh-cw')}${t('upd.reload')}`
2026-11-12 14:03:53 +01:00
btn.onclick = () => location.reload()
banner.hidden = false
} else banner.hidden = true
}
async function restartServer() {
const btn = document.getElementById('updBtn')
btn.disabled = true
btn.innerHTML = `${ic('loader')}${t('upd.restarting')}`
2026-11-12 14:03:53 +01:00
try {
let before = null
try { before = (await (await fetch('/api/version', { cache: 'no-store' })).json()).pid } catch {}
const r = await fetch('/api/restart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
if (r.status === 409) throw new Error((await r.json()).error)
// a server from before this feature has no restart: it must be closed by hand
if (!r.ok) throw new Error(t('upd.noRestart'))
2026-11-12 14:03:53 +01:00
const until = Date.now() + 20000
while (Date.now() < until) {
await new Promise((ok) => setTimeout(ok, 700))
try {
const v = await (await fetch('/api/version', { cache: 'no-store' })).json()
if (v.pid && v.pid !== before) { location.reload(); return }
} catch {}
}
throw new Error(t('upd.noResponse'))
2026-11-12 14:03:53 +01:00
} catch (e) {
toast(e.message, 'triangle-alert')
btn.disabled = false
btn.innerHTML = `${ic('refresh-cw')}${t('upd.restart')}`
2026-11-12 14:03:53 +01:00
}
}
checkVersion()
setInterval(checkVersion, 60000)
window.addEventListener('focus', checkVersion)
document.addEventListener('visibilitychange', () => { if (!document.hidden) checkVersion() })
2026-11-12 09:32:23 +01:00
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
}
2026-11-12 20:23:53 +01:00
// onClick: the toast becomes clickable (and stays a bit longer)
function toast(text, icon = 'info', onClick = null) {
2026-11-12 09:32:23 +01:00
const el = document.getElementById('toast')
el.innerHTML = `${ic(icon)}<span>${escapeHtml(text)}</span>`
el.classList.add('show')
2026-11-12 20:23:53 +01:00
el.style.pointerEvents = onClick ? 'auto' : ''
el.style.cursor = onClick ? 'pointer' : ''
el.onclick = onClick ? () => { el.classList.remove('show'); onClick() } : null
2026-11-12 09:32:23 +01:00
clearTimeout(toast.t)
2026-11-12 20:23:53 +01:00
toast.t = setTimeout(() => el.classList.remove('show'), onClick ? 8000 : 3400)
2026-11-12 09:32:23 +01:00
}
const runAction = async (name, id) => {
try {
const r = await postJson(api(name, 'run'), { id })
toast(t('action.started', { label: r.label }), 'play')
2026-11-12 09:32:23 +01:00
} catch (e) { toast(e.message, 'triangle-alert') }
}
/* ── filtering & sorting ──────────────────────────────────────────────── */
// label is a translation key (resolved with t() at render time)
2026-11-12 09:32:23 +01:00
const QUICK = [
{ key: 'all', label: 'quick.all', icon: 'layers', test: () => true },
{ key: 'nobackup', label: 'quick.nobackup', icon: 'cloud-off', test: (p) => p.git.level === 'red' },
{ key: 'unsaved', label: 'quick.unsaved', icon: 'cloud-upload', test: (p) => p.git.level === 'yellow' },
{ key: 'due', label: 'quick.due', icon: 'clock-alert', test: backupDue },
{ key: 'cleanable', label: 'quick.cleanable', icon: 'brush-cleaning', test: (p) => deletableMB(p) >= 100 },
{ key: 'install', label: 'quick.install', icon: 'download', test: (p) => p.tech?.needsInstall },
{ key: 'noicon', label: 'quick.noicon', icon: 'image-off', test: (p) => !p.hasIcon },
{ key: 'gencopy', label: 'quick.gencopy', icon: 'copy', test: (p) => p.tools?.generators?.some((g) => g.kind === 'copy') },
{ key: 'fav', label: 'quick.fav', icon: 'star', test: (p) => !!p.favorite },
{ key: 'itch', label: 'quick.itch', icon: 'rocket', feature: 'itch', test: (p) => !!p.published },
{ key: 'noitch', label: 'quick.noitch', icon: 'circle-off', feature: 'itch', test: (p) => p.status === 'done' && !p.published },
2026-11-12 09:32:23 +01:00
]
function matchesSearch(p) {
const term = searchTerm.trim().toLowerCase()
if (!term) return true
return p.name.toLowerCase().includes(term) ||
p.notes.toLowerCase().includes(term) ||
2026-11-12 19:50:38 +01:00
(p.description ?? '').toLowerCase().includes(term) ||
2026-11-12 09:32:23 +01:00
(p.tags ?? []).some((t) => t.toLowerCase().includes(term)) ||
(p.tech?.types ?? []).some((t) => t.toLowerCase().includes(term))
}
function visibleProjects({ useStatus = true } = {}) {
const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0]
const status = document.getElementById('fltStatus').value
return projects.filter((p) => matchesSearch(p) && q.test(p) && (!useStatus || status === 'all' || p.status === status))
}
function sortProjects(items) {
const sort = document.getElementById('fltSort').value
return [...items].sort((a, b) => {
if (!!a.favorite !== !!b.favorite) return a.favorite ? -1 : 1 // favorites always first
2026-11-12 09:32:23 +01:00
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))
})
}
// is any search / quick-filter / status filter narrowing the list right now?
function filtersActive() {
const status = document.getElementById('fltStatus')?.value ?? 'all'
return !!searchTerm.trim() || quickFilter !== 'all' || status !== 'all' || (activeView === 'home' && homeStatus !== 'all')
}
function clearFilters() {
searchTerm = ''
const s = document.getElementById('search'); if (s) s.value = ''
quickFilter = 'all'
const fs = document.getElementById('fltStatus'); if (fs) fs.value = 'all'
homeStatus = 'all'
render()
}
// friendly empty state: "no matches + reset" when filtering, else "no projects + new" (hidden when demo caps)
function emptyState() {
const T = window.I18N.t
if (filtersActive())
return `<div class="empty rich">${ic('search-x', 'xl')}<div class="et">${T('empty.noMatch')}</div>` +
`<button type="button" class="btn ghost" onclick="clearFilters()">${ic('rotate-ccw', 'sm')}${T('empty.resetFilters')}</button></div>`
const act = demoBlocksNew() ? '' :
`<button type="button" class="btn primary" onclick="openNewProject('')">${ic('folder-plus', 'sm')}${T('empty.newProject')}</button>`
return `<div class="empty rich">${ic('folder-open', 'xl')}<div class="et">${T('empty.noProjects')}</div>${act}</div>`
}
2026-11-12 09:32:23 +01:00
/* ── header: KPIs, quick filters ──────────────────────────────────────── */
function renderKpis() {
const tot = totals ?? { sizeMB: 0, cacheMB: 0, allMB: 0, scanned: 0, noBackup: 0 }
2026-11-12 09:32:23 +01:00
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">${t('kpi.projects', { n: active })}</div></div></div>
<div class="kpi c-red click" data-quick="nobackup" title="${t('kpi.noRemote.title')}"><div class="ico">${ic('shield-alert', 'lg')}</div><div><div class="val">${tot.noBackup}</div><div class="lbl">${t('kpi.noRemote')}</div></div></div>
<div class="kpi c-blue"><div class="ico">${ic('hard-drive', 'lg')}</div><div><div class="val">${tot.scanned ? fmtMB(tot.sizeMB) : '–'}</div><div class="lbl">${tot.scanned ? t('kpi.used', { n: tot.scanned }) : t('kpi.notScanned')}</div></div></div>
<div class="kpi c-yellow click" data-quick="cleanable" title="${t('kpi.cleanable.title')}"><div class="ico">${ic('brush-cleaning', 'lg')}</div><div><div class="val">${tot.scanned ? fmtMB(tot.allMB) : '–'}</div><div class="lbl">${tot.scanned ? t('kpi.cleanableCache', { cache: fmtMB(tot.cacheMB) }) : t('kpi.cleanable')}</div></div></div>
2026-11-12 09:32:23 +01:00
<div class="kpi scanbox">
<button class="btn primary" id="btnScanAll" ${!cleanupAvailable || running ? 'disabled' : ''}>${ic(running ? 'loader' : 'scan-search')}${running ? t('kpi.scanN', { done: scanState.done, total: scanState.total }) : t('kpi.scanAll')}</button>
2026-11-12 09:32:23 +01:00
${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')} ${t('kpi.scanError')}</div>`
: `<div class="sub">${t('kpi.scanHint')}</div>`}
2026-11-12 09:32:23 +01:00
</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)
2026-11-12 20:58:18 +01:00
// a filter of a switched-off feature (Einstellungen → Allgemein) is gone; if it was active: back to "Alle"
if (QUICK.some((q) => q.key === quickFilter && q.feature && !FEATURES[q.feature])) quickFilter = 'all'
document.getElementById('chipfilters').innerHTML = QUICK.filter((q) => !q.feature || FEATURES[q.feature]).map((q) => {
2026-11-12 09:32:23 +01:00
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="${t(q.label)}">${ic(q.icon, 'sm')}<span class="fl">${t(q.label)}</span><span class="n">${n}</span></button>`
2026-11-12 09:32:23 +01:00
}).join('')
for (const b of document.querySelectorAll('.fchip')) b.onclick = () => { quickFilter = b.dataset.q; render() }
requestAnimationFrame(fitChips) // after the rest of the toolbar (sort, board mode) has its final size
2026-11-12 09:32:23 +01:00
}
// Measured, not a fixed breakpoint (labels differ per language): too wide → icon + count only,
// still too wide → the row scrolls sideways with a fade at the edge.
function fitChips() {
const el = document.getElementById('chipfilters')
if (!el) return
el.classList.remove('compact', 'more')
if (el.scrollWidth > el.clientWidth + 1) el.classList.add('compact')
if (el.scrollWidth > el.clientWidth + 1) el.classList.add('more')
}
// the toolbar's width, not the chips' (fitChips changes those itself – that would loop)
new ResizeObserver(() => fitChips()).observe(document.querySelector('.toolbar'))
2026-11-12 09:32:23 +01:00
function render() {
document.getElementById('count').textContent = noneShown ? t('count.none') : !rootDir ? t('count.noFolder')
: rootPaths.length > 1 ? t('count.multi', { n: projects.length, folders: rootPaths.length }) : t('count.single', { n: projects.length, dir: rootDir })
2026-11-12 09:32:23 +01:00
renderKpis()
renderQuickFilters()
updateToolbarForView()
2026-11-12 20:58:18 +01:00
renderHome()
2026-11-12 09:32:23 +01:00
renderBoard()
renderGallery()
renderList()
renderTasks()
}
// Status filter makes no sense on the board (columns = status), sorting none on tasks.
function updateToolbarForView() {
document.getElementById('selStatusWrap').style.display = activeView === 'board' ? 'none' : ''
document.getElementById('selSortWrap').style.display = activeView === 'tasks' ? 'none' : ''
document.getElementById('boardMode').style.display = activeView === 'board' ? '' : 'none'
requestAnimationFrame(fitChips) // the space left for the filter chips changed
2026-11-12 09:32:23 +01:00
}
/* ── scan ─────────────────────────────────────────────────────────────── */
function pollScan() {
clearTimeout(scanTimer)
scanTimer = setTimeout(async () => {
try { scanState = await (await fetch('/api/scan')).json() } catch { return }
renderKpis()
2026-11-12 14:03:53 +01:00
// the storage page shows results as they come in
if (activeView === 'storage') loadStorage()
2026-11-12 09:32:23 +01:00
if (scanState.running) pollScan()
else {
await load()
if (editing) loadDetails(editing.name)
toast(t('scan.done'), 'circle-check')
2026-11-12 09:32:23 +01:00
}
}, 1500)
}
async function startScan(name) {
try {
const r = await postJson('/api/scan', name ? { name } : {})
scanState = r.state
renderKpis()
2026-11-12 14:03:53 +01:00
if (activeView === 'storage') loadStorage()
2026-11-12 09:32:23 +01:00
pollScan()
} catch (e) { toast(e.message, 'triangle-alert') }
}
/* ── quick start ▶ ────────────────────────────────────────────────────── */
// p.quickStart comes from the server: own start command, main exe or first start action
function quickStartTitle(p) {
const q = p.quickStart
return q ? t('qs.start', { label: q.label }) + (q.detail ? ` (${q.detail})` : '') : ''
2026-11-12 09:32:23 +01:00
}
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 ▶.
2026-11-12 14:03:53 +01:00
// explorer: also an [Explorer] button in front.
2026-11-12 09:32:23 +01:00
function qsGroup(p, placeholder = false, explorer = false) {
const ex = explorer ? `<button class="qs vs" data-ex title="${t('qs.explorer')}">${ic('folder-open')}</button>` : ''
const vs = `<button class="qs vs" data-vs title="${t('qs.vscode')}">${ic('code-xml')}</button>`
2026-11-12 09:32:23 +01:00
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 = t('prio.titled', { p: t('prio.' + p.priority) })
2026-11-12 09:32:23 +01:00
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)}">${favMark(p)}${escapeHtml(p.name)}</span>
2026-11-12 09:32:23 +01:00
<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(gitLabel(p.git))}">${ic(GIT_ICON[p.git.level], 'sm')}</span>
2026-11-12 09:32:23 +01:00
<span class="ri ${c.level}" title="${escapeHtml(c.label)}">${ic('hard-drive', 'sm')}</span>
${open ? `<span class="ri tasks" title="${t('tasks.openN', { n: open })}">${ic('list-checks', 'sm')}${open}</span>` : ''}
2026-11-12 09:32:23 +01:00
${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>
2026-11-12 14:03:53 +01:00
${qsGroup(p, true, true)}
2026-11-12 09:32:23 +01:00
</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)}">${favMark(p)}${escapeHtml(p.name)}</div>
2026-11-12 14:03:53 +01:00
<div class="sub">${prioHtml(p.priority)}</div></div>
${qsGroup(p, false, true)}
2026-11-12 09:32:23 +01:00
</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>
2026-11-12 20:23:53 +01:00
${multiRoot() || p.parent ? `<div class="rootline">${rootTag(p)}</div>` : ''}
2026-11-12 09:32:23 +01:00
<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 })
if (!visible.length) { board.innerHTML = `<div class="boardempty">${emptyState()}</div>`; return }
2026-11-12 09:32:23 +01:00
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')}${t('status.' + col.key)}<span class="n">${items.length}</span></h2>`
2026-11-12 09:32:23 +01:00
colEl.addEventListener('dragover', (e) => { e.preventDefault(); colEl.classList.add('drag-over') })
colEl.addEventListener('dragleave', () => colEl.classList.remove('drag-over'))
colEl.addEventListener('drop', async (e) => {
e.preventDefault()
colEl.classList.remove('drag-over')
const name = e.dataTransfer.getData('text/plain')
const project = projects.find((p) => p.name === name)
if (!project || project.status === col.key) return
if (await patchProject(name, { status: col.key })) { toast(`${name} → ${t('status.' + col.key)}`, col.icon); load() }
2026-11-12 09:32:23 +01:00
})
// 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 = emptyState(); return }
2026-11-12 09:32:23 +01:00
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)}
${favBtn(p, 'onthumb')}
<span class="tbadges">${pubBadge(p)}${cloudBadge(p)}<span class="tbadge ${p.git.level}" title="Git: ${escapeHtml(gitLabel(p.git))}">${ic(GIT_ICON[p.git.level])}</span></span>
2026-11-12 09:32:23 +01:00
</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)
wireFav(tile, p)
2026-11-12 09:32:23 +01:00
tile.onclick = () => openEditor(p)
grid.appendChild(tile)
}
}
/* ── list ─────────────────────────────────────────────────────────────── */
// cls: used by CSS container queries to hide columns in narrow windows
// label is a translation key (resolved with t() at render time; '' = no header)
2026-11-12 09:32:23 +01:00
const LIST_COLS = [
{ label: 'col.project', sort: 'name' }, { label: 'col.status', cls: 'c-status' }, { label: 'col.git' }, { label: 'col.backup' }, { label: 'col.tech', cls: 'c-tech' },
{ label: 'col.size', sort: 'size', num: true }, { label: 'col.cleanable', sort: 'clean', num: true, cls: 'c-clean' },
{ label: 'col.activity', sort: 'mtime', cls: 'c-act' }, { label: '' },
2026-11-12 09:32:23 +01:00
]
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 ? t(c.label) : ''}${c.sort === sort ? ' ' + ic('arrow-down', 'sm') : ''}</th>`).join('')}</tr></thead>
2026-11-12 09:32:23 +01:00
<tbody>${items.map((p) => `<tr data-name="${escapeHtml(p.name)}">
<td><div class="nm" title="${escapeHtml(p.name)}">${avatar(p)}<span>${favMark(p)}${escapeHtml(p.name)}</span>${rootTag(p, true)}</div></td>
2026-11-12 09:32:23 +01:00
<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">${emptyState()}</td></tr>`}</tbody>`
2026-11-12 09:32:23 +01:00
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)
}
}
}
}
2026-11-12 14:03:53 +01:00
// views with their own header (no project KPIs / filter toolbar)
const WIDE_VIEWS = ['storage', 'activity']
2026-11-12 20:58:18 +01:00
/* ── simple / advanced view (switch in the header) ────────────────────── */
// simple: calm tiles, only the essentials; advanced: everything. Stored per
// browser (dash.mode). Default: advanced for an existing setup (a view was
// stored before), simple for a fresh one.
let uiMode = 'advanced'
function lastAdvView() {
try { const v = localStorage.getItem('dash.advView'); if (['board', 'gallery', 'list'].includes(v)) return v } catch {}
return 'board'
}
function initUiMode() {
let m = null
try { m = localStorage.getItem('dash.mode') ?? (localStorage.getItem('dash.view') ? 'advanced' : 'simple') } catch {}
m = new URLSearchParams(location.search).get('ui') ?? m
applyUiMode(m === 'simple' ? 'simple' : 'advanced')
}
function applyUiMode(m) {
uiMode = m
document.body.classList.toggle('simple', m === 'simple')
for (const b of document.querySelectorAll('#modeSeg button')) b.classList.toggle('active', b.dataset.ui === m)
}
function setUiMode(m) {
applyUiMode(m)
try { localStorage.setItem('dash.mode', m) } catch {}
setView(m === 'simple' ? (ADV_VIEWS.includes(activeView) ? 'home' : activeView) : (activeView === 'home' ? lastAdvView() : activeView))
render()
if (editing) { openEditor(editing); }
}
for (const b of document.querySelectorAll('#modeSeg button')) b.onclick = () => setUiMode(b.dataset.ui)
// "Projekte" page of the simple view: status pills + tiles, newest first
let homeStatus = 'all'
// layout: cards (big tiles) · compact (small tiles) · list (one row each); sort: like the toolbar
const HL_STORE = (key, allowed, dflt) => { try { const v = localStorage.getItem(key); return allowed.includes(v) ? v : dflt } catch { return dflt } }
let homeLayout = HL_STORE('dash.homeLayout', ['cards', 'compact', 'list'], 'cards')
let homeSort = HL_STORE('dash.homeSort', ['mtime', 'name', 'size'], 'mtime')
// label is a translation key (resolved with t() at render time)
2026-11-12 20:58:18 +01:00
const HOME_PILLS = [
{ key: 'all', label: 'home.all', test: (p) => p.status !== 'archived' },
{ key: 'due', label: 'quick.due', test: (p) => backupDue(p), cls: 'due' },
{ key: 'active', label: 'status.active' }, { key: 'idea', label: 'home.ideas' }, { key: 'paused', label: 'status.paused' },
{ key: 'done', label: 'status.done' }, { key: 'archived', label: 'home.archive' },
2026-11-12 20:58:18 +01:00
]
const pillTest = (q) => q.test ?? ((p) => p.status === q.key)
function sortHome(items) {
return [...items].sort((a, b) => {
if (homeSort === 'name') return a.name.localeCompare(b.name, 'de', { sensitivity: 'base' })
if (homeSort === 'size') return (b.storage?.sizeMB ?? -1) - (a.storage?.sizeMB ?? -1)
return new Date(lastActivity(b)) - new Date(lastActivity(a))
})
}
const HL_SEG = [{ k: 'cards', ic: 'layout-grid', key: 'home.cards' }, { k: 'compact', ic: 'grid-2x2', key: 'home.compact' }, { k: 'list', ic: 'list', key: 'home.list' }]
const HL_SORT = [{ k: 'mtime', key: 'flt.sort.mtime' }, { k: 'name', key: 'flt.sort.name' }, { k: 'size', key: 'flt.sort.size' }]
// "Today" band on the home page: greeting, continue-where-you-left-off, quick stats. From the loaded
// projects only (no extra request). Shown on the default home (no filter, no search).
let todayOpen = (() => { try { return localStorage.getItem('dash.todayOpen') !== '0' } catch { return true } })()
function renderToday() {
const band = document.getElementById('todayBand')
if (!band) return
if (homeStatus !== 'all' || searchTerm.trim()) { band.innerHTML = ''; return }
const live = projects.filter((p) => p.status !== 'archived')
const recent = [...live].sort((a, b) => new Date(lastActivity(b)) - new Date(lastActivity(a))).slice(0, 3)
const changed = live.filter((p) => isToday(lastActivity(p))).length
const due = projects.filter(backupDue).length
const active = projects.filter((p) => p.status === 'active').length
const h = new Date().getHours()
const greet = t(h < 5 ? 'today.night' : h < 11 ? 'today.morning' : h < 17 ? 'today.day' : h < 22 ? 'today.evening' : 'today.night')
const dateStr = new Date().toLocaleDateString(I18N.locale(), { weekday: 'long', day: 'numeric', month: 'long' })
const chip = (icon, n, label, q) => n ? `<button type="button" class="tchip" data-q="${q}">${ic(icon, 'sm')}<b>${n}</b> ${label}</button>` : ''
const stats = chip('file-pen', changed, t('today.changed'), 'all') + chip('clock-alert', due, t('today.due'), 'due') + chip('rocket', active, t('today.active'), 'active')
const cards = recent.map((p) => `<div class="tcard" data-open="${escapeHtml(p.name)}" role="button" tabindex="0">
${avatar(p)}<span class="tc-main"><span class="tc-name">${escapeHtml(p.name)}</span><span class="tc-sub">${statusHtml(p.status)}<span class="hint">· ${timeAgo(lastActivity(p))}</span></span></span>${qsGroup(p, true, false)}</div>`).join('')
band.innerHTML = `<div class="today ${todayOpen ? '' : 'closed'}">
<div class="today-head">
<div><div class="today-greet">${greet}</div><div class="today-date">${dateStr}</div></div>
<div class="today-stats">${stats}</div>
<button type="button" class="today-toggle" title="${t('today.toggle')}">${ic('chevron-down', 'sm')}</button>
</div>
<div class="today-body">${cards}${recent.length ? `<a href="#" class="jump today-act">${ic('activity', 'sm')}${t('today.activity')}</a>` : ''}</div>
</div>`
band.querySelector('.today-toggle').onclick = () => { todayOpen = !todayOpen; try { localStorage.setItem('dash.todayOpen', todayOpen ? '1' : '0') } catch {}; band.querySelector('.today').classList.toggle('closed', !todayOpen) }
for (const b of band.querySelectorAll('.tchip')) b.onclick = () => { homeStatus = b.dataset.q; renderHome() }
band.querySelector('.today-act')?.addEventListener('click', (e) => { e.preventDefault(); setView('activity') })
for (const b of band.querySelectorAll('.tcard')) {
const p = projects.find((x) => x.name === b.dataset.open)
b.onclick = (e) => { if (!e.target.closest('.qsg')) openEditor(p) }
wireQuickStart(b, p)
}
}
2026-11-12 20:58:18 +01:00
function renderHome() {
renderToday()
2026-11-12 20:58:18 +01:00
const base = projects.filter(matchesSearch)
const pills = HOME_PILLS.map((q) => {
2026-11-12 20:58:18 +01:00
const n = base.filter(pillTest(q)).length
if (q.key !== 'all' && !n && homeStatus !== q.key) return ''
return `<button type="button" class="hpill ${q.cls ?? ''} ${homeStatus === q.key ? 'active' : ''}" data-hs="${q.key}">${t(q.label)}<span class="n">${n}</span></button>`
2026-11-12 20:58:18 +01:00
}).join('')
const ctl = `<div class="hctl">
<select id="homeSortSel" title="${t('home.sort')}">${HL_SORT.map((o) => `<option value="${o.k}" ${homeSort === o.k ? 'selected' : ''}>${t(o.key)}</option>`).join('')}</select>
<div class="hseg" role="group" aria-label="${t('home.view')}">${HL_SEG.map((o) => `<button type="button" data-hl="${o.k}" class="${homeLayout === o.k ? 'active' : ''}" title="${t(o.key)}" aria-pressed="${homeLayout === o.k}">${ic(o.ic, 'sm')}</button>`).join('')}</div>
</div>`
document.getElementById('homeBar').innerHTML = pills + ctl
2026-11-12 20:58:18 +01:00
for (const b of document.querySelectorAll('#homeBar .hpill')) b.onclick = () => { homeStatus = b.dataset.hs; renderHome() }
document.getElementById('homeSortSel').onchange = (e) => { homeSort = e.target.value; try { localStorage.setItem('dash.homeSort', homeSort) } catch {}; renderHome() }
for (const b of document.querySelectorAll('#homeBar .hseg button')) b.onclick = () => { homeLayout = b.dataset.hl; try { localStorage.setItem('dash.homeLayout', homeLayout) } catch {}; renderHome() }
2026-11-12 20:58:18 +01:00
const pill = HOME_PILLS.find((q) => q.key === homeStatus) ?? HOME_PILLS[0]
const items = sortHome(base.filter(pillTest(pill)))
2026-11-12 20:58:18 +01:00
const grid = document.getElementById('homeGrid')
grid.className = homeLayout === 'cards' ? '' : homeLayout
if (!items.length) { grid.innerHTML = `<div class="empty">${ic('search-x', 'xl')}<div>${t('empty.noProjects')}</div></div>`; return }
2026-11-12 20:58:18 +01:00
grid.innerHTML = ''
// "Alle": favorites get their own row on top
const favs = homeStatus === 'all' ? items.filter((p) => p.favorite) : []
const head = (icon, text) => { const h = document.createElement('div'); h.className = 'hgroup'; h.innerHTML = `${ic(icon, 'sm')}${text}`; grid.appendChild(h) }
if (favs.length) head('star', t('home.favorites'))
const ordered = favs.length ? [...favs, null, ...items.filter((p) => !p.favorite)] : items
for (const p of ordered) {
if (!p) { head('layout-grid', t('home.allProjects')); continue }
2026-11-12 20:58:18 +01:00
const desc = (p.description || p.notes || '').split(/\r?\n/).map((x) => x.trim()).find(Boolean) ?? ''
const due = backupDue(p)
const tile = document.createElement('div')
tile.className = 'htile'
tile.innerHTML = `
<div class="hhead">
${favBtn(p, 'ontile')}
2026-11-12 20:58:18 +01:00
<div class="hicon" style="--c:${nameColor(p.name)}">${escapeHtml(initialsOf(p.name))}<img loading="lazy" src="${thumbUrl(p.name)}" alt="" onerror="this.remove()"></div>
<div style="min-width:0;flex:1">
<div class="hname" title="${escapeHtml(p.name)}">${escapeHtml(p.name)}</div>
<div class="hsub">${statusHtml(p.status)}${rootTag(p, true)}</div>
</div>
</div>
<div class="hdesc ${desc ? '' : 'none'}" title="${escapeHtml(desc)}">${desc ? escapeHtml(desc) : t('home.noDesc')}</div>
2026-11-12 20:58:18 +01:00
<div class="hfoot">
${due ? `<span class="hdue" title="${escapeHtml(cloudInfo(p).label)}"></span>` : ''}
<span class="when" title="${escapeHtml(changeTitle(p))}">${timeAgo(lastActivity(p))}</span>
${qsGroup(p, false, true)}
</div>`
wireQuickStart(tile, p)
wireFav(tile, p)
2026-11-12 20:58:18 +01:00
tile.onclick = () => openEditor(p)
grid.appendChild(tile)
}
}
const ADV_VIEWS = ['board', 'gallery', 'list']
2026-11-12 09:32:23 +01:00
function setView(view) {
2026-11-12 20:58:18 +01:00
if (uiMode === 'simple' && ADV_VIEWS.includes(view)) view = 'home'
if (uiMode === 'advanced' && view === 'home') view = lastAdvView()
const changed = activeView !== view
2026-11-12 09:32:23 +01:00
activeView = view
for (const el of document.querySelectorAll('.view')) el.classList.toggle('active', el.id === view)
if (changed) { // one-shot stagger flag; render() builds the cards, flag clears after the animation
document.body.classList.add('switching')
clearTimeout(setView._t); setView._t = setTimeout(() => document.body.classList.remove('switching'), 500)
}
2026-11-12 09:32:23 +01:00
for (const btn of document.querySelectorAll('#tabs button')) btn.classList.toggle('active', btn.dataset.view === view)
2026-11-12 14:03:53 +01:00
document.body.classList.toggle('view-wide', WIDE_VIEWS.includes(view))
2026-11-12 09:32:23 +01:00
updateToolbarForView()
2026-11-12 20:58:18 +01:00
try { localStorage.setItem('dash.view', view); if (ADV_VIEWS.includes(view)) localStorage.setItem('dash.advView', view) } catch {}
2026-11-12 14:03:53 +01:00
if (view === 'storage') loadStorage()
if (view === 'activity') loadActivity()
}
/* ── activity page: calendar heatmap of active projects per day ───────── */
let actData = null
let actDay = null
let actRange = 7
// short weekday (0=Mon…6=Sun) and month (0=Jan…) in the current language, via Intl
const dowShort = (i) => new Intl.DateTimeFormat(I18N.locale(), { weekday: 'short', timeZone: 'UTC' }).format(new Date(Date.UTC(2024, 0, 1 + i)))
const monthShort = (m) => new Intl.DateTimeFormat(I18N.locale(), { month: 'short' }).format(new Date(2024, m, 1))
2026-11-12 14:03:53 +01:00
const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
const parseDay = (k) => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d) }
const fmtDay = (k) => parseDay(k).toLocaleDateString(I18N.locale(), { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })
2026-11-12 14:03:53 +01:00
const nActive = (k) => actData?.days[k]?.projects.length ?? 0
// 0 · 1 · 2 · 3–4 · 5+ active projects
const levelOf = (n) => (n <= 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n <= 4 ? 3 : 4)
const levelLabel = (l) => window.I18N.t('act.level.' + l)
2026-11-12 14:03:53 +01:00
async function loadActivity() {
try { actData = await (await fetch('/api/activity')).json() } catch { return }
if (!actDay || !actData.days[actDay]) {
// default: today, else the last day with activity
actDay = actData.days[actData.today] ? actData.today : Object.keys(actData.days).sort().pop() ?? actData.today
}
renderActivity()
clearTimeout(loadActivity.t)
// last-change dates still being collected → refresh until complete
if (actData.pending && activeView === 'activity') loadActivity.t = setTimeout(loadActivity, 3000)
}
// heatmap grid: weeks as columns (Monday first), `weeks` back from this week
function heatGrid(weeks, cell, title) {
const today = parseDay(actData?.today ?? dayKey(new Date()))
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7))
const start = new Date(monday); start.setDate(monday.getDate() - (weeks - 1) * 7)
let html = Array.from({ length: 7 }, (_, i) => (i % 2 === 0 ? `<span class="dl" style="grid-row:${i + 2}">${dowShort(i)}</span>` : '')).join('')
2026-11-12 14:03:53 +01:00
let lastMonth = -1
for (let w = 0; w < weeks; w++) {
const first = new Date(start); first.setDate(start.getDate() + w * 7)
if (first.getMonth() !== lastMonth && first.getDate() <= 7) {
html += `<span class="ml" style="grid-column:${w + 2}">${monthShort(first.getMonth())}</span>`
2026-11-12 14:03:53 +01:00
lastMonth = first.getMonth()
} else if (w === 0) lastMonth = first.getMonth()
for (let r = 0; r < 7; r++) {
const d = new Date(first); d.setDate(first.getDate() + r)
const k = dayKey(d)
const future = d > today
html += `<button type="button" class="hc ${future ? 'future' : ''}" style="grid-column:${w + 2};grid-row:${r + 2}" data-day="${k}" data-l="${future ? 0 : cell(k)}" aria-label="${escapeHtml(title(k))}" ${future ? 'tabindex="-1"' : ''}></button>`
}
}
return html
}
function renderActivity() {
if (!actData) return
const keys = Object.keys(actData.days).filter((k) => nActive(k) > 0).sort()
// streaks: consecutive active days; the current one may end yesterday
let longest = 0, run = 0, prev = null
for (const k of keys) {
run = prev && (parseDay(k) - parseDay(prev)) === 86400000 ? run + 1 : 1
longest = Math.max(longest, run); prev = k
}
let current = 0
const t = parseDay(actData.today)
const d = new Date(t)
if (!nActive(dayKey(d))) d.setDate(d.getDate() - 1)
while (nActive(dayKey(d))) { current++; d.setDate(d.getDate() - 1) }
const best = keys.reduce((b, k) => (nActive(k) > (b ? nActive(b) : 0) ? k : b), null)
const T = window.I18N.t
const daysWord = (n) => T(n === 1 ? 'act.day1' : 'act.daysN', { n })
2026-11-12 14:03:53 +01:00
document.getElementById('acKpis').innerHTML = `
<div class="stkpi"><div class="lbl">${T('act.activeDays')}</div><div class="val">${keys.length}</div><div class="sub"><span>${T('act.pastYear')}</span></div></div>
<div class="stkpi"><div class="lbl">${T('act.currentStreak')}</div><div class="val">${daysWord(current)}</div><div class="sub"><span>${T('act.streakSub')}</span></div></div>
<div class="stkpi"><div class="lbl">${T('act.longestStreak')}</div><div class="val">${daysWord(longest)}</div><div class="sub"><span>${T('act.pastYear')}</span></div></div>
<div class="stkpi"><div class="lbl">${T('act.fullestDay')}</div><div class="val">${best ? T('act.nProjects', { n: nActive(best) }) : '–'}</div><div class="sub"><span>${best ? parseDay(best).toLocaleDateString(I18N.locale()) : ''}</span></div></div>`
document.getElementById('acPending').textContent = actData.pending ? '· ' + T('act.pending', { n: actData.pending }) : ''
document.getElementById('acLegend').innerHTML = `<span>${T('act.less')}</span><span class="hleg">${[0, 1, 2, 3, 4].map((l) => `<span class="hc" data-l="${l}" title="${levelLabel(l)}"></span>`).join('')}</span><span>${T('act.more')}</span>`
2026-11-12 14:03:53 +01:00
const heat = document.getElementById('acHeat')
heat.innerHTML = heatGrid(53, (k) => levelOf(nActive(k)), (k) => `${fmtDay(k)}: ${T('act.nProjects', { n: nActive(k) })}`)
2026-11-12 14:03:53 +01:00
heat.querySelector(`[data-day="${actDay}"]`)?.classList.add('sel')
// start scrolled to the newest weeks on narrow screens
heat.parentElement.scrollLeft = heat.parentElement.scrollWidth
renderActDay()
renderActTop()
}
function actRow(p, meta) {
return `<button type="button" data-proj="${escapeHtml(p)}"><b>${escapeHtml(p)}</b><span class="m">${meta}</span></button>`
}
const actMeta = (files, commits) => [files ? t(files === 1 ? 'act.file1' : 'act.filesN', { n: files }) : '', commits ? t(commits === 1 ? 'act.commit1' : 'act.commitsN', { n: commits }) : ''].filter(Boolean).join(' · ')
2026-11-12 14:03:53 +01:00
function renderActDay() {
const e = actData.days[actDay]
document.getElementById('acDayTitle').textContent = fmtDay(actDay)
document.getElementById('acDay').innerHTML = e?.projects.length
? `<div class="aclist">${e.projects.map((p) => actRow(p.name, actMeta(p.files, p.commits))).join('')}</div>`
: `<div class="hint">${t('act.nothingDay')}</div>`
2026-11-12 14:03:53 +01:00
}
function renderActTop() {
const since = parseDay(actData.today); since.setDate(since.getDate() - actRange + 1)
const agg = new Map()
for (const [k, e] of Object.entries(actData.days)) {
if (parseDay(k) < since) continue
for (const p of e.projects) {
const a = agg.get(p.name) ?? { days: 0, files: 0, commits: 0, last: k }
a.days++; a.files += p.files; a.commits += p.commits; if (k > a.last) a.last = k
agg.set(p.name, a)
}
}
const list = [...agg].sort((a, b) => b[1].days - a[1].days || b[1].last.localeCompare(a[1].last)).slice(0, 15)
document.getElementById('acTop').innerHTML = list.length
? `<div class="aclist">${list.map(([n, a]) => actRow(n, `${t(a.days === 1 ? 'act.day1' : 'act.daysN', { n: a.days })} · ${t('act.lastAgo', { ago: timeAgo(parseDay(a.last).toISOString()) })}`)).join('')}</div>`
: `<div class="hint">${t('act.noChangesRange')}</div>`
2026-11-12 14:03:53 +01:00
}
const acHeat = document.getElementById('acHeat')
const acTip = document.getElementById('acTip')
acHeat.addEventListener('click', (e) => {
const c = e.target.closest('.hc:not(.future)')
if (!c) return
actDay = c.dataset.day
for (const x of acHeat.querySelectorAll('.hc.sel')) x.classList.remove('sel')
c.classList.add('sel')
renderActDay()
})
acHeat.addEventListener('mousemove', (e) => {
const c = e.target.closest('.hc:not(.future)')
if (!c) { acTip.hidden = true; return }
const ev = actData.days[c.dataset.day]
acTip.innerHTML = `<b>${escapeHtml(fmtDay(c.dataset.day))}</b><div class="r"><span>aktive Projekte</span><span>${ev?.projects.length ?? 0}</span></div>` +
(ev ? `<div class="r"><span>Dateien / Commits</span><span>${ev.files} / ${ev.commits}</span></div>` + ev.projects.slice(0, 4).map((p) => `<div class="r"><span>${escapeHtml(p.name)}</span><span>${actMeta(p.files, p.commits)}</span></div>`).join('') : '')
acTip.hidden = false
const card = acHeat.closest('.stcard').getBoundingClientRect()
let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14
if (x + acTip.offsetWidth > card.width - 8) x = e.clientX - card.left - acTip.offsetWidth - 14
acTip.style.left = `${x}px`; acTip.style.top = `${y}px`
})
acHeat.addEventListener('mouseleave', () => { acTip.hidden = true })
for (const id of ['acDay', 'acTop']) {
document.getElementById(id).addEventListener('click', (e) => {
const b = e.target.closest('[data-proj]')
const p = b && projects.find((x) => x.name === b.dataset.proj)
if (p) openEditor(p)
})
}
for (const b of document.querySelectorAll('#acRange button')) b.onclick = () => {
actRange = +b.dataset.range
for (const x of document.querySelectorAll('#acRange button')) x.classList.toggle('active', x === b)
renderActTop()
}
// small heatmap (26 weeks) in a project's Info tab
async function loadProjectActivity(name) {
const box = document.getElementById('actMini')
let a
try { a = await (await fetch(api(name, 'activity'))).json() } catch { return }
if (!box.isConnected || editing?.name !== name) return
const score = (k) => (a.files?.[k] ?? 0) + (a.commits?.[k] ?? 0) * 5
// 0 · 1–4 · 5–19 · 20–59 · 60+ (files + 5 × commits)
const lv = (k) => { const s = score(k); return s <= 0 ? 0 : s < 5 ? 1 : s < 20 ? 2 : s < 60 ? 3 : 4 }
const saved = actData
actData = { today: a.today, days: {} } // heatGrid reads "today" from here
box.innerHTML = `<div class="heat">${heatGrid(26, lv, (k) => `${fmtDay(k)}: ${actMeta(a.files?.[k] ?? 0, a.commits?.[k] ?? 0) || 'nichts'}`)}</div>`
actData = saved
for (const c of box.querySelectorAll('.hc:not(.future)')) c.title = c.getAttribute('aria-label')
const days = new Set([...Object.keys(a.files ?? {}), ...Object.keys(a.commits ?? {})])
const cut = new Date(); cut.setDate(cut.getDate() - 182)
const n = [...days].filter((k) => parseDay(k) >= cut).length
document.getElementById('actMiniInfo').textContent = a.files === null ? 'wird noch gelesen…' : `${n} aktive Tage im letzten halben Jahr`
}
/* ── storage page: treemap, biggest projects, biggest regenerable folders ─ */
let storageData = null
let stPath = [] // [] = all projects · [project] · [project, folder]
let stSelected = new Set()
const TIER_KEYS = ['Cache', 'Release', 'Output']
const TIER_SHORT = { get Cache() { return tierShort('Cache') }, get Release() { return tierShort('Release') }, get Output() { return tierShort('Output') } }
2026-11-12 14:03:53 +01:00
const tierVar = (t) => `var(--t-${t.toLowerCase()})`
const fmtMB1 = (mb) => (mb >= 1024 ? `${(mb / 1024).toLocaleString(I18N.locale(), { maximumFractionDigits: mb >= 10240 ? 0 : 1 })} GB` : `${Math.round(mb).toLocaleString(I18N.locale())} MB`)
2026-11-12 14:03:53 +01:00
async function loadStorage() {
try { storageData = await (await fetch('/api/storage')).json() } catch { return }
// a project that went away (folder switch, rename) leaves the drill-down
if (stPath.length && !storageData.projects.some((p) => p.name === stPath[0])) stPath = []
renderStorage()
}
function renderStorage() {
if (!storageData) return
renderStorageKpis()
renderTreemap()
renderStorageTop()
renderHogs()
}
function renderStorageKpis() {
const ps = storageData.projects
const scanned = ps.filter((p) => p.sizeMB != null)
const total = scanned.reduce((s, p) => s + p.sizeMB, 0)
const del = { Cache: 0, Release: 0, Output: 0 }
for (const p of scanned) for (const t of TIER_KEYS) del[t] += p.deletable?.[t] ?? 0
const delAll = del.Cache + del.Release + del.Output
const oldest = scanned.reduce((o, p) => (!o || p.at < o ? p.at : o), null)
const scan = storageData.scan
const bar = TIER_KEYS.filter((t) => del[t] > 0).map((t) => `<span style="flex:${del[t]};background:${tierVar(t)}" title="${TIER_SHORT[t]}: ${fmtMB1(del[t])}"></span>`).join('') +
(total > delAll ? `<span style="flex:${total - delAll};background:var(--surface-3)"></span>` : '')
const T = window.I18N.t
2026-11-12 14:03:53 +01:00
document.getElementById('stKpis').innerHTML = `
<div class="stkpi"><div class="lbl">${T('st.used')}</div><div class="val">${fmtMB1(total)}</div><div class="sub"><span>${T('st.nMeasured', { n: scanned.length })}</span></div></div>
<div class="stkpi"><div class="lbl">${T('st.cleanable')}</div><div class="val">${fmtMB1(delAll)}</div>
2026-11-12 14:03:53 +01:00
<div class="stbar" aria-hidden="true">${bar}</div>
<div class="sub">${TIER_KEYS.map((k) => `<span class="sttier"><i style="background:${tierVar(k)}"></i>${TIER_SHORT[k]} ${fmtMB1(del[k])}</span>`).join('')}</div></div>
<div class="stkpi"><div class="lbl">${T('st.cleanableShare')}</div><div class="val">${total ? Math.round((delAll / total) * 100) : 0} %</div><div class="sub"><span>${T('st.ofUsed')}</span></div></div>
<div class="stkpi"><div class="lbl">${T('st.measuredCount')}</div><div class="val">${scanned.length} / ${ps.length}</div>
<div class="sub">${scan?.running ? `<span>${ic('loader', 'sm')} ${T('st.runningN', { done: scan.done, total: scan.total })}</span>` : oldest ? `<span>${T('st.oldest', { ago: timeAgo(oldest) })}</span>` : `<span>${T('st.nothingMeasured')}</span>`}</div>
<button class="btn" type="button" id="stScanAll" ${scan?.running ? 'disabled' : ''}>${ic('scan-search')}${T('st.measureAll')}</button></div>`
2026-11-12 14:03:53 +01:00
document.getElementById('stScanAll').onclick = () => startScan()
}
// Squarified treemap (Bruls et al.): items sorted by value, laid out in rows
// along the shorter side so tiles stay close to square. -> [{ item, x, y, w, h }]
function squarify(items, x, y, w, h) {
const out = []
const total = items.reduce((s, it) => s + it.value, 0)
if (!total || w <= 0 || h <= 0) return out
const scale = (w * h) / total
let rest = items.map((it) => ({ it, a: it.value * scale })).filter((r) => r.a > 0)
const worst = (row, side) => {
const s = row.reduce((t, r) => t + r.a, 0)
let max = 0, min = Infinity
for (const r of row) { max = Math.max(max, r.a); min = Math.min(min, r.a) }
return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min))
}
while (rest.length) {
const side = Math.min(w, h)
const row = [rest[0]]
let i = 1
while (i < rest.length && worst([...row, rest[i]], side) <= worst(row, side)) row.push(rest[i++])
rest = rest.slice(i)
const s = row.reduce((t, r) => t + r.a, 0)
if (w >= h) { // column on the left
const cw = s / h
let cy = y
for (const r of row) { const rh = r.a / cw; out.push({ item: r.it, x, y: cy, w: cw, h: rh }); cy += rh }
x += cw; w -= cw
} else { // row on top
const rh = s / w
let cx = x
for (const r of row) { const rw = r.a / rh; out.push({ item: r.it, x: cx, y, w: rw, h: rh }); cx += rw }
y += rh; h -= rh
}
}
return out
}
// cleanup info for a path inside a project (rel = "Library" or "android\app")
function tierInfo(p, rel) {
const full = rel ? `${p.folder}\\${rel}` : p.folder
const exact = p.candidates.find((c) => !c.skip && c.path.toLowerCase() === full.toLowerCase())
const inside = { Cache: 0, Release: 0, Output: 0 }
const pre = (full + '\\').toLowerCase()
for (const c of p.candidates) if (!c.skip && c.path.toLowerCase().startsWith(pre)) inside[c.tier] += c.mb
return { tier: exact?.tier ?? null, inside }
}
const dlStrip = (inside, totalMB) => {
const segs = TIER_KEYS.filter((t) => inside[t] > 0)
if (!segs.length || !totalMB) return ''
// strip width = share of the tile that can go
const share = Math.min(1, segs.reduce((s, t) => s + inside[t], 0) / totalMB)
return `<div class="dl" style="right:${Math.round((1 - share) * 100)}%">${segs.map((t) => `<span style="flex:${inside[t]};background:${tierVar(t)}"></span>`).join('')}</div>`
}
function renderTreemap() {
const box = document.getElementById('stTree')
const W = box.clientWidth, H = box.clientHeight
const ps = storageData.projects
const proj = stPath.length ? ps.find((p) => p.name === stPath[0]) : null
const crumbs = [`<button type="button" data-crumb="0">${t('home.allProjects')}</button>`]
2026-11-12 14:03:53 +01:00
if (proj) crumbs.push(`<span class="sep">›</span>${stPath.length > 1 ? `<button type="button" data-crumb="1">${escapeHtml(proj.name)}</button>` : `<span class="cur">${escapeHtml(proj.name)}</span>`}`)
if (stPath.length > 1) crumbs.push(`<span class="sep">›</span><span class="cur">${escapeHtml(stPath[1])}</span>`)
if (proj) crumbs.push(`<button type="button" data-open title="${t('st.openPanel')}">${ic('panel-right-open', 'sm')}</button>`)
2026-11-12 14:03:53 +01:00
document.getElementById('stCrumbs').innerHTML = crumbs.join('')
document.getElementById('stLegend').innerHTML = TIER_KEYS.map((t) => `<span><i style="background:${tierVar(t)}"></i>${TIER_SHORT[t]}</span>`).join('') + `<span><i style="background:var(--t-rest);outline:1px solid var(--border-strong)"></i>${t('tier.rest')}</span>`
2026-11-12 14:03:53 +01:00
let html = ''
const tile = (r, cls, label, sub, attrs, extra = '') => {
const big = r.w > 46 && r.h > 30
return `<div class="tm ${cls}" style="left:${r.x}px;top:${r.y}px;width:${r.w}px;height:${r.h}px" ${attrs} tabindex="0">
${big ? `<span class="n">${escapeHtml(label)}</span>${r.h > 44 ? `<span class="v">${sub}</span>` : ''}` : ''}${extra}</div>`
}
if (!proj) {
const items = ps.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).map((p) => ({ value: p.sizeMB, p }))
if (!items.length) { box.innerHTML = `<div class="stempty">${t('st.nothingMeasuredHint')}</div>`; return }
2026-11-12 14:03:53 +01:00
const draw = (list, x, y, w, h) => squarify(list, x, y, w, h).map((r) => {
const p = r.item.p
const inside = { Cache: p.deletable?.Cache ?? 0, Release: p.deletable?.Release ?? 0, Output: p.deletable?.Output ?? 0 }
return tile(r, '', p.name, fmtMB1(p.sizeMB), `data-proj="${escapeHtml(p.name)}"`, dlStrip(inside, p.sizeMB))
}).join('')
const groups = multiRoot() ? roots.filter((rt) => activeRoots.includes(rt.id)).map((rt) => ({ rt, list: items.filter((i) => i.p.root === rt.id) })).filter((g) => g.list.length) : []
if (groups.length > 1) {
// one block per projects folder, with its name on top
for (const g of squarify(groups.map((g) => ({ value: g.list.reduce((s, i) => s + i.value, 0), g })), 0, 0, W, H)) {
html += `<div class="tmgroup" style="left:${g.x}px;top:${g.y}px;width:${g.w}px;height:${g.h}px"><span class="gl">${escapeHtml(g.item.g.rt.name)} · ${fmtMB1(g.item.value)}</span></div>`
html += draw(g.item.g.list, g.x + 2, g.y + 18, g.w - 4, g.h - 20)
}
} else html = draw(items, 0, 0, W, H)
} else {
const level = stPath.length > 1 ? proj.tree?.find((c) => c.name === stPath[1])?.children : proj.tree
if (!level?.length) {
box.innerHTML = `<div class="stempty"><div>${proj.sizeMB == null ? t('st.projUnmeasured') : t('st.projRemeasure')}<br><br>
<button class="btn primary" type="button" id="stScanOne">${ic('scan-search')}${proj.sizeMB == null ? t('st.measure') : t('st.remeasure')}</button></div></div>`
2026-11-12 14:03:53 +01:00
document.getElementById('stScanOne').onclick = () => startScan(proj.name)
return
}
const items = level.filter((c) => c.mb > 0).map((c) => ({ value: c.mb, c }))
html = squarify(items, 0, 0, W, H).map((r) => {
const c = r.item.c
const rel = stPath.length > 1 ? `${stPath[1]}\\${c.name}` : c.name
const info = c.files || c.merged ? { tier: null, inside: { Cache: 0, Release: 0, Output: 0 } } : tierInfo(proj, rel)
const drill = stPath.length === 1 && c.children?.length > 1
const cls = `${info.tier ? `t-${info.tier}` : ''} ${drill ? '' : 'flat'}`
return tile(r, cls, c.name, fmtMB1(c.mb), `data-rel="${escapeHtml(rel)}" data-name="${escapeHtml(c.name)}" ${drill ? 'data-drill' : ''}`, info.tier ? '' : dlStrip(info.inside, c.mb))
}).join('')
}
box.innerHTML = html
}
// tooltip + clicks on the treemap
const stTree = document.getElementById('stTree')
const stTip = document.getElementById('stTip')
stTree.addEventListener('mousemove', (e) => {
const t = e.target.closest('.tm')
if (!t) { stTip.hidden = true; return }
const ps = storageData?.projects ?? []
let html = ''
if (t.dataset.proj) {
const p = ps.find((x) => x.name === t.dataset.proj)
const d = p.deletable ?? {}
const T = window.I18N.t
html = `<b>${escapeHtml(p.name)}</b><div class="r"><span>${T('st.size')}</span><span>${fmtMB1(p.sizeMB)}</span></div>` +
2026-11-12 14:03:53 +01:00
TIER_KEYS.filter((k) => d[k] > 0).map((k) => `<div class="r"><span>${TIER_SHORT[k]}</span><span>${fmtMB1(d[k])}</span></div>`).join('') +
(multiRoot() ? `<div class="r"><span>${T('st.folder')}</span><span>${escapeHtml(p.rootName)}</span></div>` : '') +
`<div class="r"><span>${T('st.measured')}</span><span>${timeAgo(p.at)}</span></div>`
2026-11-12 14:03:53 +01:00
} else {
const T = window.I18N.t
2026-11-12 14:03:53 +01:00
const proj = ps.find((x) => x.name === stPath[0])
const level = stPath.length > 1 ? proj.tree.find((c) => c.name === stPath[1]).children : proj.tree
const c = level.find((x) => x.name === t.dataset.name)
const info = c.files || c.merged ? null : tierInfo(proj, t.dataset.rel)
html = `<b>${escapeHtml(t.dataset.rel)}</b><div class="r"><span>${T('st.size')}</span><span>${fmtMB1(c.mb)}</span></div>` +
(info?.tier ? `<div class="r"><span>${T('st.deletable')}</span><span>${TIER_SHORT[info.tier]}</span></div>` : '') +
(info ? TIER_KEYS.filter((k) => info.inside[k] > 0).map((k) => `<div class="r"><span>${T('st.inside', { s: TIER_SHORT[k] })}</span><span>${fmtMB1(info.inside[k])}</span></div>`).join('') : '') +
(t.hasAttribute('data-drill') ? `<div class="r"><span>${T('st.clickSub')}</span><span></span></div>` : '')
2026-11-12 14:03:53 +01:00
}
stTip.innerHTML = html
stTip.hidden = false
const card = stTree.parentElement.getBoundingClientRect()
let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14
if (x + stTip.offsetWidth > card.width - 8) x = e.clientX - card.left - stTip.offsetWidth - 14
if (y + stTip.offsetHeight > card.height - 8) y = e.clientY - card.top - stTip.offsetHeight - 14
stTip.style.left = `${x}px`; stTip.style.top = `${y}px`
})
stTree.addEventListener('mouseleave', () => { stTip.hidden = true })
const stDrill = (t) => {
if (!t) return
if (t.dataset.proj) stPath = [t.dataset.proj]
else if (t.hasAttribute('data-drill')) stPath = [stPath[0], t.dataset.name]
else return
stTip.hidden = true
renderTreemap()
}
stTree.addEventListener('click', (e) => stDrill(e.target.closest('.tm')))
stTree.addEventListener('keydown', (e) => { if (e.key === 'Enter') stDrill(e.target.closest('.tm')) })
document.getElementById('stCrumbs').addEventListener('click', (e) => {
const b = e.target.closest('button')
if (!b) return
if (b.hasAttribute('data-open')) { const p = projects.find((x) => x.name === stPath[0]); if (p) { openEditor(p); setSection?.('info') } return }
stPath = stPath.slice(0, +b.dataset.crumb)
renderTreemap()
})
new ResizeObserver(() => { if (activeView === 'storage' && storageData) renderTreemap() }).observe(stTree)
function renderStorageTop() {
const top = storageData.projects.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).slice(0, 10)
const max = top[0]?.sizeMB ?? 1
document.getElementById('stTop').innerHTML = top.length ? `<div class="sttop">${top.map((p) => {
const d = p.deletable ?? {}
const del = TIER_KEYS.reduce((s, t) => s + (d[t] ?? 0), 0)
const segs = TIER_KEYS.filter((t) => d[t] > 0).map((t) => `<span style="flex:${d[t]};background:${tierVar(t)}"></span>`).join('') +
(p.sizeMB > del ? `<span class="rest" style="flex:${p.sizeMB - del}"></span>` : '')
return `<button type="button" data-proj="${escapeHtml(p.name)}" title="${escapeHtml(p.name)}: ${fmtMB1(p.sizeMB)}${del ? t('st.ofCleanable', { size: fmtMB1(del) }) : ''}">
2026-11-12 14:03:53 +01:00
<span class="row"><b>${escapeHtml(p.name)}</b><span>${fmtMB1(p.sizeMB)}</span></span>
<span class="track" style="width:${Math.max(2, (p.sizeMB / max) * 100)}%">${segs}</span></button>`
}).join('')}</div>` : `<div class="hint">${t('st.nothingMeasured2')}</div>`
2026-11-12 14:03:53 +01:00
}
document.getElementById('stTop').addEventListener('click', (e) => {
const b = e.target.closest('[data-proj]')
if (!b) return
stPath = [b.dataset.proj]
renderTreemap()
document.getElementById('stTree').scrollIntoView({ block: 'nearest', behavior: 'smooth' })
})
// global list of regenerable folders, biggest first
function renderHogs() {
const can = storageData.cleanupAvailable
const rows = storageData.projects.flatMap((p) => p.candidates.filter((c) => !c.skip).map((c) => ({ ...c, p })))
.sort((a, b) => b.mb - a.mb).slice(0, 30)
const keyOf = (r) => `${r.p.name}|${r.path}`
// first render: Cache preselected (always regenerable)
if (!renderHogs.done) { for (const r of rows) if (r.tier === 'Cache') stSelected.add(keyOf(r)); renderHogs.done = true }
for (const k of [...stSelected]) if (!rows.some((r) => keyOf(r) === k)) stSelected.delete(k)
document.getElementById('stHogs').innerHTML = rows.length
? `<thead><tr>${can ? '<th style="width:28px"></th>' : ''}<th>${t('col.project')}</th><th>${t('st.folder')}</th><th>${t('st.kind')}</th><th class="num">${t('st.size')}</th></tr></thead>
2026-11-12 14:03:53 +01:00
<tbody>${rows.map((r) => `<tr data-k="${escapeHtml(keyOf(r))}">
${can ? `<td><input type="checkbox" ${stSelected.has(keyOf(r)) ? 'checked' : ''} aria-label="${t('st.select')}"></td>` : ''}
2026-11-12 14:03:53 +01:00
<td>${escapeHtml(r.p.name)}</td>
2026-11-12 20:23:53 +01:00
<td class="path">${escapeHtml(inProject(r.path, r.p.folder))}</td>
<td><span class="sttier" title="${r.tier ? tierHint(r.tier) : ''}"><i style="background:${tierVar(r.tier)}"></i>${TIER_SHORT[r.tier]}</span></td>
2026-11-12 14:03:53 +01:00
<td class="num">${fmtMB1(r.mb)}</td></tr>`).join('')}</tbody>`
: `<tbody><tr><td class="hint">${t('st.nothingToClean')}</td></tr></tbody>`
2026-11-12 14:03:53 +01:00
updateHogSel(rows)
renderHogs.rows = rows
}
function updateHogSel(rows = renderHogs.rows ?? []) {
const sel = rows.filter((r) => stSelected.has(`${r.p.name}|${r.path}`))
const mb = sel.reduce((s, r) => s + r.mb, 0)
document.getElementById('stSel').textContent = sel.length ? t('st.selected', { n: sel.length, size: fmtMB1(mb) }) : storageData?.cleanupAvailable ? '' : t('st.needCleanup')
2026-11-12 14:03:53 +01:00
document.getElementById('stDelete').disabled = !sel.length
}
document.getElementById('stHogs').addEventListener('click', (e) => {
const tr = e.target.closest('tr[data-k]')
if (!tr || !storageData?.cleanupAvailable) return
const cb = tr.querySelector('input')
if (e.target !== cb) cb.checked = !cb.checked
if (cb.checked) stSelected.add(tr.dataset.k); else stSelected.delete(tr.dataset.k)
updateHogSel()
})
document.getElementById('stDelete').onclick = async () => {
const sel = (renderHogs.rows ?? []).filter((r) => stSelected.has(`${r.p.name}|${r.path}`))
if (!sel.length) return
const mb = sel.reduce((s, r) => s + r.mb, 0)
if (!confirm(t('st.confirmDelete', { n: sel.length, size: fmtMB1(mb) }) + '\n\n' + sel.map((r) => `${r.p.name}: ${inProject(r.path, r.p.folder)}`).join('\n') + '\n\n' + t('st.regenHint'))) return
2026-11-12 14:03:53 +01:00
const btn = document.getElementById('stDelete')
btn.disabled = true
btn.innerHTML = `${ic('loader')}${t('st.deleting')}`
2026-11-12 14:03:53 +01:00
const byProject = new Map()
for (const r of sel) byProject.set(r.p.name, [...(byProject.get(r.p.name) ?? []), r.path])
let failed = 0
for (const [name, paths] of byProject) {
try { await postJson(api(name, 'clean'), { paths }) } catch (e) { failed++; toast(`${name}: ${e.message}`, 'triangle-alert') }
}
stSelected.clear()
btn.innerHTML = `${ic('trash')}${t('st.deleteSelected')}`
if (!failed) toast(t('st.freed', { size: fmtMB1(mb) }), 'brush-cleaning')
2026-11-12 14:03:53 +01:00
await loadStorage()
load()
2026-11-12 09:32:23 +01:00
}
/* ── tasks view (all projects) ────────────────────────────────────────── */
let taskMode = 'open' // open | done | all
const STATUS_ORDER = { active: 0, paused: 1, idea: 2, done: 3, archived: 4 }
const newTaskId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
// Saves a project's full task list; the UI updates first, a failure reloads.
async function saveTasks(p, tasks) {
p.tasks = tasks
renderTasks()
updateTaskCount()
if (!(await patchProject(p.name, { tasks }))) { toast(t('err.saveFailed'), 'triangle-alert'); load() }
2026-11-12 09:32:23 +01:00
}
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' ? t('tasks.noOpen') : t('tasks.noneFound')}</div>
<div class="hint">${t('tasks.addHint')}</div></div>`
2026-11-12 09:32:23 +01:00
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="${t('tasks.openProject')}">${avatar(p)}<b>${escapeHtml(p.name)}</b>${statusHtml(p.status)}<span class="cnt">${done}/${all.length}</span></div>
2026-11-12 09:32:23 +01:00
<div class="progress"><div style="width:${all.length ? Math.round((done / all.length) * 100) : 0}%"></div></div>
${tasks.map((x) => `<div class="titem ${x.done ? 'done' : ''}" data-id="${escapeHtml(x.id)}">
<input type="checkbox" ${x.done ? 'checked' : ''}><span>${escapeHtml(x.text)}</span>
<button class="del" title="${t('common.delete')}">${ic('trash', 'sm')}</button></div>`).join('')}
<div class="tg-add"><input type="text" placeholder="${t('tasks.addFor', { name: escapeHtml(p.name) })}"></div>
2026-11-12 09:32:23 +01:00
</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(t('tasks.added', { name: p.name }), 'list-checks')
2026-11-12 09:32:23 +01:00
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"
2026-11-12 20:23:53 +01:00
// (projects in subfolders: folder is "Sammel\A", so strip the whole folder, not up to the first \)
const inProject = (p, folder) => {
const pre = folder ? `${folder}\\` : ''
return pre && p.toLowerCase().startsWith(pre.toLowerCase()) ? p.slice(pre.length) : p.slice(p.indexOf('\\') + 1)
}
2026-11-12 09:32:23 +01:00
2026-11-12 15:58:44 +01:00
// opts: { id } for jump targets, { right } html at the end of the heading
function section(icon, title, body, opts = {}) {
2026-11-12 20:58:18 +01:00
return `<div class="card-sec${opts.adv ? ' adv' : ''}"${opts.id ? ` id="${opts.id}"` : ''}><h4>${ic(icon)}${title}${opts.right ? `<span class="h4r">${opts.right}</span>` : ''}</h4>${body}</div>`
2026-11-12 15:58:44 +01:00
}
// "→ in Aktionen": switches the tab and scrolls to the section
const jumpLink = (id, label = 'Aktionen') => `<a href="#" class="jump" data-jump="${id}">${label}${ic('arrow-right', 'sm')}</a>`
function bindJumps(root) {
for (const a of root.querySelectorAll('.jump')) a.onclick = (e) => {
e.preventDefault()
setSection('actions')
document.getElementById(a.dataset.jump)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
2026-11-12 09:32:23 +01:00
}
2026-11-12 15:58:44 +01:00
/* Info tab: read only - what the project is and how it stands */
2026-11-12 09:32:23 +01:00
function renderInfo(name, d) {
2026-11-12 15:58:44 +01:00
const p = projects.find((x) => x.name === name) ?? editing
2026-11-12 09:32:23 +01:00
const g = d.git
2026-11-12 15:58:44 +01:00
const s = d.storage
const del = s ? s.deletable.Cache + s.deletable.Release + s.deletable.Output : 0
const c = cloudInfo(p)
const overview = `<div class="kv">
<div>${t('info.folder')}</div><div><code>${escapeHtml(d.path)}</code></div>
<div class="adv">${t('panel.status')}</div><div class="adv">${statusHtml(p.status)} <span class="hint">· ${t('prio.titled', { p: p.priority ? t('prio.' + p.priority) : '–' })}</span></div>
<div>${t('info.changed')}</div><div title="${escapeHtml(changeTitle(p))}">${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))}${p.lastChange?.file ? ` <span class="hint">· ${escapeHtml(p.lastChange.file)}</span>` : ''}</div>
<div>${t('btn.backup')}</div><div title="${escapeHtml(c.label)}"><span class="bk ${c.level}">${ic('hard-drive', 'sm')}${escapeHtml(c.short)}</span>${backupDue(p) ? ` <span class="chip warn">${t('info.due')}</span>` : ''}</div>
<div>${t('st.size')}</div><div>${s ? `<b>${fmtMB(s.sizeMB)}</b> <span class="hint">· ${t('info.scannedAgo', { ago: timeAgo(s.at) })}${del >= 1 ? ` · ${fmtMB(del)} ${t('size.cleanableWord')}` : ''}</span>` : `<span class="hint">${t('kpi.notScanned')}</span>`}</div>
2026-11-12 15:58:44 +01:00
</div>`
2026-11-12 09:32:23 +01:00
const gitBody = g.isRepo
? `<div class="kv">
<div>${t('panel.status')}</div><div>${gitHtml(g)}${g.dirty ? ` <span class="hint">· ${t('info.uncommitted', { n: g.dirty })}</span>` : ''}</div>
<div>${t('info.branch')}</div><div>${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}${g.ahead ? ` <span class="hint">· ${t('info.notPushed', { n: g.ahead })}</span>` : ''}</div>
<div>${t('info.remote')}</div><div>${g.remote ? `<code>${escapeHtml(g.remote)}</code>` : `<span class="hint">${t('info.noRemoteShort')}</span>`}</div>
<div>${t('info.lastCommit')}</div><div>${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}</div>
2026-11-12 15:58:44 +01:00
</div>`
: `<div>${gitHtml(g)}</div><div class="hint">${t('info.noRepo')}</div>`
2026-11-12 15:58:44 +01:00
const ip = d.itchPack ?? { exists: false }
const itchBody = `<div class="kv">
<div>${t('info.published')}</div><div>${p.published ? `<a href="${escapeHtml(p.published.url)}" target="_blank">${escapeHtml(p.published.title || p.published.url)}</a>` : `<span class="hint">${t('info.no')}</span>`}</div>
<div>${t('info.pagePack')}</div><div>${ip.exists ? `<code>${escapeHtml(ip.rel)}</code> <span class="hint">· ${timeAgo(ip.at)}</span>` : `<span class="hint">${t('info.noneYet')}</span>`}</div>
2026-11-12 15:58:44 +01:00
</div>`
const arcs = d.archives ?? []
const arcBody = arcs.length
? `<div class="kv">${arcs.slice(0, 8).map((a) => `<div>${new Date(a.at).toLocaleDateString(I18N.locale())}</div><div>${escapeHtml(a.name)} <span class="hint">· ${fmtMB(a.mb)}</span></div>`).join('')}</div>${arcs.length > 8 ? `<div class="hint">${t('info.moreOlder', { n: arcs.length - 8 })}</div>` : ''}`
: `<div class="hint">${t('info.noZips')}</div>`
2026-11-12 09:32:23 +01:00
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')}${t('info.usesComfyGen')}</span>`
: `<span class="chip bad">${ic('copy', 'sm')}${t('info.ownCopy')}</span><div class="hint">${escapeHtml(x.scripts.join(', '))}</div>`}</div>`).join('')}</div>`
: `<div class="hint">${t('info.noGenerator')}</div>`
2026-11-12 09:32:23 +01:00
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')}${t('info.noIconFound')}</span></div>
<div class="hint">${genDir ? t('info.iconComfyGen') : t('info.iconTemplate')}</div>
2026-11-12 09:32:23 +01:00
<code class="cmd">cd "${escapeHtml(d.path)}\\${escapeHtml(genDir ? genDir.rel : 'sprite-generator')}" &amp;&amp; gen generate icon &amp;&amp; gen adopt icon</code>`
2026-11-12 19:50:38 +01:00
// description: own text (.dashboard.json), else the README's intro as a suggestion
const desc = p.description ?? ''
const descBody = desc
? `<div class="pdesc">${escapeHtml(desc)}</div>`
: d.readme
? `<div class="pdesc muted">${escapeHtml(d.readme)}</div>
<div class="hint">${ic('file-text', 'sm')} ${t('desc.fromReadme')}
<button class="btn ghost" type="button" id="btnDescTake">${ic('check', 'sm')}${t('common.apply')}</button></div>`
: `<div class="hint" style="margin-top:0">${t('desc.none')}</div>`
2026-11-12 19:50:38 +01:00
const descEdit = `<div class="pdesc-edit" hidden>
<textarea id="fDesc" rows="6" maxlength="4000" placeholder="${t('desc.placeholder')}"></textarea>
2026-11-12 19:50:38 +01:00
<div class="actgroup" style="margin-top:8px">
<button class="btn primary" type="button" id="btnDescSave">${ic('check')}${t('common.save')}</button>
<button class="btn" type="button" id="btnDescCancel">${t('common.cancel')}</button>
${d.readme ? `<button class="btn ghost" type="button" id="btnDescReadme" title="${t('desc.insertReadme')}">${ic('file-text')}${t('desc.fromReadmeBtn')}</button>` : ''}
<span class="hint" style="margin:0 0 0 auto">${t('desc.ctrlEnter')}</span>
2026-11-12 19:50:38 +01:00
</div>
</div>`
// README rendered as markdown (collapsible; open by default when short)
const readmeCard = d.readmeFull
? `<details class="card-sec mdcard" id="info-readme"${d.readmeFull.length < 1500 ? ' open' : ''}>
<summary><h4>${ic('book-open')}README</h4>${ic('chevron-down', 'sm')}</summary>
<div class="md">${renderMarkdown(d.readmeFull)}</div>
</details>`
: ''
2026-11-12 15:58:44 +01:00
const el = document.getElementById('sec-info')
el.innerHTML =
section('notebook-text', t('info.description'), `<div class="pdesc-view">${descBody}</div>${descEdit}`,
{ id: 'info-desc', right: `<a href="#" class="jump" id="btnDescEdit">${ic('pencil', 'sm')}${desc ? t('desc.edit') : t('desc.write')}</a>` }) +
readmeCard +
section('info', t('info.overview'), overview, { right: del >= 1 ? `<span class="adv">${jumpLink('act-clean', t('info.cleanUp'))}</span>` : '' }) +
section('git-branch', 'Git', gitBody, { adv: true, right: jumpLink('act-git', g.isRepo ? t('info.pushRemote') : t('set.setup')) }) +
(name === '_Tools' || !itchOn() ? '' : section('rocket', 'itch.io', itchBody, { adv: true, right: jumpLink('act-itch', ip.exists ? t('info.view') : t('info.generate')) })) +
section('cpu', t('info.tech'), `<div class="chips">${techChips(d.tech.types) || `<span class="hint">${t('info.notDetected')}</span>`}${d.tech.needsInstall ? `<span class="chip warn">${ic('download', 'sm')}${t('info.npmNeeded')}</span>` : ''}</div>`, { adv: true }) +
`<div class="card-sec"><h4>${ic('activity')}${t('tab.activity')} <span class="hint" style="font-weight:400;margin:0 0 0 auto" id="actMiniInfo"></span></h4><div id="actMini" class="hmini"><span class="hint">${t('info.loading')}</span></div></div>` +
section('file-archive', t('info.releaseArchives'), arcBody, { adv: true, right: jumpLink('act-zip', t('info.makeZip')) }) +
section('wand-sparkles', t('info.generator'), genBody, { adv: true }) +
section('image', t('info.appIcon'), iconBody, { adv: true })
2026-11-12 15:58:44 +01:00
bindJumps(el)
2026-11-12 19:50:38 +01:00
bindDescription(name, d, el)
2026-11-12 15:58:44 +01:00
loadProjectActivity(name)
}
2026-11-12 19:50:38 +01:00
function bindDescription(name, d, el) {
const view = el.querySelector('.pdesc-view')
const edit = el.querySelector('.pdesc-edit')
const ta = document.getElementById('fDesc')
const link = document.getElementById('btnDescEdit')
const open = (text) => {
ta.value = text
view.hidden = true
edit.hidden = false
link.style.visibility = 'hidden'
ta.focus()
}
const close = () => { view.hidden = false; edit.hidden = true; link.style.visibility = '' }
const save = async (text) => {
try {
const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: text }),
})
const r = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(r.error ?? t('err.saveFailed'))
2026-11-12 19:50:38 +01:00
for (const p of [editing, projects.find((x) => x.name === name)]) if (p) p.description = r.description
toast(r.description ? t('desc.saved') : t('desc.removed'), 'notebook-text')
2026-11-12 19:50:38 +01:00
if (editing?.name === name) renderInfo(name, d)
} catch (e) { toast(e.message, 'triangle-alert') }
}
link.onclick = (e) => { e.preventDefault(); open(editing?.description || '') }
document.getElementById('btnDescTake')?.addEventListener('click', () => save(d.readme))
document.getElementById('btnDescReadme')?.addEventListener('click', () => { ta.value = ta.value.trim() ? `${ta.value.trim()}\n\n${d.readme}` : d.readme; ta.focus() })
document.getElementById('btnDescCancel').onclick = close
document.getElementById('btnDescSave').onclick = () => save(ta.value)
ta.onkeydown = (e) => {
if (e.key === 'Enter' && e.ctrlKey) { e.preventDefault(); save(ta.value) }
if (e.key === 'Escape') { e.stopPropagation(); close() }
}
}
2026-11-12 15:58:44 +01:00
/* Aktionen tab: everything that does something, grouped */
function gitActionsHtml(name, d) {
const g = d.git
if (!g.isRepo) {
return `<div class="hint" style="margin-top:0">${t('info.noRepo')}</div>
<div style="margin-top:10px"><button class="btn primary" type="button" id="btnGitInit">${ic('git-branch')}${t('git.setup')}</button></div>`
2026-11-12 09:32:23 +01:00
}
2026-11-12 15:58:44 +01:00
const key = d.sshKey
const keyHint = key
? `<div class="hint">${ic('key-round', 'sm')} ${t('git.sshKey')}: <code>${escapeHtml(key.file)}</code> <button class="btn ghost" type="button" id="btnCopyKey" title="${t('git.copyKeyTitle')}">${ic('copy', 'sm')}${t('git.copy')}</button></div>`
: `<div class="hint">${ic('key-round', 'sm')} ${t('git.noSshKey')}</div>`
2026-11-12 15:58:44 +01:00
const pushBox = !g.remote ? '' : g.dirty
? `<div class="pickrow" style="margin-bottom:12px">
<input type="text" id="gMsg" placeholder="${t('git.commitMsg', { n: g.dirty })}" maxlength="200">
<button class="btn primary" type="button" id="btnCommitPush">${ic('cloud-upload')}${t('git.commitPush')}</button>
<button class="btn" type="button" id="btnPush" title="${t('git.pushOnly')}">${ic('upload')}Push</button>
2026-11-12 15:58:44 +01:00
</div>`
: `<div style="margin-bottom:12px"><button class="btn ${g.ahead || !g.upstream ? 'primary' : ''}" type="button" id="btnPush">${ic('cloud-upload')}git push${g.ahead ? ` (${g.ahead})` : ''}</button> <span class="hint">${g.ahead ? '' : t('git.nothingNew')}</span></div>`
2026-11-12 15:58:44 +01:00
return `${pushBox}
<label class="flabel">${ic('link', 'sm')}${t('git.remoteLabel')}</label>
2026-11-12 15:58:44 +01:00
<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')}${t('common.save')}</button>
2026-11-12 15:58:44 +01:00
</div>
${g.remote ? '' : `<div class="hint">${t('git.noRemoteYet')}</div>`}
2026-11-12 15:58:44 +01:00
${keyHint}
<div class="hint">${t('git.pushConsole')}</div>`
2026-11-12 15:58:44 +01:00
}
2026-11-12 09:32:23 +01:00
2026-11-12 15:58:44 +01:00
function archiveHtml(name, d) {
const s = d.storage
2026-11-12 14:03:53 +01:00
const folder = editing?.folder ?? name
2026-11-12 20:23:53 +01:00
const releaseCands = new Set((s?.candidates ?? []).filter((c) => c.Tier === 'Release' && !c.Skip).map((c) => inProject(c.Path, folder).toLowerCase()))
2026-11-12 14:03:53 +01:00
const rd = d.releaseDirs ?? []
2026-11-12 15:58:44 +01:00
return `
2026-11-12 14:03:53 +01:00
<div class="pickrow">
<select id="arcWhat">${rd.map((r) => `<option value="${escapeHtml(r.rel)}" data-del="${releaseCands.has(r.rel.toLowerCase()) ? 1 : ''}">${escapeHtml(r.rel)} · ${fmtMB(r.mb)} · ${t('act.filesN', { n: r.files })}</option>`).join('')}
<option value="project">${t('arc.whole')}</option></select>
<button class="btn primary" type="button" id="btnArc">${ic('file-archive')}${t('info.makeZip')}</button>
<button class="btn ghost" type="button" id="btnArcOpen" title="${t('arc.openDir')}">${ic('folder-open')}</button>
2026-11-12 14:03:53 +01:00
</div>
<label class="chk" id="arcDelWrap" style="margin-top:8px;display:flex;gap:6px;align-items:center;font-size:13px"><input type="checkbox" id="arcDel"> ${t('arc.delAfter')}</label>
<div class="hint">${t('arc.lands', { folder: escapeHtml(folder) })}${rd.length ? '' : t('arc.noBuild')}.</div>`
2026-11-12 15:58:44 +01:00
}
2026-11-12 09:32:23 +01:00
2026-11-12 15:58:44 +01:00
function itchActionHtml(name, d) {
const ip = d.itchPack ?? { exists: false }
const p = projects.find((x) => x.name === name) ?? editing
if (!ip.exists) {
return `<div class="actgroup"><button class="btn primary" type="button" id="btnItchGen">${ic('sparkles')}${t('itchA.generate')}</button></div>
<div class="hint">${t('itchA.generateHint')}</div>`
2026-11-12 14:03:53 +01:00
}
2026-11-12 15:58:44 +01:00
return `<div class="actgroup">
<button class="btn primary" type="button" id="btnItchView">${ic('clipboard-copy')}${t('itchA.viewCopy')}</button>
<button class="btn" type="button" id="btnItchGen" title="${t('itchA.completeTitle')}">${ic('sparkles')}${t('itchA.complete')}</button>
<button class="btn ghost" type="button" id="btnItchOpen" title="${t('dlg.itch.openDir')}">${ic('folder-open')}</button>
${p?.published ? `<a class="btn ghost" href="${escapeHtml(p.published.url)}" target="_blank" title="${t('itchA.openPublished')}">${ic('external-link')}</a>` : ''}
2026-11-12 15:58:44 +01:00
</div>
<div class="hint"><code>${escapeHtml(ip.rel)}</code> · ${t('itchA.lastChanged', { ago: timeAgo(ip.at) })}</div>`
2026-11-12 15:58:44 +01:00
}
2026-11-12 14:03:53 +01:00
2026-11-12 15:58:44 +01:00
function cleanHtml(d) {
const s = d.storage
let body
if (!s) body = `<div class="hint" style="margin-top:0">${t('clean.unscanned')}</div>`
2026-11-12 15:58:44 +01:00
else {
const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip)
body = `<div class="kv"><div>${t('st.size')}</div><div><b>${fmtMB(s.sizeMB)}</b> <span class="hint">· ${t('info.scannedAgo', { ago: timeAgo(s.at) })}</span></div>
<div>${t('st.deletable')}</div><div>Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · ${tierShort('Output')} ${fmtMB(s.deletable.Output)}</div></div>`
2026-11-12 15:58:44 +01:00
body += 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>
2026-11-12 20:23:53 +01:00
<td>${escapeHtml(inProject(c.Path, editing?.folder))}</td>
<td><span class="chip ${TIER[c.Tier].cls}" title="${tierHint(c.Tier)}">${ic(TIER[c.Tier].icon, 'sm')}${tierLabel(c.Tier)}</span>${c.Skip ? ` <span class="chip bad">${ic('lock', 'sm')}${t('clean.inGit')}</span>` : ''}</td>
2026-11-12 15:58:44 +01:00
<td class="mb">${fmtMB(c.MB)}</td></tr>`).join('')}</table>
<div class="hint">${t('clean.cacheHint')}</div>`
: `<div class="hint">${ic('sparkles', 'sm')} ${t('clean.nothing')}</div>`
2026-11-12 09:32:23 +01:00
}
2026-11-12 15:58:44 +01:00
const hasRows = s && s.candidates.some((c) => c.MB >= 1 && !c.Skip)
body += `<div class="actgroup" style="margin-top:10px">
${hasRows ? `<button class="btn danger" id="btnClean">${ic('trash')}${t('st.deleteSelected')}</button>` : ''}
<button class="btn" id="btnScanOne" ${!cleanupAvailable || scanState?.running ? 'disabled' : ''}>${ic('scan-search')}${s ? t('clean.rescan') : t('clean.scan')}</button>
2026-11-12 15:58:44 +01:00
</div>`
return body
2026-11-12 09:32:23 +01:00
}
function renderActions(name, d) {
const groups = {}
for (const a of d.actions) (groups[a.group] ??= []).push(a)
const ACT_ICON = (a) => a.id === 'vscode' ? 'code-xml' : a.id === 'explorer' ? 'folder-open' : a.id === 'console' ? 'square-terminal'
: a.id.startsWith('unity') ? 'box' : a.id.startsWith('exe:') ? 'app-window' : a.id.startsWith('bat:') ? 'file-terminal' : a.id === 'web' ? 'globe' : a.id.startsWith('gen:') ? 'wand-sparkles'
: a.id.startsWith('npm-install') ? 'download' : ACTION_ICON[a.group]
// the project's own programs (exe + html pages) come first, as big start buttons;
// the pin chooses which one the ▶ on the cards starts
const programs = groups['Programm'] ?? []
const hasBuild = !!groups['Bauen']
const prog = d.program // { rel, missing } or null
const progHtml = (programs.length
? `<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 ? t('prog.unpin') : t('prog.pin')}">${ic('pin', 'sm')}</button>` : ''}
2026-11-12 09:32:23 +01:00
</div>`
}).join('')}</div>`
: `<div class="hint" style="margin-top:0">${t('prog.noneFound')}${hasBuild ? ' ' + t('prog.buildFirst') : ''}</div>`)
+ (prog?.missing ? `<div class="hint warn">${ic('triangle-alert', 'sm')} ${t('prog.missing', { rel: escapeHtml(prog.rel) })}</div>` : '')
2026-11-12 20:58:18 +01:00
+ `<details class="progset adv"${prog?.missing ? ' open' : ''}>
<summary>${ic('pin', 'sm')}${t('prog.setForPlay')}${prog ? `: <b>${escapeHtml(prog.rel)}</b>` : ' ' + t('prog.automatic')}</summary>
2026-11-12 09:32:23 +01:00
<div class="pickrow">
<input type="text" id="fProgram" placeholder="${t('prog.placeholder')}" value="${escapeHtml(prog?.rel ?? '')}">
${hasPicker ? `<button class="btn" type="button" id="btnPickProgram">${ic('file-search')}${t('common.browse')}</button>` : ''}
<button class="btn primary" type="button" id="btnSetProgram">${ic('check')}${t('prog.set')}</button>
${prog ? `<button class="btn ghost" type="button" id="btnClearProgram" title="${t('prog.auto')}">${ic('rotate-ccw')}</button>` : ''}
2026-11-12 09:32:23 +01:00
</div>
<div class="hint">${t('prog.pathHint')}</div>
2026-11-12 15:58:44 +01:00
</details>`
// server group names (keys) → display labels
const actGroupLabel = (g) => ({ Programm: t('act.g.program'), Starten: t('act.g.start'), Einrichten: t('set.setup'), Bauen: t('act.g.build'), Werkzeuge: t('act.g.tools'), 'Öffnen': t('act.g.open') }[g] ?? g)
2026-11-12 15:58:44 +01:00
const btnGroup = (g) => groups[g]
? section(ACTION_ICON[g], actGroupLabel(g), `<div class="actgroup">${groups[g].map((a) =>
2026-11-12 20:58:18 +01:00
`<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>`, { adv: !['Starten', 'Öffnen'].includes(g) })
2026-11-12 15:58:44 +01:00
: ''
const head = (icon, title) => `<div class="agroup-h">${ic(icon, 'sm')}${title}</div>`
const tools = name === '_Tools'
2026-11-12 09:32:23 +01:00
projectLastBackup = d.lastBackup ?? null
projectTargets = d.backupTargets ?? []
2026-11-12 15:58:44 +01:00
const el = document.getElementById('sec-actions')
el.innerHTML =
head('play', t('act.g.start'))
+ section('app-window', t('act.g.program'), progHtml)
2026-11-12 15:58:44 +01:00
+ btnGroup('Starten') + btnGroup('Einrichten') + btnGroup('Bauen')
+ head('shield-check', t('act.h.save'))
2026-11-12 20:58:18 +01:00
+ section('git-branch', 'Git', gitActionsHtml(name, d), { id: 'act-git', adv: true })
+ (tools ? '' : section('hard-drive-upload', t('btn.backup'), '<div id="pbackupBody"></div>', { id: 'act-backup' }))
+ head('rocket', t('act.h.publish'))
+ section('file-archive', t('act.releaseZip'), archiveHtml(name, d), { id: 'act-zip', adv: true })
+ (tools || !itchOn() ? '' : section('rocket', t('dlg.itch.title'), itchActionHtml(name, d), { id: 'act-itch', adv: true }))
+ head('brush-cleaning', t('info.cleanUp'))
+ section('hard-drive', t('tab.storage'), cleanHtml(d), { id: 'act-clean', adv: true })
+ (groups['Werkzeuge'] || groups['Öffnen'] ? head('wrench', t('act.g.tools')) + btnGroup('Werkzeuge') + btnGroup('Öffnen') : '')
+ `<div class="hint adv" style="margin-top:12px">${ic('shield-check', 'sm')} ${t('act.consoleHint')}</div>`
+ (tools ? '' : head('triangle-alert', t('danger.title'))
+ `<div class="card-sec adv dangerzone"><div class="hint" style="margin-top:0">${t('danger.hint')}</div>
<div class="actgroup" style="margin-top:10px"><button class="btn danger" id="btnDeleteProject">${ic('trash')}${t('danger.deleteFolder')}</button></div></div>`)
document.getElementById('btnDeleteProject')?.addEventListener('click', () => deleteProject(name, d))
2026-11-12 15:58:44 +01:00
for (const btn of el.querySelectorAll('.act')) btn.onclick = () => runAction(name, btn.dataset.id)
for (const btn of el.querySelectorAll('.pin')) btn.onclick = () => setProgram(name, btn.dataset.rel)
2026-11-12 09:32:23 +01:00
const input = document.getElementById('fProgram')
document.getElementById('btnSetProgram').onclick = () => setProgram(name, input.value)
input.onkeydown = (e) => { if (e.key === 'Enter') setProgram(name, input.value) }
document.getElementById('btnClearProgram')?.addEventListener('click', () => setProgram(name, ''))
document.getElementById('btnPickProgram')?.addEventListener('click', async () => {
const file = await pickFile(t('prog.pickFor', { name }), d.path)
2026-11-12 09:32:23 +01:00
if (file) setProgram(name, file)
})
2026-11-12 15:58:44 +01:00
bindGit(name, d)
bindArchive(name)
bindItch(name)
bindClean(name, d)
2026-11-12 09:32:23 +01:00
renderProjectBackup(name)
if (!backup) loadBackup()
}
2026-11-12 15:58:44 +01:00
function bindGit(name, d) {
const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn }
const refreshInfo = () => { load(); loadDetails(name) }
on('btnPush', async () => {
try { await postJson(api(name, 'push')); toast(t('git.pushRunning'), 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') }
2026-11-12 15:58:44 +01:00
})
on('btnCommitPush', async () => {
const msg = document.getElementById('gMsg').value.trim()
if (!msg) { document.getElementById('gMsg').focus(); return toast(t('git.enterMsg'), 'info') }
try { await postJson(api(name, 'push'), { message: msg }); toast(t('git.commitPushRunning'), 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') }
2026-11-12 15:58:44 +01:00
})
on('btnRemote', async () => {
try { await postJson(api(name, 'remote'), { url: document.getElementById('gRemote').value }); toast(t('git.remoteSaved'), 'link'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') }
2026-11-12 15:58:44 +01:00
})
const rem = document.getElementById('gRemote')
if (rem) rem.onkeydown = (e) => { if (e.key === 'Enter') document.getElementById('btnRemote').click() }
on('btnGitInit', async () => {
try { await postJson(api(name, 'git-init')); toast(t('git.initDone'), 'git-branch'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') }
2026-11-12 15:58:44 +01:00
})
on('btnCopyKey', async () => {
try { await navigator.clipboard.writeText(d.sshKey.key); toast(t('git.keyCopied'), 'copy') } catch { toast(t('err.copyFailed'), 'triangle-alert') }
2026-11-12 15:58:44 +01:00
})
}
function bindArchive(name) {
const arcSel = document.getElementById('arcWhat')
const syncArc = () => { document.getElementById('arcDelWrap').style.display = arcSel.selectedOptions[0]?.dataset.del ? '' : 'none' }
arcSel.onchange = syncArc
syncArc()
document.getElementById('btnArc').onclick = async (e) => {
const btn = e.currentTarget
const what = arcSel.value
const del = document.getElementById('arcDel').checked && !!arcSel.selectedOptions[0]?.dataset.del
if (del && !confirm(t('arc.confirmDel', { what }))) return
2026-11-12 15:58:44 +01:00
btn.disabled = true
btn.innerHTML = `${ic('loader')}${t('arc.packing')}`
2026-11-12 15:58:44 +01:00
try {
const r = await postJson(api(name, 'archive'), { what, deleteAfter: del })
toast(`${r.name} (${fmtMB(r.mb)})${r.deleted ? ' – ' + t('arc.buildDeleted') : ''}`, 'file-archive')
2026-11-12 15:58:44 +01:00
loadDetails(name)
if (r.deleted) load()
} catch (ex) {
toast(ex.message, 'triangle-alert')
btn.disabled = false
btn.innerHTML = `${ic('file-archive')}${t('info.makeZip')}`
2026-11-12 15:58:44 +01:00
}
}
document.getElementById('btnArcOpen').onclick = () => postJson(api(name, 'archive/open')).catch((ex) => toast(ex.message, 'triangle-alert'))
}
function bindItch(name) {
document.getElementById('btnItchGen')?.addEventListener('click', async () => {
try {
const r = await postJson(api(name, 'itch/generate'))
toast(r.update ? t('itchA.checking') : t('itchA.creating'), 'sparkles')
2026-11-12 15:58:44 +01:00
} catch (e) { toast(e.message, 'triangle-alert') }
})
document.getElementById('btnItchView')?.addEventListener('click', () => openItch(name))
document.getElementById('btnItchOpen')?.addEventListener('click', () => postJson(api(name, 'itch/open')).catch((e) => toast(e.message, 'triangle-alert')))
}
function bindClean(name, d) {
const s = d.storage
document.getElementById('btnScanOne').onclick = () => startScan(name)
const clean = document.getElementById('btnClean')
if (clean) clean.onclick = async () => {
const paths = [...document.querySelectorAll('.candcb:checked')].map((cb) => cb.dataset.path)
if (!paths.length) return toast(t('import.nothingSelected'))
2026-11-12 15:58:44 +01:00
const mb = s.candidates.filter((c) => paths.includes(c.Path)).reduce((a, c) => a + c.MB, 0)
if (!confirm(t('clean.confirmDel', { n: paths.length, size: fmtMB(mb), name }) + '\n\n' + paths.map((x) => inProject(x, editing?.folder)).join('\n'))) return
2026-11-12 15:58:44 +01:00
clean.disabled = true
clean.innerHTML = `${ic('loader')}${t('st.deleting')}`
2026-11-12 15:58:44 +01:00
try {
const r = await postJson(api(name, 'clean'), { paths })
toast(t('clean.result', { n: r.deleted.length, gb: String(r.freedGB).replace('.', ',') }) + (r.failed.length ? ' · ' + t('clean.locked', { n: r.failed.length }) : ''), 'brush-cleaning')
2026-11-12 15:58:44 +01:00
await load()
loadDetails(name)
} catch (e) { toast(e.message, 'triangle-alert'); clean.disabled = false; clean.innerHTML = `${ic('trash')}${t('st.deleteSelected')}` }
2026-11-12 15:58:44 +01:00
}
}
2026-11-12 20:23:53 +01:00
/* ── projects in subfolders (scanner, lib/nested.js) ──────────────────── */
let nestData = null
let nestDeep = false
async function openNested(deep = false) {
const dlg = document.getElementById('nestDlg')
nestDeep = deep
// keep what was ticked before a re-scan (deep)
const prev = new Map([...document.querySelectorAll('#nestBody input[data-rel]')].map((cb) => [`${cb.dataset.root}|${cb.dataset.rel}`, cb.checked]))
document.getElementById('nestBody').innerHTML = `<div class="hint">${ic('loader', 'sm')} ${t('nest.searching')}</div>`
2026-11-12 20:23:53 +01:00
document.getElementById('nestDeep').hidden = deep
if (!dlg.open) dlg.showModal()
try {
const r = await fetch(`/api/nested/scan${deep ? '?deep=1' : ''}`)
nestData = await r.json()
if (!r.ok) throw new Error(nestData.error)
renderNested(dlg.open && deep ? prev : new Map())
} catch (e) {
document.getElementById('nestBody').innerHTML = `<div class="hint">${t('nest.error')}: ${escapeHtml(e.message)}</div>`
2026-11-12 20:23:53 +01:00
}
}
function renderNested(prev) {
const item = (root, x, preset) => {
const k = `${root.id}|${x.rel}`
const on = prev.has(k) ? prev.get(k) : preset
const parts = x.rel.split('\\')
return `<label class="nitem">
<input type="checkbox" data-root="${escapeHtml(root.id)}" data-rel="${escapeHtml(x.rel)}" ${on ? 'checked' : ''}>
<span class="nrel" title="${escapeHtml(root.path)}\\${escapeHtml(x.rel)}"><span class="hint" style="margin:0">${escapeHtml(parts.slice(0, -1).join('\\'))}\\</span><b>${escapeHtml(parts.at(-1))}</b></span>
${x.markers.slice(0, 4).map((m) => `<span class="chip tech">${escapeHtml(m === '.NET-sln' ? '.NET' : m === 'dashboard' ? 'Dashboard' : m)}</span>`).join('')}
${x.chosen ? `<span class="chip ok">${t('nest.chosen')}</span>` : x.ignored ? `<span class="chip neutral">${t('nest.ignored')}</span>` : `<span class="chip warn">${t('nest.new')}</span>`}
2026-11-12 20:23:53 +01:00
</label>`
}
const roots = nestData.roots ?? []
const html = roots.map((r) => {
const groups = r.containers.map((c) => `<div class="ngroup">
<div class="nghead">${ic('folder', 'sm')}${escapeHtml(c.rel)}<span class="hint">${t('nest.collection')}</span></div>
2026-11-12 20:23:53 +01:00
${c.projects.map((x) => item(r, x, x.chosen || !x.ignored)).join('')}
</div>`).join('')
const inner = r.inProjects.length ? `<div class="ngroup">
<div class="nghead">${ic('folder-git-2', 'sm')}${t('nest.inProjects')}<span class="hint">${t('nest.inProjectsHint')}</span></div>
2026-11-12 20:23:53 +01:00
${r.inProjects.map((x) => item(r, x, x.chosen)).join('')}
</div>` : ''
const n = r.containers.reduce((a, c) => a + c.projects.length, 0) + r.inProjects.length
return `<div class="nroot"><h4>${ic('folders')}${escapeHtml(r.name)} <span class="hint">${escapeHtml(r.path)} · ${t('nest.nFound', { n })}</span></h4>
${groups + inner || `<div class="hint">${nestDeep ? t('nest.noneDeep') : t('nest.none')}</div>`}</div>`
2026-11-12 20:23:53 +01:00
}).join('')
document.getElementById('nestBody').innerHTML = `
<div class="hint" style="margin-top:12px">${t('nest.explain')}</div>
${html || `<div class="hint">${t('nest.noFolders')}</div>`}`
2026-11-12 20:23:53 +01:00
}
async function saveNested() {
const out = {}
for (const r of nestData?.roots ?? []) out[r.id] = { chosen: [], ignored: [] }
for (const cb of document.querySelectorAll('#nestBody input[data-rel]')) out[cb.dataset.root]?.[cb.checked ? 'chosen' : 'ignored'].push(cb.dataset.rel)
const btn = document.getElementById('nestOk')
btn.disabled = true
try {
const r = await postJson('/api/nested', { roots: out })
document.getElementById('nestDlg').close()
await load()
toast(r.chosen ? t(r.chosen === 1 ? 'nest.adopted1' : 'nest.adoptedN', { n: r.chosen }) : t('nest.adoptedNone'), 'folder-tree')
2026-11-12 20:23:53 +01:00
} catch (e) { toast(e.message, 'triangle-alert') } finally { btn.disabled = false }
}
2026-11-12 15:58:44 +01:00
/* ── itch.io copy view (docs\itchio of the project, lib/itchpack.js) ───── */
let itchName = null
let itchData = null
async function copyText(text, what) {
try { await navigator.clipboard.writeText(text); toast(t('copy.ok', { what }), 'copy') } catch { toast(t('err.copyFailed'), 'triangle-alert') }
2026-11-12 15:58:44 +01:00
}
// formatted: pastes as rich text into itch.io's description editor
async function copyHtml(html, what) {
try {
const tmp = document.createElement('div')
tmp.innerHTML = html
await navigator.clipboard.write([new ClipboardItem({
'text/html': new Blob([html], { type: 'text/html' }),
'text/plain': new Blob([tmp.innerText], { type: 'text/plain' }),
})])
toast(t('copy.okFormatted', { what }), 'copy')
2026-11-12 15:58:44 +01:00
} catch { copyText(html, `${what} (HTML)`) }
}
async function openItch(name) {
itchName = name
const dlg = document.getElementById('itchDlg')
document.getElementById('itchTitle').textContent = `${t('dlg.itch.title')} · ${name}`
document.getElementById('itchBody').innerHTML = `<div class="hint">${ic('loader', 'sm')} ${t('itch.loading')}</div>`
2026-11-12 15:58:44 +01:00
if (!dlg.open) dlg.showModal()
try {
const r = await fetch(api(name, 'itch'))
itchData = await r.json()
if (!r.ok) throw new Error(itchData.error)
renderItch()
} catch (e) {
document.getElementById('itchBody').innerHTML = `<div class="hint">${t('nest.error')}: ${escapeHtml(e.message)}</div>`
2026-11-12 15:58:44 +01:00
}
}
const ITCH_SHORT_MAX = 120 // itch.io "Short description or tagline"
function htmlText(html) {
const t = document.createElement('template')
t.innerHTML = html
return (t.content.textContent ?? '').replace(/\s+/g, ' ').trim()
}
function firstParagraph(html) {
const t = document.createElement('template')
t.innerHTML = html
const p = [...t.content.querySelectorAll('p')].map((x) => x.textContent.replace(/\s+/g, ' ').trim()).find((x) => x.length > 30)
return p ?? ''
}
// ≤ 120 characters: the first part before " – " / ". " if it fits, else cut at a word
function shorten(s) {
s = String(s ?? '').trim()
if (!s || s.length <= ITCH_SHORT_MAX) return s
for (const sep of [' – ', ' - ', '. ', ': ', ', ']) {
let cut = ''
for (const part of s.split(sep)) {
const next = cut ? cut + sep + part : part
if (next.length > ITCH_SHORT_MAX) break
cut = next
}
if (cut.length >= 40) return cut.replace(/[,:;–-]\s*$/, '').trim() + (sep === '. ' && !/[.!?]$/.test(cut) ? '.' : '')
}
return s.slice(0, ITCH_SHORT_MAX - 1).replace(/\s+\S*$/, '') + '…'
}
// itch.io tag ideas from the texts and the tech (lowercase, hyphenated like on itch)
const TAG_RULES = [
[/\bidle\b/, ['idle', 'incremental']], [/clicker/, ['clicker']], [/incremental/, ['incremental']],
[/puzzle|riddle/, ['puzzle', 'casual']], [/\brpg\b|role[- ]playing/, ['rpg']], [/rogue(like|lite)/, ['roguelike']],
[/platform(er)?/, ['platformer']], [/shoot|bullet/, ['shooter']], [/tower defen[cs]e/, ['tower-defense']],
[/strateg/, ['strategy']], [/simulat|management|manage\b|tycoon/, ['simulation', 'management']],
[/arcade/, ['arcade']], [/high ?score|leaderboard/, ['high-score']], [/retro|8-bit|16-bit/, ['retro']],
[/pixel/, ['pixel-art']], [/\b3d\b/, ['3d']], [/\b2d\b/, ['2d']], [/fantasy|magic|dragon/, ['fantasy']],
[/horror|creepy|scary/, ['horror']], [/sci-?fi|spaceship|outer space|galaxy|alien|robot/, ['sci-fi']],
[/relax|cozy|calm|chill/, ['relaxing', 'cozy']], [/cute/, ['cute']], [/funny|humou?r|silly/, ['funny']],
[/physics|ragdoll/, ['physics']], [/survival/, ['survival']], [/card game|card-game|deck-?build/, ['card-game']],
[/rhythm/, ['rhythm']], [/racing|race car|kart/, ['racing']], [/fight|combat|duel|arena/, ['fighting']],
[/medieval|knight|castle/, ['medieval']], [/roman|rome|gladiator|ancient/, ['historical']],
[/zombie/, ['zombies']], [/ocean|underwater|fish|aquarium/, ['underwater']], [/time attack|timer|speed/, ['time-attack']],
[/multiplayer|co-?op\b/, ['multiplayer']], [/local (co-?op|multiplayer)|split ?screen/, ['local-multiplayer']],
[/gamepad|controller/, ['controller']], [/mouse only|mouse-only/, ['mouse-only']], [/touch|mobile|android/, ['mobile']],
[/short|minutes/, ['short']], [/procedural|random(ly)? generated/, ['procedural-generation']],
[/singleplayer|single-player|solo/, ['singleplayer']], [/\bvr\b|virtual reality|quest/, ['virtual-reality']],
]
function suggestTags(text, techTypes) {
const t = String(text).toLowerCase()
const out = []
const add = (x) => { if (!out.includes(x)) out.push(x) }
for (const [re, tags] of TAG_RULES) if (re.test(t)) tags.forEach(add)
if (techTypes.includes('Unity')) add('unity')
if (techTypes.some((x) => ['Web', 'Vite'].includes(x))) add('html5')
if (!/multiplayer/.test(t)) add('singleplayer')
add('indie')
if (!out.includes('3d') && !out.includes('2d')) add('2d')
if (!out.some((x) => ['rpg', 'horror', 'strategy', 'roguelike'].includes(x))) add('casual')
return out.slice(0, 16)
}
// second element is a translation key (resolved at render time)
2026-11-12 15:58:44 +01:00
const ITCH_KINDS = [
['cover', 'itch.kind.cover'], ['theme', 'itch.kind.theme'],
['promo', 'itch.kind.promo'], ['screenshot', 'itch.kind.screenshot'], ['other', 'itch.kind.other'],
2026-11-12 15:58:44 +01:00
]
function renderItch() {
const d = itchData
const name = itchName
const body = document.getElementById('itchBody')
if (!d.exists) {
body.innerHTML = `<div class="hint">${t('itch.noPackage')}</div>`
2026-11-12 15:58:44 +01:00
return
}
const row = (label, f, extra = '') => {
const v = f?.copy ?? ''
return `<div class="copyrow">
<div class="cl">${label}</div>
<div class="cv">${v ? escapeHtml(v) : `<span class="hint">${f?.placeholder ? t('itch.openField') : t('itch.notFound')}</span>`}${extra}</div>
<button class="btn ghost" type="button" data-copy="${escapeHtml(v)}" data-what="${escapeHtml(label)}" ${v ? '' : 'disabled'} title="${t('copy.title')}">${ic('copy')}</button>
2026-11-12 15:58:44 +01:00
</div>`
}
// short description: itch.io allows 120 characters; a longer one gets a shortened suggestion
const descText = htmlText(d.descriptionHtml ?? '')
const tl = d.tagline?.copy ?? ''
const tlCount = tl ? ` <span class="chip ${tl.length <= ITCH_SHORT_MAX ? 'ok' : 'warn'}">${tl.length} / ${ITCH_SHORT_MAX}</span>` : ''
const shortSugg = tl.length > ITCH_SHORT_MAX ? shorten(tl) : !tl ? shorten(firstParagraph(d.descriptionHtml ?? '')) : ''
const shortRow = shortSugg
? row(tl ? t('itch.shorter') : t('itch.shortSugg'), { copy: shortSugg }, ` <span class="chip ok">${shortSugg.length} / ${ITCH_SHORT_MAX}</span>`)
2026-11-12 15:58:44 +01:00
: ''
const words = descText ? descText.split(/\s+/).filter(Boolean).length : 0
const htmlBlock = (key, title, html, info = '') => html == null ? '' : `
<div class="isec"><h4>${ic('file-code')}${title}${info ? ` <span class="hint" style="font-weight:400">${info}</span>` : ''}
<span class="h4r"><button class="btn" type="button" data-rich="${key}">${ic('clipboard-copy')}${t('itch.copyFormatted')}</button>
2026-11-12 15:58:44 +01:00
<button class="btn ghost" type="button" data-raw="${key}">${ic('code-xml')}HTML</button></span></h4>
<iframe class="ipreview${key === 'desc' ? ' big' : ''}" sandbox="" data-html="${key}" title="${title}"></iframe></div>`
const otherFields = d.fields.filter((f) => !/^tags/i.test(f.key))
// tags: the package's own (click = copy one) + suggestions from the texts and the tech
const tagField = d.fields.find((f) => /^tags/i.test(f.key))
const ownTags = (tagField?.copy ?? '').split(/,\s*/).map((t) => t.trim().toLowerCase()).filter(Boolean)
const genre = d.fields.find((f) => /^genre/i.test(f.key))?.text ?? ''
const sugg = suggestTags(`${d.title?.copy ?? ''} ${tl} ${genre} ${descText}`, editing?.tech?.types ?? []).filter((t) => !ownTags.includes(t))
const tagChips = (list, cls) => list.map((x) => `<button type="button" class="tagc ${cls}" data-copy="${escapeHtml(x)}" data-what="${escapeHtml(t('itch.tagWhat', { t: x }))}">${escapeHtml(x)}</button>`).join('')
const tagsBlock = `<div class="isec"><h4>${ic('tags')}Tags <span class="hint" style="font-weight:400">${t('itch.tagsHint')}</span>
<span class="h4r">${ownTags.length ? `<button class="btn ghost" type="button" data-copy="${escapeHtml(ownTags.join(', '))}" data-what="Tags">${ic('copy')}${t('itch.all')}</button>` : ''}</span></h4>
${ownTags.length ? `<div class="tagrow"><span class="cl">${t('itch.inPackage', { n: ownTags.length })}</span>${tagChips(ownTags, 'own')}</div>` : `<div class="hint">${t('itch.noTags')}</div>`}
${sugg.length ? `<div class="tagrow"><span class="cl">${t('itch.examples')}</span>${tagChips(sugg, 'sugg')}</div>` : ''}
2026-11-12 15:58:44 +01:00
</div>`
const imgs = d.images ?? []
const imgUrl = (rel) => `${api(name, 'itch/file')}?f=${encodeURIComponent(rel)}`
const gallery = ITCH_KINDS.map(([k, label]) => {
const list = imgs.filter((i) => i.kind === k)
if (!list.length) return ''
return `<div class="igroup"><div class="agroup-h">${t(label)} <span class="hint">· ${list.length}</span></div><div class="itchgrid">${list.map((i) =>
`<button type="button" class="ishot" data-file="${escapeHtml(i.rel)}" title="${escapeHtml(i.rel)} – ${t('itch.showInExplorer')}">
2026-11-12 15:58:44 +01:00
<img loading="lazy" src="${imgUrl(i.rel)}" alt=""><span>${escapeHtml(i.rel.split(/[\\/]/).pop())}<small>${i.mb < 1 ? '< 1 MB' : fmtMB(i.mb)}</small></span>
</button>`).join('')}</div></div>`
}).join('')
body.innerHTML = `
<div class="isec"><h4>${ic('type')}${t('itch.texts')}</h4>
2026-11-12 15:58:44 +01:00
${row('Title', d.title)}
${row('Short description', d.tagline, tlCount)}
${shortRow}
</div>
${d.descriptionHtml == null ? `<div class="isec"><h4>${ic('file-code')}Description</h4><div class="hint">${t('itch.noDescHtml')}</div></div>` : ''}
${htmlBlock('desc', 'Description', d.descriptionHtml, t('itch.nWords', { n: words }))}
2026-11-12 15:58:44 +01:00
${tagsBlock}
${htmlBlock('install', 'Install instructions', d.installHtml)}
<div class="isec"><h4>${ic('images')}${t('itch.images')} <span class="hint" style="font-weight:400">${t('itch.imagesHint')}</span></h4>
${gallery || `<div class="hint">${t('itch.noImages')}</div>`}
${d.media?.length ? `<div class="hint">${ic('film', 'sm')} ${t('itch.moreFiles')}: ${d.media.map(escapeHtml).join(', ')}</div>` : ''}
2026-11-12 15:58:44 +01:00
</div>
${otherFields.length ? `<div class="isec"><h4>${ic('list')}${t('itch.moreFields')}</h4>
2026-11-12 15:58:44 +01:00
${otherFields.map((f) => `<div class="copyrow">
<div class="cl">${escapeHtml(f.key)}</div>
<div class="cv">${f.placeholder ? `<span class="hint">${t('itch.openField')}</span>` : escapeHtml(f.text)}</div>
<button class="btn ghost" type="button" data-copy="${escapeHtml(f.copy)}" data-what="${escapeHtml(f.key)}" ${f.copy ? '' : 'disabled'} title="${f.copy ? t('itch.copiedVal', { v: escapeHtml(f.copy) }) : ''}">${ic('copy')}</button>
2026-11-12 15:58:44 +01:00
</div>`).join('')}
</div>` : ''}
<div class="hint">${ic('shield-check', 'sm')} ${t('itch.nothingUploaded')}</div>`
2026-11-12 15:58:44 +01:00
const html = { desc: d.descriptionHtml, install: d.installHtml }
for (const f of body.querySelectorAll('iframe[data-html]')) {
f.srcdoc = `<!doctype html><meta charset="utf-8"><style>body{font:14px/1.5 system-ui,sans-serif;margin:12px;color:#222;background:#fff}h2,h3{margin:.8em 0 .3em}img{max-width:100%}</style>${html[f.dataset.html]}`
}
for (const b of body.querySelectorAll('[data-copy]')) b.onclick = () => copyText(b.dataset.copy, b.dataset.what)
for (const b of body.querySelectorAll('[data-rich]')) b.onclick = () => copyHtml(html[b.dataset.rich], b.dataset.rich === 'desc' ? 'Description' : t('itch.installText'))
2026-11-12 15:58:44 +01:00
for (const b of body.querySelectorAll('[data-raw]')) b.onclick = () => copyText(html[b.dataset.raw], 'HTML')
for (const b of body.querySelectorAll('.ishot')) b.onclick = () => postJson(api(name, 'itch/open'), { f: b.dataset.file }).catch((e) => toast(e.message, 'triangle-alert'))
}
2026-11-12 09:32:23 +01:00
// Saves the program the ▶ starts ('' = choose automatically again).
async function setProgram(name, program) {
try {
const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ program }),
})
const r = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(r.error ?? t('err.saveFailed'))
toast(r.program ? t('prog.nowStarts', { prog: r.program }) : t('prog.autoAgain'), 'pin')
2026-11-12 09:32:23 +01:00
if (editing?.name === name) { editing.program = r.program; loadDetails(name) }
load()
} catch (e) { toast(e.message, 'triangle-alert') }
}
// Permanently deletes the whole project folder (server: /delete). Two confirms.
async function deleteProject(name, d) {
if (!confirm(t('danger.confirm1', { name, path: d?.path ?? name }))) return
if (!confirm(t('danger.confirm2', { name }))) return
try {
await postJson(api(name, 'delete'))
toast(t('danger.deleted', { name }), 'trash')
closeEditor()
await load()
await loadBackup()
} catch (e) { toast(e.message, 'triangle-alert') }
}
2026-11-12 09:32:23 +01:00
/* ── per-project backup ("Sichern" in Aktionen) ─────────────────────── */
let projectLastBackup = null
let projectTargets = [] // [{ id, name, last }] – this project on every backup target
function renderProjectBackup(name) {
const el = document.getElementById('pbackupBody')
if (!el || editing?.name !== name) return
const b = backup
const T = window.I18N.t
2026-11-12 09:32:23 +01:00
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>${T('pbackup.noTarget')}</div></div>
<div class="bactions"><button class="btn primary" id="pbSetup">${ic('settings')}${T('pbackup.setupTarget')}</button></div>`
2026-11-12 09:32:23 +01:00
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>${T('pbackup.lastSaved')}</div><div>${last
? `<b>${new Date(last.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' })}</b> (${timeAgo(last.at)}) <span class="hint">· ${last.how}</span>`
: `<span style="color:var(--yellow)">${T('cloud.never')}</span>`}</div>
<div>${T('pbackup.target')}</div><div class="hint" style="margin:0">${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}</div>
${projectTargets.length > 1 ? `<div>${T('pbackup.allTargets')}</div><div class="tlast">${projectTargets.map((x) => {
2026-11-12 09:32:23 +01:00
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(I18N.locale())} (${x.last.how})` : `${x.name}: ${T('cloud.never')}`)}">${ic('hard-drive', 'sm')}${escapeHtml(x.name)} · ${x.last ? timeAgo(x.last.at) : T('cloud.never')}</span>`
2026-11-12 09:32:23 +01:00
}).join('')}</div>` : ''}</div>`
if (busy && mine && b.phase === 'checking') {
html += `<div class="msg info">${ic('loader')}<div><b>${T('pbackup.checking')}</b></div></div>`
2026-11-12 09:32:23 +01:00
} 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>${T('pbackup.copyingPct', { pct })}</b><span>${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}</span></div>
2026-11-12 09:32:23 +01:00
<div class="progress big"><div style="width:${pct}%"></div></div>
<div class="hint">${T('pbackup.nFiles', { done: pr.files.toLocaleString(I18N.locale()), total: pr.filesTotal.toLocaleString(I18N.locale()) })}</div>
2026-11-12 09:32:23 +01:00
<div class="curfile" title="${escapeHtml(pr.current)}">${escapeHtml(pr.current)}</div>`
} else if (busy) {
html += `<div class="msg info">${ic('hourglass')}<div>${T('pbackup.otherRunning', { scope: b.scope ? escapeHtml(b.scope) : T('pbackup.allProjects') })}</div></div>`
2026-11-12 09:32:23 +01:00
} else if (mine && b.phase === 'done') {
const l = shownT?.lastByProject?.[name]
html += l && l.files
? `<div class="msg ok">${ic('circle-check')}<div><b>${T('pbackup.savedBold')}</b> ${T('pbackup.copiedN', { n: l.files.toLocaleString(I18N.locale()), size: fmtBytes(l.bytes) })}</div></div>`
: `<div class="msg ok">${ic('circle-check')}<div><b>${T('pbackup.upToDate')}</b> ${T('pbackup.nothingMissing')}</div></div>`
2026-11-12 09:32:23 +01:00
} 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>${T('pbackup.cancelled')}</div></div>`
2026-11-12 09:32:23 +01:00
}
html += `<div class="bactions">${busy && mine
? `<button class="btn" id="pbCancel">${ic('circle-x')}${T('common.cancel')}</button>`
: `<button class="btn primary" id="pbSave" ${busy || b?.configError ? 'disabled' : ''}>${ic('hard-drive-upload')}${T('pbackup.saveNow')}</button>`}</div>
<div class="hint">${T('pbackup.hint')}</div>`
2026-11-12 09:32:23 +01:00
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">${t('nest.error')}: ${escapeHtml(e.message)}</div>`
2026-11-12 09:32:23 +01:00
}
}
function openEditor(p) {
closeBackup()
editing = p
editingTasks = (p.tasks ?? []).map((t) => ({ ...t }))
document.getElementById('pAvatar').innerHTML = avatar(p, 'lg')
document.getElementById('panel').style.setProperty('--pc', nameColor(p.name))
document.getElementById('pBanner').innerHTML = `<img loading="lazy" src="${thumbUrl(p.name)}" alt="" onerror="this.remove()">`
2026-11-12 09:32:23 +01:00
document.getElementById('panelTitle').textContent = p.name
document.getElementById('pFav').innerHTML = favBtn(p)
wireFav(document.getElementById('pFav'), p)
2026-11-12 20:58:18 +01:00
document.getElementById('panelSub').innerHTML = uiMode === 'simple' ? `${statusHtml(p.status)}${rootTag(p)}` : `${statusHtml(p.status)}${gitHtml(p.git, true)}${techChips(p.tech?.types)}${pubChip(p)}`
2026-11-12 09:32:23 +01:00
document.getElementById('fStatus').value = p.status
document.getElementById('fPriority').value = p.priority
document.getElementById('fTags').value = (p.tags ?? []).join(', ')
document.getElementById('fThumb').value = p.thumbnail ?? ''
document.getElementById('fStart').value = p.start ?? ''
document.getElementById('fItch').value = p.itch ?? ''
document.getElementById('fItchHint').innerHTML = p.itch === '-'
? `${ic('circle-off', 'sm')} ${t('edit.itchNot')}`
2026-11-12 09:32:23 +01:00
: p.published?.source === 'auto'
? `${ic('sparkles', 'sm')} ${t('edit.itchAuto', { title: escapeHtml(p.published.title) })} – ${escapeHtml(p.published.url)}`
: p.published ? '' : `${ic('info', 'sm')} ${t('edit.itchNotFound')}`
2026-11-12 09:32:23 +01:00
document.getElementById('fNotes').value = p.notes
renderTaskList()
const loading = `<div class="hint">${ic('loader', 'sm')} ${t('itch.loading')}</div>`
2026-11-12 09:32:23 +01:00
document.getElementById('sec-info').innerHTML = loading
document.getElementById('sec-actions').innerHTML = loading
document.getElementById('overlay').classList.add('open')
document.getElementById('panel').classList.add('open')
document.getElementById('panel').setAttribute('aria-hidden', 'false')
loadDetails(p.name)
}
function closeEditor() {
editing = null
editingTasks = []
document.getElementById('overlay').classList.remove('open')
document.getElementById('panel').classList.remove('open')
document.getElementById('panel').setAttribute('aria-hidden', 'true')
}
async function saveEditor() {
if (!editing) return
const body = {
status: document.getElementById('fStatus').value,
priority: document.getElementById('fPriority').value,
notes: document.getElementById('fNotes').value,
tags: document.getElementById('fTags').value.split(',').map((s) => s.trim()).filter(Boolean),
thumbnail: document.getElementById('fThumb').value.trim(),
start: document.getElementById('fStart').value.trim(),
itch: document.getElementById('fItch').value.trim(),
tasks: editingTasks,
}
if (await patchProject(editing.name, body)) {
toast(t('edit.saved'), 'save')
2026-11-12 09:32:23 +01:00
closeEditor()
load()
} else toast(patchProject.error || t('err.saveFailed'), 'triangle-alert')
2026-11-12 09:32:23 +01:00
}
/* ── 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((x) => `<button type="button" data-target="${escapeHtml(x.id)}" class="${x.id === cur ? 'active' : ''}" ${busyId && x.id !== busyId ? `disabled title="${t('backup.otherRunning')}"` : ''}>${ic('hard-drive', 'sm')}${escapeHtml(x.name)}</button>`).join('')}</div>`
2026-11-12 09:32:23 +01:00
}
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()
2026-11-12 14:03:53 +01:00
const wasAuto = backup?.auto
2026-11-12 09:32:23 +01:00
try { backup = await (await fetch('/api/backup')).json() } catch { return }
2026-11-12 14:03:53 +01:00
if (wasBusy && !backupBusy()) {
load() // refresh the backup badges on cards/tiles/list
if (wasAuto) toast(backup.phase === 'done' ? t('backup.autoDone') : t('backup.autoFail', { err: backup.error ?? t('backup.cancelledWord') }), backup.phase === 'done' ? 'circle-check' : 'triangle-alert')
} else if (!wasBusy && backupBusy() && backup.auto) toast(t('backup.autoRunning'), 'hard-drive-upload')
2026-11-12 09:32:23 +01:00
renderBackupButton()
2026-11-12 14:03:53 +01:00
if (document.getElementById('spanel').classList.contains('open')) renderAutoStatus()
2026-11-12 09:32:23 +01:00
if (document.getElementById('bpanel').classList.contains('open')) renderBackup()
if (editing) {
const own = curTarget()?.lastByProject?.[editing.name]
if (own && (!projectLastBackup || own.at > projectLastBackup.at)) projectLastBackup = { ...own, how: 'Projekt' }
renderProjectBackup(editing.name)
}
clearTimeout(backupTimer)
if (backupBusy()) backupTimer = setTimeout(loadBackup, 1000)
}
function renderBackupButton() {
const sub = document.getElementById('backupSub')
if (!backup) return
const btn = document.getElementById('btnBackup')
const T = window.I18N.t
btn.title = (backup.targets ?? []).map((x) => `${x.name}: ${x.last ? T('backup.lastAgo', { ago: timeAgo(x.last.at) }) : T('backup.neverComplete')}`).join('\n') || T('pbackup.setupTarget')
if (backup.notConfigured) { sub.textContent = '· ' + T('backup.setup'); sub.classList.add('warn'); return }
2026-11-12 09:32:23 +01:00
const t = curTarget()
const last = t?.last
const prefix = backup.targets.length > 1 ? `· ${t.name} ` : '· '
if (backup.phase === 'checking') sub.textContent = backup.auto ? '· ' + T('backup.autoChecking') : '· ' + T('backup.checkingShort')
2026-11-12 09:32:23 +01:00
else if (backup.phase === 'copying') {
const pr = backup.progress
2026-11-12 14:03:53 +01:00
sub.textContent = `· ${backup.auto ? 'auto ' : ''}${pr.bytesTotal ? Math.round((pr.bytes / pr.bytesTotal) * 100) : 0} %`
} else if (dueCount()) sub.textContent = `· ${T('backup.nDue', { n: dueCount() })}`
2026-11-12 14:03:53 +01:00
else if (last) sub.textContent = `${prefix}${timeAgo(last.at)}`
else sub.textContent = `${prefix}${T('cloud.never')}`
2026-11-12 14:03:53 +01:00
const old = last && (Date.now() - new Date(last.at)) > BACKUP_FRESH_DAYS * 86400000
sub.classList.toggle('warn', !last || old || last.ok === false || dueCount() > 0)
if (dueCount()) btn.title += `\n\n${T('backup.dueTitle', { n: dueCount(), days: BACKUP_FRESH_DAYS })}`
fitHeader()
2026-11-12 14:03:53 +01:00
}
const dueCount = () => projects.filter(backupDue).length
// once a day: a hint when backups are due
function remindBackup() {
const n = dueCount()
if (!n || backup?.notConfigured || backupBusy()) return
const today = new Date().toISOString().slice(0, 10)
try { if (localStorage.getItem('dash.backupReminded') === today) return; localStorage.setItem('dash.backupReminded', today) } catch {}
toast(t(n === 1 ? 'backup.remind1' : 'backup.remindN', { n }), 'clock-alert')
2026-11-12 09:32:23 +01:00
}
async function backupAction(what) {
try {
backup = await postJson(`/api/backup/${what}`, what === 'check' ? { target: curTargetId() } : {})
renderBackup()
loadBackup()
} catch (e) { toast(e.message, 'triangle-alert') }
}
function renderBackup() {
const T = window.I18N.t
2026-11-12 09:32:23 +01:00
let b = backup
if (!b) return
if (b.notConfigured) {
document.getElementById('bpTarget').textContent = T('backup.noTargetShort')
document.getElementById('bpBody').innerHTML = `<div class="msg info">${ic('hard-drive-upload')}<div>${T('backup.noTargetLong')}</div></div>
<div class="bactions"><button class="btn primary big" id="bpSetup">${ic('settings')}${T('pbackup.setupTarget')}</button></div>`
2026-11-12 09:32:23 +01:00
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>${T('backup.lastBackup')}</div><div><b>${new Date(tl.at).toLocaleString(I18N.locale(), { dateStyle: 'medium', timeStyle: 'short' })}</b> (${timeAgo(tl.at)})</div>
<div>${T('backup.copied')}</div><div>${T('backup.nFilesCell', { n: tl.files.toLocaleString(I18N.locale()) })} · ${fmtBytes(tl.bytes)}${tl.ok === false ? ` · <span style="color:var(--red)">${T('cloud.incomplete')}</span>` : ''}</div></div>`
: `<div class="hint">${T('backup.noneOnTarget', { name: escapeHtml(t.name) })}</div>`
2026-11-12 09:32:23 +01:00
let body = targetTabs(busy ? b.target : null) + section('clock-3', T('backup.statusOf', { name: escapeHtml(t.name) }), last)
2026-11-12 09:32:23 +01:00
b = { ...b, phase }
if (b.scope && b.phase !== 'idle') {
body += `<div class="msg info">${ic('folder')}<div>${T('backup.scopeNote', { scope: escapeHtml(b.scope) })}</div></div>`
2026-11-12 09:32:23 +01:00
}
if (b.phase === 'checking') {
body += `<div class="msg info">${ic('loader')}<div><b>${T('backup.checkingLong')}</b><div class="hint">${T('backup.checkingTime')}</div></div></div>
<div class="bactions"><button class="btn" id="bpCancel">${ic('circle-x')}${T('common.cancel')}</button></div>`
2026-11-12 09:32:23 +01:00
} else if (b.phase === 'copying') {
const pr = b.progress
const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0
body += section('hard-drive-upload', T('backup.copyingTitle'), `
2026-11-12 09:32:23 +01:00
<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">${T('pbackup.nFiles', { done: pr.files.toLocaleString(I18N.locale()), total: pr.filesTotal.toLocaleString(I18N.locale()) })}</div>
2026-11-12 09:32:23 +01:00
<div class="curfile" title="${escapeHtml(pr.current)}">${escapeHtml(pr.current)}</div>`)
+ `<div class="bactions"><button class="btn" id="bpCancel">${ic('circle-x')}${T('common.cancel')}</button></div>
<div class="hint">${T('backup.keepOpen')}</div>`
2026-11-12 09:32:23 +01:00
} else if (b.phase === 'ready' && b.check) {
const c = b.check
if (!c.files) {
body += `<div class="msg ok">${ic('circle-check')}<div><b>${T('pbackup.upToDate')}</b> ${T('backup.nothingMissing')}</div></div>`
2026-11-12 09:32:23 +01:00
} else {
body += section('scan-search', `${T('backup.checkResult')} <span class="hint" style="margin:0 0 0 auto">${timeAgo(c.at)}</span>`, `
2026-11-12 09:32:23 +01:00
<div class="bstats">
<div class="bstat new"><div class="l">${ic('file-plus', 'sm')}${T('backup.new')}</div><div class="v">${c.newFiles.toLocaleString(I18N.locale())}</div><div class="s">${fmtBytes(c.newBytes)}</div></div>
<div class="bstat chg"><div class="l">${ic('file-pen', 'sm')}${T('backup.changed')}</div><div class="v">${c.changedFiles.toLocaleString(I18N.locale())}</div><div class="s">${fmtBytes(c.changedBytes)}</div></div>
<div class="bstat"><div class="l">${ic('archive', 'sm')}${T('backup.onlyInBackup')}</div><div class="v">${c.extraFiles.toLocaleString(I18N.locale())}</div><div class="s">${T('backup.kept')}</div></div>
2026-11-12 09:32:23 +01:00
</div>
<table class="bproj">${c.projects.slice(0, 15).map((p) => `<tr><td>${escapeHtml(p.name)}</td><td class="r">${T('backup.nFilesCell', { n: p.files.toLocaleString(I18N.locale()) })}</td><td class="r">${fmtBytes(p.bytes)}</td></tr>`).join('')}</table>
${c.projects.length > 15 ? `<div class="hint">${T('backup.moreProjects', { n: c.projects.length - 15 })}</div>` : ''}`)
2026-11-12 09:32:23 +01:00
}
body += `<div class="bactions">
<button class="btn" id="bpCheck">${ic('refresh-cw')}${T('backup.recheck')}</button>
${c.files ? `<button class="btn primary" id="bpCopy">${ic('hard-drive-upload')}${T('backup.copyNow', { size: fmtBytes(c.bytes) })}</button>` : ''}
2026-11-12 09:32:23 +01:00
</div>`
} else {
if (b.phase === 'done') body += `<div class="msg ok">${ic('circle-check')}<div><b>${T('backup.done')}</b> ${tl && !b.scope ? T('backup.doneN', { n: tl.files.toLocaleString(I18N.locale()), size: fmtBytes(tl.bytes) }) : ''}</div></div>`
if (b.phase === 'cancelled') body += `<div class="msg info">${ic('circle-x')}<div>${T('pbackup.cancelled')}</div></div>`
2026-11-12 09:32:23 +01:00
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')}${T('backup.checkWhatsNew')}</button></div>`
2026-11-12 09:32:23 +01:00
}
body += `<div class="hint" style="margin-top:16px">${ic('shield-check', 'sm')} ${T('backup.footerHint', { exclude: escapeHtml((settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.gradle', '.venv']).join(', ')) })}</div>`
2026-11-12 09:32:23 +01:00
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)
applyAccent() // accent is derived per theme, so recompute on every theme change
}
/* ── accent colour (Einstellungen → Allgemein → Darstellung) ──────────── */
// All accent CSS vars are derived from one chosen base colour via color-mix, theme-aware. Not set =
// the hand-tuned defaults in index.html stay untouched.
const ACCENTS = ['#6366f1', '#3b82f6', '#06b6d4', '#10b981', '#f59e0b', '#ef4444', '#ec4899', '#a855f7']
let accentBase = (() => { try { return localStorage.getItem('dash.accent') || '' } catch { return '' } })()
function applyAccent() {
const r = document.documentElement, s = r.style
if (!accentBase) { for (const v of ['--accent', '--accent-2', '--accent-soft', '--accent-text']) s.removeProperty(v); return }
const dark = r.dataset.theme === 'dark'
const base = accentBase
const accent = dark ? `color-mix(in srgb, ${base} 78%, #fff)` : base
s.setProperty('--accent', accent)
s.setProperty('--accent-2', `color-mix(in srgb, ${base} 65%, ${dark ? '#c084fc' : '#a855f7'})`)
s.setProperty('--accent-soft', dark ? `color-mix(in srgb, ${base} 30%, #171a23)` : `color-mix(in srgb, ${base} 13%, #fff)`)
s.setProperty('--accent-text', dark ? `color-mix(in srgb, ${base} 45%, #fff)` : `color-mix(in srgb, ${base} 72%, #1e1b4b)`)
}
function setAccent(hex) {
accentBase = /^#[0-9a-f]{6}$/i.test(hex || '') && hex.toLowerCase() !== '#6366f1' ? hex.toLowerCase() : ''
try { accentBase ? localStorage.setItem('dash.accent', accentBase) : localStorage.removeItem('dash.accent') } catch {}
applyAccent()
renderAccentPicker()
}
function renderAccentPicker() {
const box = document.getElementById('accentSwatches')
if (!box) return
const cur = accentBase || '#6366f1'
box.innerHTML = ACCENTS.map((c) => `<button type="button" class="swatch ${c === cur ? 'active' : ''}" style="--sw:${c}" data-accent="${c}" title="${c}"></button>`).join('')
for (const b of box.querySelectorAll('[data-accent]')) b.onclick = () => setAccent(b.dataset.accent)
const custom = document.getElementById('accentCustom')
if (custom) { custom.value = cur; const lab = custom.closest('.swatch'); if (lab) lab.classList.toggle('active', !ACCENTS.includes(cur)) }
}
function initAccent() {
applyAccent()
renderAccentPicker()
const custom = document.getElementById('accentCustom')
if (custom) custom.oninput = (e) => setAccent(e.target.value)
2026-11-12 09:32:23 +01:00
}
function setThemeMode(mode) {
themeMode = ['light', 'dark', 'system'].includes(mode) ? mode : 'system'
applyTheme()
try { localStorage.setItem('dash.theme', themeMode) } catch {}
}
function initTheme() {
let saved = null
try { saved = localStorage.getItem('dash.theme') } catch {}
saved = new URLSearchParams(location.search).get('theme') ?? saved
themeMode = ['light', 'dark', 'system'].includes(saved) ? saved : 'system'
applyTheme()
}
systemDark.addEventListener('change', () => { if (themeMode === 'system') applyTheme() })
for (const b of document.querySelectorAll('#themeSeg button')) b.onclick = () => setThemeMode(b.dataset.mode)
/* ── language (Einstellungen → Allgemein) ─────────────────────────────── */
// Static text is swapped by I18N via data-i18n attributes; dynamic parts are
// re-rendered here after a switch. English is the default (see i18n.js).
function initLang() {
const sel = document.getElementById('fLang')
if (sel) {
sel.innerHTML = Object.entries(I18N.langs).map(([code, name]) => `<option value="${code}">${escapeHtml(name)}</option>`).join('')
sel.value = I18N.get()
sel.addEventListener('change', () => I18N.set(sel.value))
}
I18N.onChange(() => {
const sl = document.getElementById('fLang'); if (sl) sl.value = I18N.get()
try { render() } catch {}
try { renderBackupButton() } catch {}
try { renderRootPicker() } catch {}
try { renderDemo() } catch {}
if (editing) try { openEditor(editing) } catch {}
const sp = document.getElementById('spanel')
if (sp.classList.contains('open')) { I18N.apply(sp); try { renderAutoStatus() } catch {} }
try { if (document.getElementById('helpDlg').open) renderHelp() } catch {}
})
}
/* ── start screen: progress while the projects are read ───────────────── */
// 1/2 projects (git, sizes, tech - the first /api/projects), 2/2 "last change" of
// every project (lib/activity.js, background). Shows count, bar and time left.
let boot = null
function startBoot() {
const el = document.getElementById('boot')
boot = { step: 1, t0: Date.now(), timer: null, loaded: false }
el.hidden = false
document.getElementById('bootSkip').onclick = endBoot
const tick = async () => {
if (!boot) return
try {
const r = await (await fetch('/api/progress')).json()
if (!boot) return
if (boot.step === 1) {
const pj = r.projects
showBoot(1, pj.phase === 'itch' ? t('boot.itch') : t('boot.reading2'), pj.done, pj.total)
} else {
const total = r.activity.total || 1
const done = Math.max(0, total - r.activity.pending)
if (!r.activity.pending) return endBoot()
showBoot(2, t('boot.changes'), done, total)
}
} catch {}
if (boot) boot.timer = setTimeout(tick, 300)
}
// only worth a screen when it takes a moment
boot.timer = setTimeout(tick, 150)
}
function showBoot(step, label, done, total) {
if (boot.shownStep !== step) { boot.shownStep = step; boot.t0 = Date.now(); boot.d0 = done }
const pct = total ? Math.min(100, Math.round((done / total) * 100)) : 0
document.getElementById('bootStep').textContent = t('boot.step', { step })
document.getElementById('bootLabel').textContent = label
document.getElementById('bootBar').style.width = `${pct}%`
document.getElementById('bootCount').textContent = total ? `${done} / ${total}` : ''
// time left from the speed of this step so far
const secs = (Date.now() - boot.t0) / 1000
const rate = (done - (boot.d0 ?? 0)) / Math.max(secs, 0.1)
const left = rate > 0 && total > done ? Math.ceil((total - done) / rate) : null
document.getElementById('bootEta').textContent = left == null ? t('boot.estimating') : left < 2 ? t('boot.almost') : left < 60 ? t('boot.etaS', { s: left }) : t('boot.etaMin', { m: Math.ceil(left / 60) })
}
// the projects are there: step 2 only while "last change" is still being collected
function bootLoaded() {
if (!boot) return
if (noneShown || !projects.length || document.getElementById('spanel').classList.contains('open')) return endBoot()
boot.step = 2
}
function endBoot() {
if (!boot) return
clearTimeout(boot.timer)
boot = null
const el = document.getElementById('boot')
el.classList.add('done')
setTimeout(() => { el.hidden = true }, 250)
}
/* ── header: gets more compact step by step when it does not fit ──────── */
function fitHeader() {
const bar = document.querySelector('.topbar')
const levels = 4
for (let i = 1; i <= levels; i++) document.body.classList.remove(`hc${i}`)
for (let i = 1; i <= levels && bar.scrollWidth > bar.clientWidth + 1; i++) document.body.classList.add(`hc${i}`)
}
new ResizeObserver(fitHeader).observe(document.querySelector('.topbar'))
window.addEventListener('resize', fitHeader)
2026-11-12 09:32:23 +01:00
/* ── 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)
2026-11-12 20:23:53 +01:00
document.getElementById('nestClose').onclick = () => document.getElementById('nestDlg').close()
document.getElementById('nestCancel').onclick = () => document.getElementById('nestDlg').close()
document.getElementById('nestDeep').onclick = () => openNested(true)
document.getElementById('nestOk').onclick = saveNested
document.getElementById('fNestedOpen').onclick = () => openNested()
document.getElementById('itchClose').onclick =() => document.getElementById('itchDlg').close()
2026-11-12 15:58:44 +01:00
document.getElementById('itchReload').onclick = () => itchName && openItch(itchName)
document.getElementById('itchOpenDir').onclick = () => itchName && postJson(api(itchName, 'itch/open')).catch((e) => toast(e.message, 'triangle-alert'))
2026-11-12 09:32:23 +01:00
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('/')
2026-11-12 20:58:18 +01:00
const VIEWS = ['home', 'board', 'gallery', 'list', 'tasks', 'storage', 'activity']
2026-11-12 09:32:23 +01:00
initTheme()
initAccent()
initLang()
2026-11-12 20:58:18 +01:00
initUiMode()
2026-11-12 09:32:23 +01:00
if (VIEWS.includes(hashView)) setView(hashView)
else try { const v = localStorage.getItem('dash.view'); if (VIEWS.includes(v)) setView(v) } catch {}
2026-11-12 20:58:18 +01:00
// nothing stored (first start): the simple view starts on its tile page
if (uiMode === 'simple' && ADV_VIEWS.includes(activeView)) setView('home')
2026-11-12 09:32:23 +01:00
function openFromHash(project, sec) {
const p = project && projects.find((x) => x.name === project)
if (p) { openEditor(p); if (sec) setSection(sec) }
}
document.getElementById('noneOpen').onclick = (e) => { e.stopPropagation(); toggleRootMenu(true) }
startBoot()
load().then(() => { bootLoaded(); openFromHash(hashProject, hashSec); if (hashView === 'backup') openBackup() })
2026-11-12 09:32:23 +01:00
loadBackup()
2026-11-12 14:03:53 +01:00
// an automatic backup can start any time: look once a minute (while busy, loadBackup polls every second)
setInterval(() => { if (!backupBusy()) loadBackup() }, 60000)
2026-11-12 09:32:23 +01:00
window.addEventListener('hashchange', () => {
const [v, project, sec] = decodeURIComponent(location.hash.slice(1)).split('/')
if (VIEWS.includes(v)) { setView(v); render() }
openFromHash(project, sec)
})