commit 53f1896d05438e183d905f3a89a689688f7cc4ca Author: Michi Date: Thu Nov 12 09:32:23 2026 +0100 main ini diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..157803d --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,11 @@ +{ + "permissions": { + "allow": [ + "PowerShell($c = Get-NetTCPConnection -LocalPort 4949 -State Listen -ErrorAction SilentlyContinue; foreach \\($x in $c\\) { $p = Get-CimInstance Win32_Process -Filter \"ProcessId=$\\($x.OwningProcess\\)\"; \"$\\($p.ProcessId\\) $\\($p.CommandLine\\)\"; if \\($p.CommandLine -match 'server\\\\.js'\\) { Stop-Process -Id $p.ProcessId -Confirm:$false } })", + "PowerShell(\\(Get-Content public\\\\app.js -Raw\\) -replace 'const rootPaths = \\\\\\(\\\\\\) =>', 'const rowRootPaths = \\(\\) =>' -replace 'have: rootPaths\\\\\\(\\\\\\)', 'have: rowRootPaths\\(\\)' | Set-Content public\\\\app.js -Encoding utf8 -NoNewline; Select-String -Path public\\\\app.js -Pattern 'rootPaths\\\\\\(\\\\\\)|rowRootPaths' | ForEach-Object { \"$\\($_.LineNumber\\): $\\($_.Line.Trim\\(\\)\\)\" }; node --check public/app.js; if \\($?\\) { 'OK' })", + "PowerShell($b = [IO.File]::ReadAllBytes\\(\"$PWD\\\\public\\\\app.js\"\\); if \\($b[0] -eq 0xEF -and $b[1] -eq 0xBB\\) { [IO.File]::WriteAllBytes\\(\"$PWD\\\\public\\\\app.js\", $b[3..\\($b.Length-1\\)]\\); 'BOM removed' } else { 'no BOM' }; node --check public/app.js; if \\($?\\) { 'OK' })", + "PowerShell($f = \"$PWD\\\\public\\\\app.js\"; $txt = [IO.File]::ReadAllText\\($f, [Text.UTF8Encoding]::new\\($false\\)\\); $orig = [Text.Encoding]::GetEncoding\\(1252\\).GetBytes\\($txt\\); $fixed = [Text.UTF8Encoding]::new\\($false, $true\\).GetString\\($orig\\); [IO.File]::WriteAllText\\($f, $fixed, [Text.UTF8Encoding]::new\\($false\\)\\); \"mojibake left: \" + \\([regex]::Matches\\($fixed, 'Ã|Â'\\).Count\\); \"umlauts: \" + \\([regex]::Matches\\($fixed, '[äöüÄÖÜß–…→]'\\).Count\\); node --check public/app.js; if \\($?\\) { 'OK' })", + "PowerShell($c = Get-NetTCPConnection -LocalPort 4848 -State Listen -ErrorAction SilentlyContinue; foreach \\($x in $c\\) { Get-CimInstance Win32_Process -Filter \"ProcessId=$\\($x.OwningProcess\\)\" | Select-Object ProcessId, CreationDate, CommandLine, ExecutablePath | Format-List }; \\(Get-Item server.js\\).LastWriteTime; try { \\(Invoke-WebRequest -UseBasicParsing -Method Post -Uri 'http://127.0.0.1:4848/api/projects/xyz/git-init' -Headers @{Origin='http://127.0.0.1:4848'} -ContentType 'application/json' -Body '{}'\\).Content } catch { $_.Exception.Response.StatusCode; \\(New-Object IO.StreamReader\\($_.Exception.Response.GetResponseStream\\(\\)\\)\\).ReadToEnd\\(\\).Substring\\(0,120\\) })" + ] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f7f65e9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +node_modules/ +.cache/ +launcher/bin/ +launcher/obj/ +launcher/publish/ +release/ +launcher/payload.zip +launcher/payload-stage/ +launcher/publish-portable/ diff --git a/ProjectDashboard.exe b/ProjectDashboard.exe new file mode 100644 index 0000000..ba45c22 Binary files /dev/null and b/ProjectDashboard.exe differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..5763645 --- /dev/null +++ b/README.md @@ -0,0 +1,201 @@ +# Project Dashboard + +Kleines lokales Kanban-Board für alle Ordner unter `D:\Oculusquest\Projekt`. +Kein Account, keine Cloud - Status/Priorität/Notizen landen als +`.dashboard.json` direkt im jeweiligen Projektordner. + +Liegt als Werkzeug in `_Tools\ProjectDashboard` und verwaltet die Ordner zwei Ebenen höher +(`D:\Oculusquest\Projekt`; anders per Umgebungsvariable `DASHBOARD_ROOT`). + +## Starten + +**Als Programm:** `ProjectDashboard.exe` doppelklicken (Verknüpfung „Projekt-Dashboard“ liegt auf dem +Desktop und im Startmenü). Eigenes Fenster, kein Konsolenfenster. Die exe startet `server.js` unsichtbar +(beim ersten Mal auch `npm install`) und beendet ihn beim Schließen wieder. Läuft der Server schon +(zweites Fenster, `.bat`), wird er mitbenutzt. Server-Log: `%LOCALAPPDATA%\ProjectDashboard\server.log`. +Braucht Node.js, die .NET 8 Desktop Runtime und WebView2 (bei Windows 11 dabei). + +**Im Browser:** `start-dashboard.bat` doppelklicken oder `npm install` + `npm start`, +dann http://127.0.0.1:4848 – der Server ist **nur lokal** erreichbar. + +**Weitergeben (an Freunde):** `powershell -ExecutionPolicy Bypass -File build.ps1 -Release` → +`release\ProjectDashboard.exe` (~100 MB, **eine Datei**, nichts zu installieren: .NET, Node.js und das Dashboard sind drin). +Beim ersten Start entpackt sie sich nach `%LOCALAPPDATA%\ProjectDashboard\app\` und zeigt **Einrichten**: +Projektordner wählen (Pflicht), Backup-Ziel wählen (optional: externe Platte, NAS, anderes Laufwerk) – je mit „Durchsuchen…“. +Später änderbar über das **Zahnrad** oben. Einstellungen, Scan- und Backup-Stand liegen in `%LOCALAPPDATA%\ProjectDashboard\data\`. +**Mehrere Projektordner:** im Zahnrad-Menü einzeln hinzufügen („Ordner hinzufügen“) oder gesammelt +(„Mehrere einlesen…“: übergeordneten Ordner wählen, Unterordner ankreuzen) – beides auch direkt im Dropdown oben +links neben dem Logo. Dort per Häkchen **mehrere Ordner gleichzeitig anzeigen** (Klick auf den Namen = nur dieser). +Bei mehreren sichtbaren Ordnern zeigen die Karten ihren Ordner; gleichnamige Projekte heißen „Name (Ordner)“. +Scan- und Backup-Stand gelten je Ordner; „Backup“ sichert alle angezeigten Ordner. Im Backup-Ziel landet der erste +Ordner direkt, jeder weitere in einem Unterordner mit seinem Namen (liegt er im ersten Ordner: sein Pfad darunter). + +**Git im Info-Tab:** Remote (SSH `git@github.com:name/projekt.git` oder https) eintragen/ändern, „Git einrichten“ +(`git init -b main`) für Projekte ohne Repo, „Push“ bzw. „Commit & Push“ mit Nachricht – läuft in einem +Konsolenfenster (SSH-Passphrase/Fehler sichtbar). Der eigene SSH-Public-Key lässt sich dort kopieren. + +**Neu / Klonen:** Knopf „Neu“ oben legt ein leeres Projekt (Ordner + `README.md` + `.dashboard.json`) oder einen Klon an, +„Klonen“ im Projekt-Panel klont direkt. Ziel: beliebiger Projektordner. Der Klon lässt `node_modules`, Caches und +(abwählbar) Build-Ordner weg, den git-Verlauf nur auf Wunsch; er startet als „Idee“ ohne itch.io-Link, nur mit offenen Aufgaben. + +Voraussetzung: Windows 10/11 mit WebView2 (bei Windows 11 immer dabei; fehlt sie, zeigt die exe den Download-Link). +Git, VS Code, Unity usw. sind optional – fehlen sie, fehlen nur die passenden Anzeigen/Knöpfe. + +Eigener Rechner (dieser Ordner): Einstellungen kommen automatisch aus dem Ordner-Aufbau +(`\_Tools\ProjectDashboard`) und `_Tools\Backup\backup-config.json`; Änderungen im Zahnrad-Menü +werden auch dorthin geschrieben, damit `backup-projekte.bat` dasselbe sichert. + +**exe neu bauen** (nach Änderungen an `launcher\`): `powershell -ExecutionPolicy Bypass -File build.ps1` +(braucht .NET SDK 8+). Icon neu zeichnen: `launcher\make-icon.ps1`, dann `launcher\app.ico` löschen und bauen. +Änderungen an `server.js`, `lib\` oder `public\` brauchen keinen Neubau – nur das Fenster neu öffnen. + +Zweite Instanz zum Testen: `DASHBOARD_PORT=4849` setzen (gilt für exe und Server). + +## Ansichten & Bedienung + +- **Board** (Kanban; Umschalter **Karten | Liste** – „Liste“ = zwei Zeilen pro Projekt: Name, darunter Größe, + letzte Änderung, Git, Backup, offene Aufgaben; mit ▶, ebenfalls per Drag & Drop verschiebbar; die Wahl wird gemerkt). + **Größe** = Ordnergröße aus dem Scan. **Letzte Änderung** = neueste Datei im Projekt (ohne node_modules, Build-, + Cache- und .git-Ordner; Tooltip nennt die Datei), wird im Hintergrund ermittelt und alle 5 Minuten aufgefrischt. + „Zuletzt geändert“ sortiert danach. **Galerie** (Kacheln mit Icon, Hover: Starten / Ordner / VS Code), **Liste** (Tabelle, Spaltenkopf klicken = sortieren), + **Aufgaben** (alle Aufgaben aller Projekte: Offen / Erledigt / Alle, abhaken, löschen, oben oder pro Projekt neue eintragen; Zähler am Reiter = offene Aufgaben). +- **VS-Code-Knopf ``** links neben ▶ auf Karten und Zeilen (Galerie: Hover „Code“, Liste: eigener Knopf). +- **▶ Schnellstart** auf Karte, Kachel und in der Liste: festgelegtes Programm (Aktionen → 📌) → eigener Start-Befehl → + sonst Haupt-exe (zum Projektnamen passend, „Server/Helper“ nach hinten, beste Kopie aus publish/release/dist/bin) → + sonst HTML-Seite, die per Doppelklick läuft (`release\*.html` → `game\index.html` → `index.html` / `.html`; + Vite-/Modul-Seiten nicht, die laufen über npm) → sonst Start-Skript (.bat mit „start/run/spiel …“ im Namen) → + sonst erste Start-Aktion (Unity, npm run dev, Python …). Vite-Server öffnen dabei den Browser (`-- --open`), + fehlt `node_modules`, läuft vorher `npm install`. Fehlt die Datei, kommt eine Meldung statt eines stillen Fehlschlags. +- **itch.io veröffentlicht** (🚀 rot, Klick öffnet die Spielseite): auf Karte, Zeile, Kachel, Liste und im Editor. + Das Dashboard liest das öffentliche Profil (Einstellungen → „itch.io-Profil“, hier `https://sn09.itch.io`, + stündlich, ↻ = sofort) und ordnet Spiele per Namen zu (gleicher Name, oder itch-Titel = Projektname + kurzer + Zusatz). Im Editor unter **Bearbeiten → itch.io-Seite**: leer = automatisch, Link = manuell (`"itch"` in + `.dashboard.json`), `-` = „nicht veröffentlicht“. Die Einstellungen zeigen itch-Spiele ohne Projekt. + Schnellfilter **itch.io** und **Fertig, nicht auf itch**. +- Kennzahlen oben: Projekte, ohne Backup (klickbar = filtern), belegter Speicher, aufräumbar (klickbar), Scan-Fortschritt. +- Schnellfilter-Chips: Ohne Backup, Ungesichert, Aufräumbar, npm install, Ohne Icon, Generator-Kopie. +- Seitenpanel rechts (Klick auf Projekt), `Esc` schließt, `/` springt in die Suche. +- Darstellung oben rechts wählbar: **Hell / System / Dunkel** (System folgt Windows, auch live). Wird im Browser gemerkt; per Link: `?theme=light` / `?theme=dark`. +- Direktlinks: `#gallery`, `#list`, `#board/GallerySwiper/info` (öffnet Projekt + Reiter). +- Icons: [Lucide](https://lucide.dev) (ISC-Lizenz), lokal aus `node_modules/lucide-static` unter `/icons.svg`. + +## Backup auf die MyCloud + +Knopf **Backup** oben (zeigt „vor … Tagen“, gelb wenn älter als 7 Tage oder noch nie): + +1. **Prüfen, was neu ist** – listet neue / geänderte Dateien (fehlen im Backup) und Dateien, die nur noch im Backup liegen, mit Größe pro Projekt. +2. **Jetzt kopieren** – kopiert genau das, mit Fortschrittsbalken, abbrechbar. + +**Einzelnes Projekt:** im Projekt unter **Aktionen → Sichern auf MyCloud → Jetzt sichern**. Ein Klick prüft +`\` und kopiert sofort, was fehlt oder sich geändert hat (mit Fortschritt). Dort steht auch +„zuletzt gesichert“ (eigenes Projekt-Backup oder letztes Komplett-Backup, was neuer ist). +Es läuft immer nur ein Backup gleichzeitig. + +**Mehrere Backup-Ziele** (z. B. MyCloud + USB-Platte): Zahnrad → „Ziel hinzufügen“ (Name + Ordner). Jedes Ziel hat +seinen eigenen Stand. Im Backup-Fenster und unter „Sichern“ im Projekt oben das Ziel per Reiter wählen – die Wahl gilt +auch für die Backup-Anzeige auf Karten/Kacheln/Liste. Im Projekt steht zusätzlich „Alle Ziele“ mit dem Stand jedes Ziels. +Es läuft immer nur ein Backup gleichzeitig. Ein Ziel muss beim Eintragen erreichbar sein. + +Im Backup wird **nie** etwas gelöscht. Nicht gesichert: `node_modules`, `__pycache__`, `.gradle`, `.venv`, `.bin` +(`.bin`: Build-Ausgaben; die WD MyCloud versteckt Ordner mit diesem Namen, sie ließen sich dort gar nicht anlegen). +Scheitern bei einem Komplett-Backup einzelne Ordner, gilt nur das betroffene Projekt als „unvollständig“ (rot), +alle anderen als gesichert. +Ziele und Ausnahmen: `_Tools\Backup\backup-config.json` – dieselbe Datei nutzt `backup-projekte.bat` +(ohne Dashboard, auch für die Aufgabenplanung; sichert auf das **erste** Ziel der Liste). Protokolle: `_Tools\Backup\logs\`. +Schließen der exe während eines Backups fragt nach und bricht es sauber ab (Kopiertes bleibt). + +## Projektverwaltung (Karten, Galerie, Editor) + +Jede Karte/Kachel zeigt zusätzlich: + +- **Ampel Git/Backup**: 🔴 kein Git oder kein Remote (liegt nur auf dieser Platte) · + 🟡 ungesicherte Änderungen, nicht gepusht oder kein Upstream · 🟢 gesichert. +- **Technik** (Unity, Node/Electron/Expo/Capacitor, .NET, Flutter, Android, C++/CMake, Python, Web, Arduino) + und „npm install nötig“, wenn `node_modules` fehlt. +- **Speicher** (nach Scan): Größe und 🧹 löschbare Menge. +- **Werkzeuge**: „ComfyGen“ = Generator nutzt `_Tools\ComfyGen` · „eigene Generator-Kopie“ = eigene Skripte. +- **Icon**: echtes App-Icon (Android `mipmap…/ic_launcher`, `.ico`, `icon.png`, `logo`) wird als Bild genutzt, + sonst „kein Icon“. + +Kopfzeile: Anzahl ohne Backup, Gesamtgröße, löschbar (Cache / alles), **💾 Alle scannen**. +Galerie: Filter „Zeigen“ (ohne Backup, ohne Icon, aufräumbar, npm install nötig, Generator-Kopie), Sortierung nach Größe. + +Editor-Reiter: + +- **Info** – Git-Details + **git push** (in sichtbarer Konsole), Technik, Generator, Icon + (fehlt es: fertiger `gen generate icon`-Befehl zum Kopieren), Speicher mit Ordnerliste. + **Scannen** misst das Projekt, **Ausgewählte löschen** löscht angehakte Ordner (Cache ist vorausgewählt, + fertige Builds/Rohbilder nur bewusst). Was löschbar ist, entscheidet `_Tools\Cleanup\cleanup.ps1` + (Ordner mit git-getrackten Dateien bleiben immer). +- **Aktionen** – oben **Programm starten**: gefundene exe und HTML-Seiten als große Knöpfe. 📌 an einem Knopf legt fest, + was ▶ auf der Karte startet; darunter Feld + **Durchsuchen…** (Datei-Dialog, nur in der exe) für jede andere Datei im + Projekt (exe, html, bat, cmd, lnk) und ↺ zum Zurücksetzen auf „automatisch“ (`"program"` in `.dashboard.json`, Pfad relativ + zum Projekt). Dann VS Code, Explorer, Konsole, npm install / npm run …, dotnet build/run, flutter run, + Unity (passende Editor-Version), Gradle, Python (.venv wenn vorhanden), Generator-Konsole. + Befehle laufen **sichtbar** in einem eigenen Konsolenfenster. +- **Bearbeiten** – wie bisher, plus **Eigener Start-Befehl** (`"start"` in `.dashboard.json`). + +Sicherheit: Server hört nur auf `127.0.0.1`; Anfragen mit fremdem `Host` oder (bei Änderungen) fremdem +`Origin` werden abgelehnt (403). Der Browser schickt nur die ID einer Aktion – die Befehle selbst baut der Server. +Scan-Ergebnisse liegen in `.cache\scan.json`. + +Code: `server.js` (Routen), `lib\git.js`, `lib\tech.js`, `lib\storage.js`, `lib\tools.js`, `lib\icons.js`, `lib\proc.js`. + +## Tabs + +Oben zwischen **Board** (Kanban) und **Galerie** (Thumbnail-Kacheln) umschalten. + +### Galerie + +- Kachel pro Projekt mit Vorschaubild, Name, Status-Chip, Prioritäts-Punkt + und Datum. Klick auf die Kachel öffnet dasselbe Bearbeiten-Fenster wie im + Board, der 📂-Knopf oben rechts öffnet direkt den Ordner im Explorer. +- Das Vorschaubild wird automatisch im Projektordner gesucht (bis 3 Ebenen + tief, `node_modules`/`.git`/Build-Ordner werden übersprungen). Bevorzugt + werden Dateien wie `icon`, `logo`, `thumb`, `preview`, `screenshot`, + `cover`, `splash` und flach liegende Bilder. +- Ohne passendes Bild zeigt die Kachel eine farbige Kachel mit den + Anfangsbuchstaben (Farbe ist pro Projektname stabil). +- Manuell festlegen: Feld **Thumbnail** im Bearbeiten-Fenster, Pfad relativ + zum Projektordner (z.B. `assets/icon.png`); landet als `"thumbnail"` in + der `.dashboard.json`. +- Raster: feste 10 Kacheln pro Reihe, auf schmalen Fenstern stufenweise + weniger (6 unter 1400px, 4 unter 1000px, 2 unter 640px). +- Eigene Filter für Status und Sortierung (zuletzt geändert / Name / + Priorität); die Suche oben filtert beide Tabs. +- Gefundene Bilder werden 5 Minuten im Speicher gecacht, Speichern eines + Projekts leert dessen Cache sofort. + +## Wie es funktioniert + +- Scannt jeden Unterordner von `D:\Oculusquest\Projekt` (außer sich selbst). +- Zeigt pro Projekt: Status-Spalte (Idee/Aktiv/Pausiert/Fertig/Archiviert), + Priorität, Tags, Notizen, Aufgaben-Fortschritt, und wenn vorhanden das + letzte Git-Commit-Datum - sonst den Zeitpunkt der letzten + Ordner-Änderung als Fallback. +- **Drag & Drop**: Karten zwischen Spalten ziehen ändert den Status direkt. +- **Aufgaben**: Klick auf eine Karte öffnet das Bearbeiten-Fenster - dort + Aufgaben anlegen (Enter oder +), abhaken, löschen. Die Karte zeigt den + Fortschritt als Balken (z.B. "2/5 ✓"). +- **Tags**: frei vergebbar (mit Komma getrennt), werden als Chips auf der + Karte angezeigt und von der Suche mit durchsucht. +- **Suche**: Feld oben rechts filtert live über Name, Notizen und Tags. +- **📂 Ordner**: Knopf im Bearbeiten-Fenster öffnet den Projektordner im + Windows Explorer. +- Speichern schreibt `.dashboard.json` in den Projektordner. +- Neue Projektordner tauchen automatisch in der Spalte "Idee" auf, sobald + du die Seite neu lädst. +- Innerhalb einer Spalte sortiert: hohe Priorität zuerst, dann zuletzt + geändert. + +## Bekannte Einschränkung + +Die Git-Commit-Erkennung ruft `git` als Kindprozess auf. Falls das in +deiner Umgebung nicht klappt (z.B. `git` nicht im PATH der Node-Umgebung), +fällt die Karte automatisch auf das Ordner-Änderungsdatum zurück - keine +Fehlfunktion, nur ein fehlendes Detail. + +Galerie-Bilder werden in Originalgröße ausgeliefert (keine serverseitige +Skalierung, dafür keine zusätzliche Abhängigkeit). Bei sehr großen PNGs +lädt die Kachel entsprechend etwas länger - lokal unkritisch, die Bilder +werden lazy geladen. diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..9a19037 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,85 @@ +# Builds the dashboard exe. +# +# powershell -ExecutionPolicy Bypass -File build.ps1 -> ProjectDashboard.exe next to server.js +# small, for this folder: uses the installed Node.js and .NET 8 Desktop Runtime. +# +# powershell -ExecutionPolicy Bypass -File build.ps1 -Release -> release\ProjectDashboard.exe +# ONE exe to pass on: .NET runtime, node.exe and all dashboard files are inside. +# On another PC it unpacks itself to %LOCALAPPDATA%\ProjectDashboard on first start +# and asks for the projects folder and the backup target. +# +# Needs the .NET 8+ SDK (and Node.js on this PC, which is copied into the release exe). +param([switch]$Release) +$ErrorActionPreference = 'Stop' +$here = $PSScriptRoot +$launcher = Join-Path $here 'launcher' +$csproj = Join-Path $launcher 'ProjectDashboard.csproj' + +if (-not (Test-Path (Join-Path $launcher 'app.ico'))) { & (Join-Path $launcher 'make-icon.ps1') } + +if (-not $Release) { + $stage = Join-Path $launcher 'publish' + dotnet publish $csproj -c Release -o $stage --nologo -v q + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed ($LASTEXITCODE)" } + Copy-Item (Join-Path $stage 'ProjectDashboard.exe') (Join-Path $here 'ProjectDashboard.exe') -Force + Remove-Item $stage -Recurse -Force + Write-Host "-> $(Join-Path $here 'ProjectDashboard.exe')" + return +} + +# ── release: assemble the payload ──────────────────────────────────────────── +$payload = Join-Path $launcher 'payload-stage' +$zip = Join-Path $launcher 'payload.zip' +if (Test-Path $payload) { Remove-Item $payload -Recurse -Force } +New-Item -ItemType Directory $payload | Out-Null + +Write-Host '1/3 Paket zusammenstellen ...' +foreach ($f in 'server.js', 'package.json') { Copy-Item (Join-Path $here $f) $payload } +foreach ($d in 'lib', 'public') { Copy-Item (Join-Path $here $d) (Join-Path $payload $d) -Recurse } + +# node_modules: everything the server needs, but from lucide-static only the icon sprite +$nm = Join-Path $payload 'node_modules' +New-Item -ItemType Directory $nm | Out-Null +Get-ChildItem (Join-Path $here 'node_modules') -Directory -Force | Where-Object { $_.Name -ne 'lucide-static' -and $_.Name -ne '.bin' } | + ForEach-Object { Copy-Item $_.FullName (Join-Path $nm $_.Name) -Recurse } +$lucide = Join-Path $nm 'lucide-static' +New-Item -ItemType Directory $lucide | Out-Null +foreach ($f in 'sprite.svg', 'LICENSE', 'package.json') { Copy-Item (Join-Path $here "node_modules\lucide-static\$f") $lucide } + +# cleanup.ps1 (shipped copy, used when the projects folder has no _Tools\Cleanup) +$cleanup = Join-Path (Split-Path $here -Parent) 'Cleanup\cleanup.ps1' +New-Item -ItemType Directory (Join-Path $payload 'tools') | Out-Null +Copy-Item $cleanup (Join-Path $payload 'tools\cleanup.ps1') + +# node.exe of this PC (MIT license, copied alongside) +$nodeExe = (Get-Command node -ErrorAction Stop).Source +New-Item -ItemType Directory (Join-Path $payload 'node') | Out-Null +Copy-Item $nodeExe (Join-Path $payload 'node\node.exe') +$nodeLicense = Join-Path (Split-Path $nodeExe -Parent) 'LICENSE' +if (Test-Path $nodeLicense) { Copy-Item $nodeLicense (Join-Path $payload 'node\LICENSE') } +Set-Content -Encoding UTF8 (Join-Path $payload 'THIRD-PARTY.txt') @" +Enthaltene Software: +- Node.js $(& $nodeExe --version) (MIT) - node\LICENSE +- Express (MIT) - node_modules\express +- Lucide Icons (ISC) - node_modules\lucide-static\LICENSE +"@ + +Write-Host '2/3 Packen ...' +if (Test-Path $zip) { Remove-Item $zip -Force } +Add-Type -AssemblyName System.IO.Compression.FileSystem +[IO.Compression.ZipFile]::CreateFromDirectory($payload, $zip, [IO.Compression.CompressionLevel]::Optimal, $false) + +# ── release: one self-contained exe with the payload inside ───────────────── +Write-Host '3/3 exe bauen ...' +$stage = Join-Path $launcher 'publish-portable' +dotnet publish $csproj -c Release -p:Portable=true -o $stage --nologo -v q +if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed ($LASTEXITCODE)" } +$outDir = Join-Path $here 'release' +New-Item -ItemType Directory -Force $outDir | Out-Null +$out = Join-Path $outDir 'ProjectDashboard.exe' +Copy-Item (Join-Path $stage 'ProjectDashboard.exe') $out -Force + +Remove-Item $stage, $payload, $zip -Recurse -Force +# the normal build must not pick up the self-contained restore state +Remove-Item (Join-Path $launcher 'obj') -Recurse -Force -ErrorAction SilentlyContinue +Write-Host ("-> {0} ({1:N0} MB)" -f $out, ((Get-Item $out).Length / 1MB)) diff --git a/launcher/Program.cs b/launcher/Program.cs new file mode 100644 index 0000000..b08fd99 --- /dev/null +++ b/launcher/Program.cs @@ -0,0 +1,364 @@ +using System.Diagnostics; +using System.IO.Compression; +using System.Reflection; +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.Web.WebView2.Core; +using Microsoft.Web.WebView2.WinForms; + +namespace ProjectDashboard; + +static class Program +{ + [STAThread] + static void Main() + { + ApplicationConfiguration.Initialize(); + Application.Run(new MainForm()); + } +} + +// One window: makes sure the Node server runs, then shows +// http://127.0.0.1:4848 in WebView2. A server that is already running +// (second window, start-dashboard.bat) is reused and left alone. +// +// Two modes: +// source - server.js lies next to the exe (Michi's _Tools\ProjectDashboard): +// system Node, data in the app's .cache folder. +// portable - the exe carries everything as embedded payload.zip (node.exe + +// dashboard files) and unpacks it once to %LOCALAPPDATA%\ProjectDashboard\app\. +sealed class MainForm : Form +{ + // DASHBOARD_PORT (also read by server.js) allows a second instance, e.g. for tests + static readonly int Port = int.TryParse(Environment.GetEnvironmentVariable("DASHBOARD_PORT"), out var p) ? p : 4848; + static readonly string BaseUrl = $"http://127.0.0.1:{Port}/"; + // DASHBOARD_HOME moves everything (window state, WebView2, unpacked app, data) - used for tests + static readonly string DataDir = Environment.GetEnvironmentVariable("DASHBOARD_HOME") is { Length: > 0 } home + ? Path.GetFullPath(home) + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ProjectDashboard"); + const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"; + + string appDir = AppContext.BaseDirectory; + bool portable; + readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false }; + readonly Label status = new() + { + Dock = DockStyle.Fill, + TextAlign = ContentAlignment.MiddleCenter, + Font = new Font("Segoe UI", 12f), + ForeColor = Color.FromArgb(107, 113, 131), + }; + Process? server; // only set when this window started the server + StreamWriter? serverLog; + + public MainForm() + { + Text = "Projekte"; + Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); + MinimumSize = new Size(900, 560); + RestoreWindow(); + FormClosing += (_, e) => + { + if (server != null && BackupRunning() && + MessageBox.Show(this, "Das Backup läuft noch.\n\nBeim Schließen wird es abgebrochen (bereits kopierte Dateien bleiben). Trotzdem schließen?", + "Projekte", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) + { + e.Cancel = true; + return; + } + SaveWindow(); + }; + BackColor = Color.FromArgb(245, 246, 250); + status.Text = "Starte Dashboard …"; + Controls.Add(web); + Controls.Add(status); + Shown += async (_, _) => await StartAsync(); + FormClosed += (_, _) => StopServer(); + } + + async Task StartAsync() + { + try + { + Directory.CreateDirectory(DataDir); + if (!await IsServerUp()) + { + string node; + if (File.Exists(Path.Combine(appDir, "server.js"))) + { + node = FindNode() ?? throw new Exception("Node.js nicht gefunden. Bitte von nodejs.org installieren."); + if (!Directory.Exists(Path.Combine(appDir, "node_modules"))) + { + status.Text = "Installiere einmalig die Abhängigkeiten (npm install) …"; + await RunHidden("cmd.exe", "/c npm install --no-audit --no-fund", Path.GetDirectoryName(node)!); + } + } + else + { + status.Text = "Richte das Dashboard ein …"; + appDir = await Task.Run(UnpackPayload); + portable = true; + node = Path.Combine(appDir, "node", "node.exe"); + } + StartServer(node); + status.Text = "Starte Server …"; + var until = DateTime.Now.AddSeconds(25); + while (!await IsServerUp()) + { + if (server is { HasExited: true }) throw new Exception($"Server ist abgestürzt. Details:\n{Path.Combine(DataDir, "server.log")}"); + if (DateTime.Now > until) throw new Exception($"Server antwortet nicht (Port {Port} belegt?)."); + await Task.Delay(300); + } + } + + var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2")); + await web.EnsureCoreWebView2Async(env); + var core = web.CoreWebView2; + core.Settings.IsStatusBarEnabled = false; + core.Settings.AreDevToolsEnabled = true; + // Anything outside the dashboard opens in the normal browser. + core.NewWindowRequested += (_, e) => { e.Handled = true; OpenExternal(e.Uri); }; + core.NavigationStarting += (_, e) => + { + if (!e.Uri.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenExternal(e.Uri); } + }; + core.DocumentTitleChanged += (_, _) => Text = core.DocumentTitle; + core.WebMessageReceived += OnWebMessage; + if (savedZoom is > 0.3 and < 3) web.ZoomFactor = savedZoom; + web.Source = new Uri(BaseUrl); + web.Visible = true; + status.Visible = false; + } + catch (WebView2RuntimeNotFoundException) + { + ShowError("Für das Fenster fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken, um sie herunterzuladen und zu installieren,\ndanach das Dashboard neu starten."); + status.Cursor = Cursors.Hand; + status.Click += (_, _) => OpenExternal(WebView2Download); + } + catch (Exception ex) + { + ShowError("Dashboard konnte nicht starten:\n\n" + ex.Message); + } + } + + void ShowError(string text) + { + status.Text = text; + status.ForeColor = Color.FromArgb(220, 38, 38); + status.Visible = true; + web.Visible = false; + } + + // The page asks for a folder dialog ("Durchsuchen…" in the settings): + // { type: "pickFolder", id, title, initial } → { type: "folderPicked", id, path } + // or for a file dialog (program to start in "Aktionen"): + // { type: "pickFile", id, title, initial } → { type: "filePicked", id, path } + void OnWebMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e) + { + if (!e.Source.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) return; + try + { + using var doc = JsonDocument.Parse(e.WebMessageAsJson); + var m = doc.RootElement; + if (m.ValueKind != JsonValueKind.Object) return; + var type = m.GetProperty("type").GetString(); + if (type != "pickFolder" && type != "pickFile") return; + var id = m.GetProperty("id").GetString() ?? ""; + var title = m.TryGetProperty("title", out var t) ? t.GetString() : null; + var initial = m.TryGetProperty("initial", out var i) ? i.GetString() : null; + if (type == "pickFile") + { + BeginInvoke(() => + { + using var fd = new OpenFileDialog + { + Title = title ?? "Datei wählen", + Filter = "Programme und Seiten (*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk)|*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk|Alle Dateien (*.*)|*.*", + CheckFileExists = true, + DereferenceLinks = false, + }; + if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) fd.InitialDirectory = initial; + var file = fd.ShowDialog(this) == DialogResult.OK ? fd.FileName : ""; + web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "filePicked", id, path = file })); + }); + return; + } + BeginInvoke(() => + { + using var dlg = new FolderBrowserDialog + { + Description = title ?? "Ordner wählen", + UseDescriptionForTitle = true, + ShowNewFolderButton = true, + }; + if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) dlg.InitialDirectory = initial; + var path = dlg.ShowDialog(this) == DialogResult.OK ? dlg.SelectedPath : ""; + web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "folderPicked", id, path })); + }); + } + catch { } + } + + // Unpacks the embedded payload.zip once per version to \app\ + // and removes older versions. Returns the app folder. + string UnpackPayload() + { + var asm = Assembly.GetExecutingAssembly(); + using var res = asm.GetManifestResourceStream("payload.zip") + ?? throw new Exception("Diese exe enthält kein Dashboard-Paket (server.js fehlt daneben)."); + string hash; + using (var sha = SHA256.Create()) hash = Convert.ToHexString(sha.ComputeHash(res))[..12].ToLowerInvariant(); + var appsRoot = Path.Combine(DataDir, "app"); + var target = Path.Combine(appsRoot, hash); + if (File.Exists(Path.Combine(target, ".ok"))) return target; + + Directory.CreateDirectory(appsRoot); + var tmp = target + ".tmp"; + if (Directory.Exists(tmp)) Directory.Delete(tmp, true); + res.Position = 0; + using (var zip = new ZipArchive(res, ZipArchiveMode.Read)) zip.ExtractToDirectory(tmp); + File.WriteAllText(Path.Combine(tmp, ".ok"), DateTime.Now.ToString("s")); + if (Directory.Exists(target)) Directory.Delete(target, true); + Directory.Move(tmp, target); + foreach (var old in Directory.GetDirectories(appsRoot)) + { + if (!string.Equals(old, target, StringComparison.OrdinalIgnoreCase)) + try { Directory.Delete(old, true); } catch { } // may be in use by another window + } + return target; + } + + // Window size/position/zoom are remembered in %LOCALAPPDATA%\ProjectDashboard\window.txt + // ("x y w h maximized zoom"). First start: maximized. + static readonly string WindowFile = Path.Combine(DataDir, "window.txt"); + double savedZoom = 1.0; + + void RestoreWindow() + { + StartPosition = FormStartPosition.CenterScreen; + Size = new Size(1500, 950); + WindowState = FormWindowState.Maximized; + try + { + var v = File.ReadAllText(WindowFile).Split(' '); + var inv = System.Globalization.CultureInfo.InvariantCulture; + var rect = new Rectangle(int.Parse(v[0]), int.Parse(v[1]), int.Parse(v[2]), int.Parse(v[3])); + savedZoom = double.Parse(v[5], inv); + // only restore a position that is still on a connected screen + if (Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(rect)) && rect.Width >= MinimumSize.Width) + { + StartPosition = FormStartPosition.Manual; + Bounds = rect; + } + WindowState = v[4] == "1" ? FormWindowState.Maximized : FormWindowState.Normal; + } + catch { } + } + + void SaveWindow() + { + try + { + var b = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; + var zoom = web.CoreWebView2 != null ? web.ZoomFactor : savedZoom; + Directory.CreateDirectory(DataDir); + File.WriteAllText(WindowFile, string.Join(' ', b.X, b.Y, b.Width, b.Height, + WindowState == FormWindowState.Maximized ? "1" : "0", + zoom.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + catch { } + } + + static bool BackupRunning() + { + try + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1) }; + var json = http.GetStringAsync(BaseUrl + "api/backup").GetAwaiter().GetResult(); + return json.Contains("\"phase\":\"copying\"") || json.Contains("\"phase\":\"checking\""); + } + catch { return false; } + } + + static async Task IsServerUp() + { + try + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1.5) }; + var res = await http.GetAsync(BaseUrl + "api/scan"); + return res.IsSuccessStatusCode; + } + catch { return false; } + } + + string? FindNode() + { + foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries)) + { + try + { + var p = Path.Combine(dir.Trim('"'), "node.exe"); + if (File.Exists(p)) return p; + } + catch { } + } + var std = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "nodejs", "node.exe"); + return File.Exists(std) ? std : null; + } + + void StartServer(string node) + { + serverLog = new StreamWriter(Path.Combine(DataDir, "server.log"), append: false) { AutoFlush = true }; + var psi = new ProcessStartInfo(node, "server.js") + { + WorkingDirectory = appDir, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + // npm/git/code started by the server must be found + psi.Environment["PATH"] = Path.GetDirectoryName(node) + ";" + Environment.GetEnvironmentVariable("PATH"); + // portable: settings, cache and logs live next to the window state, not in the unpacked app + if (portable) psi.Environment["DASHBOARD_DATA"] = Path.Combine(DataDir, "data"); + server = Process.Start(psi) ?? throw new Exception("Node konnte nicht gestartet werden."); + server.OutputDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine(e.Data); }; + server.ErrorDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine("ERR " + e.Data); }; + server.BeginOutputReadLine(); + server.BeginErrorReadLine(); + } + + async Task RunHidden(string exe, string args, string extraPath) + { + var psi = new ProcessStartInfo(exe, args) { WorkingDirectory = appDir, UseShellExecute = false, CreateNoWindow = true }; + psi.Environment["PATH"] = extraPath + ";" + Environment.GetEnvironmentVariable("PATH"); + using var p = Process.Start(psi)!; + await p.WaitForExitAsync(); + if (p.ExitCode != 0) throw new Exception("npm install ist fehlgeschlagen."); + } + + // Only node itself is stopped: programs it launched (Unity, consoles, ...) + // were started detached and keep running. + void StopServer() + { + if (server is { HasExited: false }) + { + // a running backup (robocopy, child of node) is stopped cleanly first + try + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) }; + using var req = new HttpRequestMessage(HttpMethod.Post, BaseUrl + "api/backup/cancel"); + req.Headers.Add("Origin", BaseUrl.TrimEnd('/')); + http.Send(req); + } + catch { } + } + try { if (server is { HasExited: false }) server.Kill(entireProcessTree: false); } catch { } + serverLog?.Dispose(); + } + + static void OpenExternal(string uri) + { + try { Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true }); } catch { } + } +} diff --git a/launcher/ProjectDashboard.csproj b/launcher/ProjectDashboard.csproj new file mode 100644 index 0000000..d38a7cb --- /dev/null +++ b/launcher/ProjectDashboard.csproj @@ -0,0 +1,42 @@ + + + + + WinExe + net8.0-windows + true + enable + enable + ProjectDashboard + ProjectDashboard + app.ico + PerMonitorV2 + Projekt-Dashboard + 1.0.0 + win-x64 + false + true + true + none + de + + $(NoWarn);MSB3277 + + + + + true + true + false + + + + + + + + + + diff --git a/launcher/app.ico b/launcher/app.ico new file mode 100644 index 0000000..d60e65f Binary files /dev/null and b/launcher/app.ico differ diff --git a/launcher/app.png b/launcher/app.png new file mode 100644 index 0000000..ec7d8a4 Binary files /dev/null and b/launcher/app.png differ diff --git a/launcher/make-icon.ps1 b/launcher/make-icon.ps1 new file mode 100644 index 0000000..1f1b5dd --- /dev/null +++ b/launcher/make-icon.ps1 @@ -0,0 +1,63 @@ +# Draws the app icon (indigo/violet rounded square with a white "layers" glyph, +# same look as the dashboard logo) and writes launcher\app.ico with 16-256 px. +Add-Type -AssemblyName System.Drawing +$ErrorActionPreference = 'Stop' +$out = Join-Path $PSScriptRoot 'app.ico' + +function New-IconPng([int]$size) { + $bmp = New-Object System.Drawing.Bitmap $size, $size + $g = [System.Drawing.Graphics]::FromImage($bmp) + $g.SmoothingMode = 'AntiAlias' + $g.Clear([System.Drawing.Color]::Transparent) + + # rounded square with diagonal gradient + $r = [single]($size * 0.22) + $rect = New-Object System.Drawing.RectangleF 0, 0, $size, $size + $path = New-Object System.Drawing.Drawing2D.GraphicsPath + $d = $r * 2 + $path.AddArc(0, 0, $d, $d, 180, 90) + $path.AddArc($size - $d, 0, $d, $d, 270, 90) + $path.AddArc($size - $d, $size - $d, $d, $d, 0, 90) + $path.AddArc(0, $size - $d, $d, $d, 90, 90) + $path.CloseFigure() + $brush = New-Object System.Drawing.Drawing2D.LinearGradientBrush $rect, ([System.Drawing.Color]::FromArgb(99, 102, 241)), ([System.Drawing.Color]::FromArgb(139, 92, 246)), 45 + $g.FillPath($brush, $path) + + # layers glyph: a diamond on top, two chevrons below (Lucide "layers" shape) + $s = $size / 24.0 + $pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White), ([single][Math]::Max(1.2, 1.9 * $s)) + $pen.LineJoin = 'Round'; $pen.StartCap = 'Round'; $pen.EndCap = 'Round' + $ox = 0; $oy = 0.6 * $s + function P($x, $y) { New-Object System.Drawing.PointF ([single]($x * $s + $ox)), ([single]($y * $s + $oy)) } + $g.DrawPolygon($pen, [System.Drawing.PointF[]]@((P 12 4.2), (P 19.5 7.6), (P 12 11), (P 4.5 7.6))) + $g.DrawLines($pen, [System.Drawing.PointF[]]@((P 4.5 11.8), (P 12 15.2), (P 19.5 11.8))) + $g.DrawLines($pen, [System.Drawing.PointF[]]@((P 4.5 15.8), (P 12 19.2), (P 19.5 15.8))) + + $g.Dispose() + $ms = New-Object System.IO.MemoryStream + $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) + $bmp.Dispose() + return , $ms.ToArray() +} + +# ICO container with PNG-compressed entries +$sizes = 16, 24, 32, 48, 64, 128, 256 +$images = foreach ($sz in $sizes) { , (New-IconPng $sz) } +$fs = [System.IO.File]::Create($out) +$w = New-Object System.IO.BinaryWriter $fs +$w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]$sizes.Count) +$offset = 6 + 16 * $sizes.Count +for ($i = 0; $i -lt $sizes.Count; $i++) { + $sz = $sizes[$i]; $data = $images[$i] + $w.Write([byte]($(if ($sz -ge 256) { 0 } else { $sz }))) + $w.Write([byte]($(if ($sz -ge 256) { 0 } else { $sz }))) + $w.Write([byte]0); $w.Write([byte]0) + $w.Write([uint16]1); $w.Write([uint16]32) + $w.Write([uint32]$data.Length); $w.Write([uint32]$offset) + $offset += $data.Length +} +foreach ($data in $images) { $w.Write($data) } +$w.Close() +# also a PNG preview for the dashboard / README +[System.IO.File]::WriteAllBytes((Join-Path $PSScriptRoot 'app.png'), (New-IconPng 256)) +Write-Host "icon -> $out" diff --git a/lib/activity.js b/lib/activity.js new file mode 100644 index 0000000..7acf089 --- /dev/null +++ b/lib/activity.js @@ -0,0 +1,76 @@ +// "Last change" of a project = newest modified file inside it, ignoring +// folders that change by themselves (node_modules, build output, caches, .git). +// The folder's own mtime is useless for this (it only changes when direct +// children are added/removed). Bounded walk, cached for a few minutes. +const fs = require('fs') +const path = require('path') + +const SKIP = /^(node_modules|\.git|\.gradle|\.gradle-local|Library|Temp|Logs|obj|bin|build|builds|dist|out|release|publish|\.venv.*|venv|env|__pycache__|\.cache|\.expo|\.next|\.idea|\.vs|\.vscode|output|CMakeFiles|_deps|\.dart_tool|\.cxx|\.externalNativeBuild|cmake-build-.*)$/i +const IGNORE_FILES = /^(\.dashboard\.json|thumbs\.db|desktop\.ini|\.ds_store)$/i +const MAX_ENTRIES = 30000 +const MAX_DEPTH = 10 +const TTL_MS = 5 * 60 * 1000 +const cache = new Map() // projectPath -> { value, at } + +function scan(projectPath) { + let best = 0 + let bestFile = '' + let seen = 0 + const stack = [{ dir: projectPath, depth: 0 }] + while (stack.length) { + const { dir, depth } = stack.pop() + let entries + try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue } + for (const e of entries) { + if (++seen > MAX_ENTRIES) return finish() + const full = path.join(dir, e.name) + if (e.isDirectory()) { + if (depth < MAX_DEPTH && !SKIP.test(e.name)) stack.push({ dir: full, depth: depth + 1 }) + } else if (e.isFile() && !IGNORE_FILES.test(e.name)) { + let m = 0 + try { m = fs.statSync(full).mtimeMs } catch { continue } + if (m > best) { best = m; bestFile = full } + } + } + } + return finish() + function finish() { + return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES } : null + } +} + +// Scans run in the background, one project per tick, so the server stays +// responsive; the list always gets the latest known value right away. +const queue = [] +const queued = new Set() +let running = false + +function enqueue(projectPath) { + if (queued.has(projectPath)) return + queued.add(projectPath) + queue.push(projectPath) + if (!running) { running = true; setImmediate(work) } +} + +function work() { + const p = queue.shift() + if (!p) { running = false; return } + queued.delete(p) + try { cache.set(p, { value: scan(p), at: Date.now() }) } catch {} + setImmediate(work) +} + +// -> { at, file, partial } | null (empty project) | undefined (not known yet); +// a stale or missing value is refreshed in the background. +function lastChange(projectPath) { + const c = cache.get(projectPath) + if (!c || Date.now() - c.at > TTL_MS) enqueue(projectPath) + return c ? c.value : undefined +} + +function warm(projectPaths) { for (const p of projectPaths) enqueue(p) } +function pending() { return queue.length + (running ? 1 : 0) } +function forget(projectPath) { cache.delete(projectPath) } +function clear() { cache.clear(); queue.length = 0; queued.clear() } + +module.exports = { lastChange, warm, pending, forget, clear } diff --git a/lib/backup.js b/lib/backup.js new file mode 100644 index 0000000..f1b55a2 --- /dev/null +++ b/lib/backup.js @@ -0,0 +1,344 @@ +// Backup to one or more targets (folder / drive / NAS), in two steps like +// _Tools\Backup\backup-projekte.ps1: +// check: robocopy /L lists what is new/changed (missing in the backup) and +// what exists only in the backup +// copy: robocopy /E copies exactly that - nothing is ever deleted in the backup +// Scope: all shown projects folders (scope = null; several can be selected, +// see lib/settings.js) or one project (\ -> \). +// Each projects folder lands in its own place on the target (settings.backupSubdir): +// the first registered folder directly in the target, further ones in a subfolder. +// One job at a time (for one target), in the background; the UI polls getState(). +// Excludes come from the settings, which also keep _Tools\Backup\backup-config.json +// in sync (backup-projekte.bat uses the first target). Every projects folder keeps +// its own "last backup" info per target. +const fs = require('fs') +const path = require('path') +const { spawn } = require('child_process') +const settings = require('./settings') + +let roots = [] // selected projects folders (paths) +let keyOf = (root, folder) => folder // display name of a project (set by the server) +let logDir = null +const STATE_FILE = path.join(settings.DATA_DIR, 'backup.json') + +// the running / last job +const state = { + phase: 'idle', // idle | checking | ready | copying | done | cancelled | error + target: null, // target id of the job + scope: null, // null = everything, else the project's display name + autoCopy: false, // copy right after the check (per-project "Sichern") + error: null, + check: null, // summary of the last check + progress: null, // { files, filesTotal, bytes, bytesTotal, current } +} +let job = null // { scope: {root, folder} | null, items: [{ root, source, target }] } +let all = {} // root (lower case) -> target id -> { path, last, lastByProject } +let child = null + +const rootKey = (r) => (r ?? '').toLowerCase() +const targets = () => settings.get().backup.targets +const targetById = (id) => targets().find((t) => t.id === id) ?? null +// where a projects folder lands on a target +const destOf = (t, root) => path.join(t.path, settings.backupSubdir(root)) +// per root and target; starts fresh when the destination changed +function dataFor(t, root) { + const r = (all[rootKey(root)] ??= {}) + let d = r[t.id] + const dest = destOf(t, root) + if (!d || d.path.toLowerCase() !== dest.toLowerCase()) d = r[t.id] = { path: dest, last: null, lastByProject: {} } + return d +} + +// (Re)initialise for the current settings. rootList: selected projects folders, +// key: (root, folder) -> name of the project in the UI. +function init(rootList, key) { + roots = (Array.isArray(rootList) ? rootList : [rootList]).filter(Boolean) + if (key) keyOf = key + const first = roots[0] ?? '' + const own = first ? path.join(first, '_Tools', 'Backup') : '' + logDir = own && fs.existsSync(own) ? path.join(own, 'logs') : path.join(settings.DATA_DIR, 'logs') + if (!busy()) Object.assign(state, { phase: 'idle', target: null, scope: null, error: null, check: null, progress: null }) + all = {} + try { + const saved = JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8')) + if (saved.roots && typeof saved.roots === 'object') all = saved.roots + else if (saved.targets) all[rootKey(saved.root ?? first)] = saved.targets + else { + // old format: one target + const t = targets().find((x) => !saved.target || x.path.toLowerCase() === saved.target.toLowerCase()) + if (t) all[rootKey(first)] = { [t.id]: { path: t.path, last: saved.last ?? null, lastByProject: saved.lastByProject ?? {} } } + } + } catch {} + const ids = new Set(targets().map((t) => t.id)) + for (const r of Object.values(all)) for (const id of Object.keys(r)) if (!ids.has(id)) delete r[id] +} + +function save() { + fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true }) + fs.writeFileSync(STATE_FILE, JSON.stringify({ roots: all }, null, 1)) +} + +function config(targetId) { + const s = settings.get() + if (!s.backup.targets.length) throw new Error('Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.') + const t = targetById(targetId) ?? s.backup.targets[0] + return { t, excludeDirs: s.backup.excludeDirs, excludeFiles: s.backup.excludeFiles } +} + +function baseArgs(cfg) { + return ['/E', '/FFT', '/XJ', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:T', + '/XD', ...cfg.excludeDirs, '/XF', ...cfg.excludeFiles] +} + +// robocopy runs of a job: one per projects folder, or one for a single project +function itemsFor(t, scope) { + if (scope) return [{ root: scope.root, source: path.join(scope.root, scope.folder), target: path.join(destOf(t, scope.root), scope.folder) }] + return roots.map((root) => ({ root, source: root, target: destOf(t, root) })) +} + +const stamp = () => new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '-') +const slug = (s) => (s ? '-' + s.replace(/[^\w.-]+/g, '_').slice(0, 40) : '') + +// Runs robocopy and calls onLine for every line it writes to `logFile`. +// robocopy's stdout uses the old OEM code page (umlauts break), but /UNILOG +// writes real UTF-16 - so the log file is tailed while robocopy runs. +function robocopy(args, logFile, onLine) { + return new Promise((resolve) => { + fs.mkdirSync(path.dirname(logFile), { recursive: true }) + try { fs.unlinkSync(logFile) } catch {} + child = spawn('robocopy', [...args, `/UNILOG:${logFile}`], { windowsHide: true, stdio: 'ignore' }) + const decoder = new TextDecoder('utf-16le') + let offset = 0 + let rest = '' + const buf = Buffer.alloc(1 << 20) + const drain = (final) => { + let fd + try { fd = fs.openSync(logFile, 'r') } catch { return } + try { + for (;;) { + const n = fs.readSync(fd, buf, 0, buf.length, offset) + if (n <= 0) break + offset += n + const lines = (rest + decoder.decode(buf.subarray(0, n), { stream: true })).split(/\r?\n/) + rest = lines.pop() + for (const l of lines) onLine(l) + } + } finally { fs.closeSync(fd) } + if (final && rest) { onLine(rest); rest = '' } + } + const timer = setInterval(() => drain(false), 500) + const finish = (code) => { clearInterval(timer); drain(true); child = null; resolve(code ?? 16) } + child.on('close', finish) + child.on('error', () => finish(16)) + }) +} + +// One file line of robocopy output: "\t\t" +function parseLine(line) { + const parts = line.split('\t').map((s) => s.trim()).filter(Boolean) + if (parts.length < 3) return null + const size = Number(parts[parts.length - 2]) + const file = parts[parts.length - 1] + if (!Number.isFinite(size) || file.endsWith('\\')) return null + return { cls: parts[0], size, file } +} + +function busy() { return state.phase === 'checking' || state.phase === 'copying' } + +// robocopy error line: "2026/11/10 11:17:10 FEHLER 2 (0x00000002) Verzeichnis wird kopiert D:\x\y\" -> path +const ERR_RE = /\b(?:FEHLER|ERROR)\s+\d+\s+\(0x[0-9A-Fa-f]+\).*?\s((?:[A-Za-z]:\\|\\\\).*)$/ +// which project folder a source or target path belongs to (null = none / outside) +function projectOfPath(p, source, target, scopeFolder) { + if (scopeFolder) return scopeFolder + const l = p.toLowerCase() + for (const base of [source, target]) { + const b = base.toLowerCase().replace(/\\$/, '') + '\\' + if (l.startsWith(b)) return p.slice(b.length).split('\\')[0] || null + } + return null +} +// projects with errors in a finished robocopy log (for older records without a "failed" list) +function failedFromLog(log, source, target) { + try { + const out = new Set() + for (const line of fs.readFileSync(log, 'utf16le').split(/\r?\n/)) { + const m = line.match(ERR_RE) + const p = m && projectOfPath(m[1].trim(), source, target, null) + if (p) out.add(p) + } + return [...out] + } catch { return null } +} + +// scope: null = all shown projects folders, or { root, folder } of one project. +// autoCopy: continue with the copy right away (nothing is deleted, so no question needed). +// targetId: which backup target (default: the first one). +function check(scope = null, autoCopy = false, targetId = null) { + if (busy()) return false + const cfg = config(targetId) + const items = itemsFor(cfg.t, scope) + job = { scope, items } + Object.assign(state, { phase: 'checking', target: cfg.t.id, scope: scope ? keyOf(scope.root, scope.folder) : null, autoCopy, error: null, check: null, progress: null }) + run(async () => { + const share = path.dirname(cfg.t.path) + if (!fs.existsSync(cfg.t.path) && !fs.existsSync(share)) throw new Error(`Backup-Ziel „${cfg.t.name}“ nicht erreichbar: ${cfg.t.path} – Laufwerk/NAS angeschlossen und eingeschaltet?`) + const newF = { n: 0, b: 0 }, changed = { n: 0, b: 0 }, extra = { n: 0, b: 0 } + const perProject = new Map() + for (const it of items) { + if (!fs.existsSync(it.source)) throw new Error(`Projektordner fehlt: ${it.source}`) + fs.mkdirSync(it.target, { recursive: true }) + const checkLog = path.join(logDir, `pruefung-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`) + const src = it.source + const rc = await robocopy([src, it.target, ...baseArgs(cfg), '/L', '/X', '/NJH', '/NJS', '/NDL', '/NP', '/FP', '/BYTES'], checkLog, (line) => { + const p = parseLine(line) + if (!p) return + if (p.cls.includes('EXTRA')) { extra.n++; extra.b += p.size; return } + if (!p.file.toLowerCase().startsWith(src.toLowerCase())) return + const bucket = /^(Neue Datei|New File)$/i.test(p.cls) ? newF : changed + bucket.n++; bucket.b += p.size + // group by project (all) or by top-level folder inside the project (one project) + const rel = p.file.slice(src.length).replace(/^\\/, '') + const key = scope + ? (rel.includes('\\') ? rel.split('\\')[0] : '(Projektordner)') + : rel.includes('\\') ? keyOf(it.root, rel.split('\\')[0]) : rel + const e = perProject.get(key) ?? { name: key, files: 0, bytes: 0 } + e.files++; e.bytes += p.size + perProject.set(key, e) + }) + if (state.phase === 'cancelled') return + if (rc >= 8) throw new Error(`Prüfung fehlgeschlagen (robocopy ${rc})`) + } + state.check = { + at: new Date().toISOString(), scope: state.scope, + source: items.map((i) => i.source).join(' + '), target: items.map((i) => i.target).join(' + '), + files: newF.n + changed.n, bytes: newF.b + changed.b, + newFiles: newF.n, newBytes: newF.b, changedFiles: changed.n, changedBytes: changed.b, + extraFiles: extra.n, extraBytes: extra.b, + projects: [...perProject.values()].sort((a, b) => b.bytes - a.bytes), + } + state.phase = 'ready' + if (autoCopy) { + if (state.check.files) startCopy() + else { for (const it of items) record(cfg.t, it.root, scope?.folder, 0, 0, 0, null); state.phase = 'done' } // already complete + } + }) + return true +} + +function copy() { + if (busy() || state.phase !== 'ready' || !state.check || !job) return false + startCopy() + return true +} + +function startCopy() { + const cfg = config(state.target) + const c = state.check + const { scope, items } = job + Object.assign(state, { phase: 'copying', error: null, progress: { files: 0, filesTotal: c.files, bytes: 0, bytesTotal: c.bytes, current: '' } }) + run(async () => { + const problems = [] + for (const it of items) { + const log = path.join(logDir, `backup-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`) + const failed = new Set() // project folders with copy errors + const before = { files: state.progress.files, bytes: state.progress.bytes } + const rc = await robocopy([it.source, it.target, ...baseArgs(cfg), '/MT:16', '/NJH', '/NDL', '/NP', '/FP', '/BYTES'], log, (line) => { + const err = line.match(ERR_RE) + if (err) { const pr = projectOfPath(err[1].trim(), it.source, it.target, scope?.folder); if (pr) failed.add(pr); return } + const p = parseLine(line) + if (!p || p.cls.includes('EXTRA')) return + state.progress.files++ + state.progress.bytes += p.size + state.progress.current = p.file.slice(it.source.length + 1) + }) + if (state.phase === 'cancelled') return + record(cfg.t, it.root, scope?.folder, state.progress.files - before.files, state.progress.bytes - before.bytes, rc, log, [...failed]) + if (rc >= 8) problems.push({ rc, log, failed: [...failed].map((f) => keyOf(it.root, f)) }) + } + if (problems.length) { + const failed = problems.flatMap((p) => p.failed) + const which = failed.length ? ` Betroffen: ${failed.slice(0, 5).join(', ')}${failed.length > 5 ? ' …' : ''} – alle anderen Projekte sind gesichert.` : '' + throw new Error(`Backup unvollständig (robocopy ${problems[0].rc}).${which} Protokoll: ${problems.map((p) => p.log).join(', ')}`) + } + state.phase = 'done' + state.check = null + }) +} + +function record(t, root, folder, files, bytes, rc, log, failed = []) { + const d = dataFor(t, root) + const entry = { at: new Date().toISOString(), files, bytes, rc, log, ok: rc < 8 } + if (rc >= 8) entry.failed = failed + if (folder) d.lastByProject[folder] = entry + else d.last = entry + save() +} + +function cancel() { + if (!busy()) return false + state.phase = 'cancelled' + try { child?.kill() } catch {} + return true +} + +// When the dashboard stops (window closed), don't leave robocopy running orphaned. +process.on('exit', () => { try { child?.kill() } catch {} }) + +function run(fn) { + fn().catch((e) => { state.phase = 'error'; state.error = String(e.message ?? e) }) +} + +// Last time a project (root + folder) was backed up to a target (default: the first one): +// its own backup or the last full one of its projects folder, whichever is newer. +function lastFor(root, folder, targetId) { + const t = targetById(targetId) ?? targets()[0] + if (!t) return null + const d = dataFor(t, root) + const own = d.lastByProject[folder] + // an incomplete full backup still counts for every project that had no errors + let full = null + if (d.last?.ok) full = { at: d.last.at, ok: true, how: 'Komplett-Backup' } + else if (d.last) { + if (!Array.isArray(d.last.failed) && d.last.log) d.last.failed = failedFromLog(d.last.log, root, destOf(t, root)) ?? undefined + if (Array.isArray(d.last.failed)) { + full = d.last.failed.includes(folder) + ? { at: d.last.at, ok: false, how: 'Komplett-Backup – Fehler in diesem Projekt' } + : { at: d.last.at, ok: true, how: 'Komplett-Backup' } + } + } + if (own && (!full || own.at > full.at)) return { ...own, how: 'Projekt' } + return full +} + +// One project on every target: [{ id, name, last }] +function lastOnAllTargets(root, folder) { + return targets().map((t) => ({ id: t.id, name: t.name, last: lastFor(root, folder, t.id) })) +} + +// "Last full backup" of a target over all shown folders: the oldest of them +// (none if one folder was never backed up there), files/bytes added up. +function combinedLast(t) { + const lasts = roots.map((r) => dataFor(t, r).last) + if (!lasts.length || lasts.some((l) => !l)) return null + if (lasts.length === 1) return lasts[0] + const oldest = lasts.reduce((a, b) => (a.at < b.at ? a : b)) + return { + ...oldest, + files: lasts.reduce((a, l) => a + (l.files ?? 0), 0), + bytes: lasts.reduce((a, l) => a + (l.bytes ?? 0), 0), + ok: lasts.every((l) => l.ok), + } +} + +function getState() { + const list = targets().map((t) => { + // per-project entries, keyed like the projects in the UI + const lastByProject = {} + for (const r of roots) for (const [folder, e] of Object.entries(dataFor(t, r).lastByProject)) lastByProject[keyOf(r, folder)] = e + return { id: t.id, name: t.name, path: roots.map((r) => destOf(t, r)).join(' + ') || t.path, short: settings.targetName(t.path), last: combinedLast(t), lastByProject } + }) + if (!list.length) return { ...state, targets: [], configError: 'Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.', notConfigured: true } + return { ...state, source: roots.join(' + '), targets: list } +} + +module.exports = { init, check, copy, cancel, getState, lastFor, lastOnAllTargets, busy } diff --git a/lib/create.js b/lib/create.js new file mode 100644 index 0000000..892ede0 --- /dev/null +++ b/lib/create.js @@ -0,0 +1,73 @@ +// New projects: an empty folder (with .dashboard.json and README.md) or a clone +// of an existing project. Clones are copied with robocopy and leave out what +// can be regenerated (node_modules, caches, optionally build output) and, unless +// asked for, the git history - so the clone does not push to the original's remote. +const fs = require('fs') +const path = require('path') +const { run } = require('./proc') +const settings = require('./settings') + +const STATUS_FILE = '.dashboard.json' +// left out when "Build-Ordner und Caches weglassen" is ticked (on top of the backup excludes) +const BUILD_DIRS = ['dist', 'build', 'out', 'bin', 'obj', 'Library', 'Temp', 'Logs', '.gradle', '.next', 'coverage', '.cache'] +const RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i + +let running = null // name of the project being created + +// Throws with a German message if `name` can't be a Windows folder name. +function checkName(raw) { + const name = typeof raw === 'string' ? raw.trim() : '' + if (!name) throw new Error('Bitte einen Namen eingeben.') + if (name.length > 80) throw new Error('Name zu lang (höchstens 80 Zeichen).') + if (/[<>:"/\\|?*\x00-\x1f%]/.test(name)) throw new Error('Diese Zeichen gehen nicht im Namen: < > : " / \\ | ? * %') + if (/[. ]$/.test(name) || name.startsWith('.')) throw new Error('Der Name darf nicht mit einem Punkt beginnen oder mit Punkt/Leerzeichen enden.') + if (RESERVED.test(name)) throw new Error(`„${name}“ ist unter Windows reserviert.`) + return name +} + +function readMeta(dir) { + try { return JSON.parse(fs.readFileSync(path.join(dir, STATUS_FILE), 'utf-8')) } catch { return {} } +} + +// opts: { rootPath, name, from (absolute project path or null), withGit, skipBuild, status } +async function create(opts) { + if (running) throw new Error(`Es wird gerade schon „${running}“ angelegt.`) + const name = checkName(opts.name) + const dest = path.join(opts.rootPath, name) + if (fs.existsSync(dest)) throw new Error(`Es gibt schon einen Ordner „${name}“ in ${opts.rootPath}.`) + running = name + try { + const now = new Date().toISOString() + if (!opts.from) { + fs.mkdirSync(dest) + fs.writeFileSync(path.join(dest, STATUS_FILE), JSON.stringify({ status: 'idea', priority: 'medium', notes: '', tags: [], tasks: [], updatedAt: now }, null, 2)) + fs.writeFileSync(path.join(dest, 'README.md'), `# ${name}\n`) + return { name, path: dest, cloned: false } + } + const src = opts.from + if (dest.toLowerCase().startsWith(src.toLowerCase() + path.sep)) throw new Error('Der Klon darf nicht im Original liegen.') + const b = settings.get().backup + const xd = [...b.excludeDirs, ...(opts.skipBuild ? BUILD_DIRS : []), ...(opts.withGit ? [] : ['.git'])] + const r = await run('robocopy', [src, dest, '/E', '/XJ', '/R:1', '/W:1', '/COPY:DAT', '/DCOPY:T', '/MT:8', '/NJH', '/NJS', '/NP', '/NFL', '/NDL', + '/XD', ...xd, '/XF', ...b.excludeFiles], { timeout: 60 * 60 * 1000 }) + // robocopy: 0-7 = success, 8+ = errors + if (r.code < 0 || r.code >= 8) throw new Error(`Kopieren fehlgeschlagen (robocopy ${r.code}). Der angefangene Ordner liegt in ${dest}.`) + if (!fs.existsSync(dest)) fs.mkdirSync(dest) + // the clone starts as a fresh idea: same tags/program/start, no itch link, open tasks only + const m = readMeta(src) + const tasks = Array.isArray(m.tasks) ? m.tasks.filter((t) => !t?.done) : [] + const note = `Klon von „${path.basename(src)}“ (${now.slice(0, 10)}).` + fs.writeFileSync(path.join(dest, STATUS_FILE), JSON.stringify({ + ...m, status: 'idea', itch: '', tasks, + notes: m.notes ? `${note}\n\n${m.notes}` : note, + updatedAt: now, + }, null, 2)) + return { name, path: dest, cloned: true } + } finally { + running = null + } +} + +const busy = () => !!running + +module.exports = { create, checkName, busy } diff --git a/lib/git.js b/lib/git.js new file mode 100644 index 0000000..5e1f9c8 --- /dev/null +++ b/lib/git.js @@ -0,0 +1,97 @@ +// Git and backup status of one project: branch, remote, uncommitted changes, +// commits not pushed, last commit. `level` drives the traffic light in the UI. +const fs = require('fs') +const path = require('path') +const { run } = require('./proc') + +// Git is optional (a friend's PC may not have it): checked once. +let gitOk = null +async function gitAvailable() { + if (gitOk === null) gitOk = (await run('git', ['--version'])).ok + return gitOk +} + +async function gitInfo(projectPath) { + if (!fs.existsSync(path.join(projectPath, '.git'))) { + return { isRepo: false, level: 'red', label: 'kein Git', lastCommit: null } + } + if (!(await gitAvailable())) { + return { isRepo: true, level: 'red', label: 'Git nicht installiert', remote: '', branch: '', upstream: '', ahead: 0, behind: 0, dirty: 0, lastCommit: null } + } + const [st, rem, log] = await Promise.all([ + run('git', ['-C', projectPath, '-c', 'core.quotepath=off', 'status', '--porcelain=v2', '--branch'], { timeout: 8000 }), + run('git', ['-C', projectPath, 'remote', '-v']), + run('git', ['-C', projectPath, 'log', '-1', '--format=%ad|%s', '--date=short']), + ]) + + let branch = '', upstream = '', ahead = 0, behind = 0, dirty = 0 + for (const line of st.stdout.split('\n')) { + if (!line) continue + if (line.startsWith('# branch.head ')) branch = line.slice(14).trim() + else if (line.startsWith('# branch.upstream ')) upstream = line.slice(18).trim() + else if (line.startsWith('# branch.ab ')) { + const m = line.match(/\+(\d+) -(\d+)/) + if (m) { ahead = +m[1]; behind = +m[2] } + } else if (!line.startsWith('#')) dirty++ + } + + const remoteLine = rem.stdout.split('\n').find((l) => l.startsWith('origin\t')) ?? rem.stdout.split('\n').find(Boolean) + const remote = remoteLine ? remoteLine.split('\t')[1].replace(/\s+\((fetch|push)\)$/, '') : '' + + let lastCommit = null + const out = log.stdout.trim() + if (out) { + const [date, ...msg] = out.split('|') + lastCommit = { date, message: msg.join('|') } + } + + const parts = [] + if (dirty) parts.push(`${dirty} geändert`) + if (ahead) parts.push(`${ahead} nicht gepusht`) + if (behind) parts.push(`${behind} hinterher`) + let level, label + if (!remote) { level = 'red'; label = ['kein Remote (nur lokal)', ...parts].join(' · ') } + else if (!upstream) { level = 'yellow'; label = ['kein Upstream', ...parts].join(' · ') } + else if (dirty || ahead) { level = 'yellow'; label = parts.join(' · ') } + else { level = 'green'; label = behind ? parts.join(' · ') : 'gesichert' } + + return { isRepo: true, branch, upstream, remote, ahead, behind, dirty, level, label, lastCommit } +} + +// Remote URL as typed in the Info tab: SSH (git@host:user/repo.git, ssh://...) or https. +// Never starts with "-", so it can't be taken for a git option. +const REMOTE_RE = /^(?:[\w.-]+@[\w.-]+:[\w./~-]+|ssh:\/\/[^\s"'`]+|https?:\/\/[^\s"'`]+|git:\/\/[^\s"'`]+)$/ + +// Sets (or with '' removes) the "origin" remote. +async function setRemote(projectPath, url) { + if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.') + if (!fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Kein Git-Repository – erst „Git einrichten“.') + const u = String(url ?? '').trim() + const has = (await run('git', ['-C', projectPath, 'remote'])).stdout.split(/\r?\n/).includes('origin') + if (!u) { + if (has) await run('git', ['-C', projectPath, 'remote', 'remove', 'origin']) + return + } + if (!REMOTE_RE.test(u)) throw new Error('Remote: z. B. git@github.com:name/projekt.git (SSH) oder https://github.com/name/projekt.git') + const r = await run('git', ['-C', projectPath, 'remote', has ? 'set-url' : 'add', 'origin', u]) + if (!r.ok) throw new Error(r.stderr.trim() || 'git remote fehlgeschlagen') +} + +// git init with branch "main" (no commit yet). +async function initRepo(projectPath) { + if (!(await gitAvailable())) throw new Error('Git ist nicht installiert.') + if (fs.existsSync(path.join(projectPath, '.git'))) throw new Error('Ist schon ein Git-Repository.') + const r = await run('git', ['init', '-b', 'main', projectPath]) + if (!r.ok) throw new Error(r.stderr.trim() || 'git init fehlgeschlagen') +} + +// The user's SSH public key (to paste into GitHub/GitLab), or null. +function sshKey() { + const dir = path.join(process.env.USERPROFILE || require('os').homedir(), '.ssh') + for (const n of ['id_ed25519.pub', 'id_ecdsa.pub', 'id_rsa.pub']) { + try { return { file: path.join(dir, n), key: fs.readFileSync(path.join(dir, n), 'utf-8').trim() } } catch {} + } + return null +} + +module.exports = { gitInfo, setRemote, initRepo, sshKey } diff --git a/lib/icons.js b/lib/icons.js new file mode 100644 index 0000000..ffc2744 --- /dev/null +++ b/lib/icons.js @@ -0,0 +1,70 @@ +// Finds a real app icon in a project (Android launcher icon, .ico, icon.png, logo). +// Bounded breadth-first walk; results are cached because the list endpoint +// asks for every project. +const fs = require('fs') +const path = require('path') +const { SKIP } = require('./tech') + +const EXTRA_SKIP = new Set(['Packages', 'test', 'tests', 'node_modules', 'PackageCache']) +const MAX_DEPTH = 8 +const MAX_ENTRIES = 8000 +const TTL_MS = 10 * 60 * 1000 +const cache = new Map() // projectPath -> { result, at } + +function score(rel, fileName) { + const lower = fileName.toLowerCase() + const ext = path.extname(lower) + if (!['.png', '.ico', '.webp', '.jpg', '.jpeg', '.svg'].includes(ext)) return -1 + const base = path.basename(lower, ext) + const relL = rel.toLowerCase().replace(/\\/g, '/') + let s = -1 + if (relL.includes('mipmap') && base.startsWith('ic_launcher')) { + s = 100 + const m = relL.match(/mipmap-(x*)hdpi/) + if (m) s += m[1].length * 2 + if (/foreground|background|monochrome/.test(base)) s -= 30 + if (base.includes('round')) s -= 1 + } else if (ext === '.ico') s = 85 + else if (/^(app[_-]?icon|icon|appicon|launcher[_-]?icon|store[_-]?icon|favicon)([_-]?\d+)?$/.test(base) || /^(app[_-]?icon|icon)[_-]/.test(base)) s = 75 + else if (/^logo([_-]|$)/.test(base)) s = 50 + return s +} + +function scan(projectPath) { + const queue = [{ dir: projectPath, depth: 0 }] + let seen = 0 + let best = null + let bestScore = -1 + while (queue.length) { + const { dir, depth } = queue.shift() + let entries + try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { continue } + for (const e of entries) { + if (++seen > MAX_ENTRIES) return best + if (e.isDirectory()) { + if (depth < MAX_DEPTH && !e.name.startsWith('.') && !SKIP.has(e.name) && !EXTRA_SKIP.has(e.name)) { + queue.push({ dir: path.join(dir, e.name), depth: depth + 1 }) + } + continue + } + if (!e.isFile()) continue + const s = score(path.relative(projectPath, dir), e.name) + if (s > bestScore) { bestScore = s; best = path.join(dir, e.name) } + } + } + return best +} + +// -> absolute path of the icon, or null +function findIcon(projectPath) { + const c = cache.get(projectPath) + if (c && Date.now() - c.at < TTL_MS) return c.result + const result = scan(projectPath) + cache.set(projectPath, { result, at: Date.now() }) + return result +} + +function forget(projectPath) { cache.delete(projectPath) } +function clear() { cache.clear() } + +module.exports = { findIcon, forget, clear } diff --git a/lib/itch.js b/lib/itch.js new file mode 100644 index 0000000..a70317e --- /dev/null +++ b/lib/itch.js @@ -0,0 +1,91 @@ +// itch.io: which projects are published. Reads the public profile page (settings +// "itchProfile", e.g. https://sn09.itch.io) - no API key, no login - and matches the +// game titles/links to project names. A project can override it in .dashboard.json: +// "itch": "" automatic (match by name) +// "itch": "" this page (manual, also for games not listed on the profile) +// "itch": "-" not on itch.io (switch the automatic match off) +const settings = require('./settings') + +const TTL_MS = 60 * 60 * 1000 +const state = { profile: '', games: [], at: 0, error: null } +let pending = null + +const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '') + +function profileUrl() { + return (settings.get().itchProfile ?? '').replace(/\/+$/, '') +} + +// Title +function parse(html, profile) { + const games = [] + const seen = new Set() + const re = /]*\bclass="[^"]*\btitle game_link\b[^"]*"[^>]*>([^<]*)<\/a>/g + for (const m of html.matchAll(re)) { + const href = m[0].match(/\bhref="([^"]+)"/)?.[1] + if (!href || seen.has(href)) continue + seen.add(href) + const title = m[1].replace(/&/g, '&').replace(/'/g, "'").replace(/"/g, '"').trim() + games.push({ title, url: href, slug: href.replace(profile + '/', '').replace(/\/.*$/, '') }) + } + return games +} + +async function refresh() { + const profile = profileUrl() + if (!profile) { Object.assign(state, { profile: '', games: [], at: Date.now(), error: null }); return state } + if (pending) return pending + pending = (async () => { + try { + const res = await fetch(profile + '/', { headers: { 'User-Agent': 'ProjectDashboard' }, signal: AbortSignal.timeout(10000) }) + if (!res.ok) throw new Error(`itch.io antwortet ${res.status}`) + const games = parse(await res.text(), profile) + Object.assign(state, { profile, games, at: Date.now(), error: null }) + } catch (e) { + // keep the last good list; retry after a few minutes instead of an hour + Object.assign(state, { profile, at: Date.now() - TTL_MS + 5 * 60 * 1000, error: String(e.message ?? e) }) + } finally { pending = null } + return state + })() + return pending +} + +// For the project list: fresh enough data, but never hold the page up for long. +async function ensure(maxWaitMs = 3000) { + if (state.profile !== profileUrl() || Date.now() - state.at > TTL_MS) { + const p = refresh() + if (!state.games.length) await Promise.race([p, new Promise((r) => setTimeout(r, maxWaitMs))]) + } + return state +} + +// Same name, or the itch title is the project name plus a short suffix +// ("DataOrganizer" -> "Data Organizer Ultra"). Not the other way round, so +// "CatMaus 2" does not take over "CatMaus". +function autoMatch(name) { + const pn = norm(name) + if (!pn) return null + return state.games.find((g) => norm(g.title) === pn || norm(g.slug) === pn) + ?? state.games.find((g) => pn.length >= 5 && norm(g.title).startsWith(pn) && norm(g.title).length - pn.length <= 6) + ?? null +} + +// -> { url, title, source: 'manual' | 'auto' } or null (not published / switched off) +function forProject(name, manual) { + const m = (manual ?? '').trim() + if (m === '-') return null + if (/^https?:\/\//i.test(m)) { + const g = state.games.find((x) => x.url.replace(/\/+$/, '') === m.replace(/\/+$/, '')) + return { url: m, title: g?.title ?? '', source: 'manual' } + } + const g = autoMatch(name) + return g ? { url: g.url, title: g.title, source: 'auto' } : null +} + +// Games on the profile that no project claims (to spot a missing manual link). +function unmatched(claimedUrls) { + const set = new Set(claimedUrls.map((u) => u.replace(/\/+$/, ''))) + return state.games.filter((g) => !set.has(g.url.replace(/\/+$/, ''))) +} + +module.exports = { ensure, refresh, forProject, unmatched, state, parse } diff --git a/lib/proc.js b/lib/proc.js new file mode 100644 index 0000000..b28fbff --- /dev/null +++ b/lib/proc.js @@ -0,0 +1,81 @@ +// Small process helpers: run a command and collect its output (never throws), +// run async work with limited concurrency, and open a visible console window. +const { execFile, spawn } = require('child_process') +const fs = require('fs') +const path = require('path') + +const RUN_DIR = path.join(__dirname, '..', '.cache', 'run') + +function run(cmd, args, opts = {}) { + return new Promise((resolve) => { + execFile(cmd, args, { + encoding: 'utf-8', + timeout: opts.timeout ?? 5000, + windowsHide: true, + maxBuffer: 64 * 1024 * 1024, + cwd: opts.cwd, + }, (err, stdout, stderr) => resolve({ + ok: !err, + code: err ? (typeof err.code === 'number' ? err.code : -1) : 0, + stdout: stdout ?? '', + stderr: stderr ?? '', + })) + }) +} + +async function pool(items, size, fn) { + const out = new Array(items.length) + let next = 0 + const workers = Array.from({ length: Math.min(size, items.length) }, async () => { + while (next < items.length) { + const i = next++ + out[i] = await fn(items[i], i) + } + }) + await Promise.all(workers) + return out +} + +// Paths end up quoted inside a .cmd file ("cd /d """), so they must not +// contain quotes, % (variable expansion) or line breaks. +function assertSafe(s) { + if (/["%\r\n]/.test(s)) throw new Error(`unsupported character in: ${s}`) +} + +// Opens a new, visible cmd window in `cwd` that runs `command` and stays open. +// The command is written into a small .cmd file, so no shell quoting through +// spawn is needed. `echo on` makes cmd print the command before it runs. +// Commands may contain quotes (call "x.bat", py "main.py"); a line break is +// refused, and % is doubled so file names with % stay literal – except for +// the user's own start command (raw), where %VAR% may be meant. +function openConsole(title, cwd, command, { raw = false } = {}) { + assertSafe(cwd) + if (/[\r\n]/.test(command)) throw new Error('Zeilenumbruch im Befehl') + if (!raw) command = command.replace(/%/g, '%%') + fs.mkdirSync(RUN_DIR, { recursive: true }) + const slug = title.replace(/[^\w.-]+/g, '_').slice(0, 60) + const file = path.join(RUN_DIR, `${slug}.cmd`) + const safeTitle = title.replace(/[^\w .:-]+/g, ' ') + fs.writeFileSync(file, [ + '@echo off', + `title ${safeTitle}`, + `cd /d "${cwd}"`, + 'echo on', + command, + '', + ].join('\r\n')) + spawn('cmd.exe', ['/c', `start "" cmd /k "${file}"`], { + windowsVerbatimArguments: true, detached: true, stdio: 'ignore', + }).unref() +} + +// Starts a GUI program / opens a file with its default app, detached. +// A start error (file gone, no permission) must not crash the server: without an +// 'error' listener Node throws it as an uncaught exception. +function openDetached(exe, args = [], cwd) { + const child = spawn(exe, args, { detached: true, stdio: 'ignore', cwd }) + child.on('error', (e) => console.error(`start failed: ${exe}: ${e.message}`)) + child.unref() +} + +module.exports = { run, pool, openConsole, openDetached, assertSafe } diff --git a/lib/settings.js b/lib/settings.js new file mode 100644 index 0000000..fffa963 --- /dev/null +++ b/lib/settings.js @@ -0,0 +1,284 @@ +// User settings: which folder holds the projects and where backups go. +// Stored in \settings.json. DATA is DASHBOARD_DATA (set by the portable +// exe: %LOCALAPPDATA%\ProjectDashboard\data) or, when run from source, the +// app's own .cache folder. +// +// Michi's setup (app inside \_Tools\ProjectDashboard) needs no +// settings file: the projects folder is two levels up and the backup settings +// come from \_Tools\Backup\backup-config.json, which is also kept in +// sync on save because backup-projekte.bat reads it. +const fs = require('fs') +const path = require('path') + +const APP_DIR = path.join(__dirname, '..') +const DATA_DIR = process.env.DASHBOARD_DATA + ? path.resolve(process.env.DASHBOARD_DATA) + : path.join(APP_DIR, '.cache', process.env.DASHBOARD_ROOT ? 'test' : '') // test instances never touch real data +const FILE = path.join(DATA_DIR, 'settings.json') + +// ".bin": build output (e.g. tests\.bin) – WD MyCloud shares hide folders with that name, so it can't be backed up there anyway +const DEFAULT_EXCLUDE_DIRS = ['node_modules', '__pycache__', '.gradle', '.venv', 'venv', '.venv-tts', '.bin'] +const DEFAULT_EXCLUDE_FILES = ['Thumbs.db', 'desktop.ini', '~$*'] + +// \_Tools\ProjectDashboard → X +function devRoot() { + const parent = path.dirname(APP_DIR) + return path.basename(parent).toLowerCase() === '_tools' ? path.dirname(parent) : '' +} + +const legacyBackupFile = (root) => (root ? path.join(root, '_Tools', 'Backup', 'backup-config.json') : '') + +function readJson(file) { + // strip a BOM (PowerShell's "Out-File -Encoding utf8" writes one) + try { return JSON.parse(fs.readFileSync(file, 'utf-8').replace(/^/, '')) } catch { return null } +} + +// short display name: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup +function targetName(t) { + const unc = t.match(/^\\\\([^\\]+)/) + if (unc) return unc[1] + const drive = t.match(/^([A-Za-z]:)/) + return drive ? `${drive[1]} ${path.basename(t)}`.trim() : path.basename(t) +} +const newId = () => Math.random().toString(36).slice(2, 10) +// one path (older settings / backup-config.json) -> target list +const targetsFrom = (p) => (p ? [{ id: 'main', name: targetName(p), path: p }] : []) + +// Projects folders ("roots"): several can be registered, one is active at a time. +// Display name: folder name, "D:" for a drive root. +const rootName = (p) => path.basename(p) || p.replace(/[\\/]+$/, '') +const rootsFrom = (p) => (p ? [{ id: 'main', name: rootName(p), path: p }] : []) +const MAX_ROOTS = 30 +const samePath = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() +const inside = (child, parent) => path.resolve(child).toLowerCase().startsWith(path.resolve(parent).toLowerCase().replace(/[\\/]+$/, '') + path.sep) + +function defaults() { + const root = process.env.DASHBOARD_ROOT ? path.resolve(process.env.DASHBOARD_ROOT) : devRoot() + const legacy = readJson(legacyBackupFile(root)) + return { + roots: rootsFrom(root), + projectsRoot: root, + // public itch.io profile ("veröffentlicht" on the cards); Michi's setup knows his + itchProfile: devRoot() && !process.env.DASHBOARD_ROOT ? 'https://sn09.itch.io' : '', + backup: { + // several targets possible (NAS, USB disk, ...); each has its own backup state + targets: Array.isArray(legacy?.targets) ? legacy.targets : targetsFrom(legacy?.target ?? ''), + excludeDirs: legacy?.excludeDirs ?? DEFAULT_EXCLUDE_DIRS, + excludeFiles: legacy?.excludeFiles ?? DEFAULT_EXCLUDE_FILES, + }, + } +} + +let current = null + +function load() { + const d = defaults() + const saved = process.env.DASHBOARD_ROOT && !process.env.DASHBOARD_DATA ? null : readJson(FILE) + const backup = { ...d.backup, ...(saved?.backup ?? {}) } + if (!Array.isArray(saved?.backup?.targets) && typeof saved?.backup?.target === 'string') backup.targets = targetsFrom(saved.backup.target) + delete backup.target + // older settings had one "projectsRoot" + let roots = Array.isArray(saved?.roots) + ? saved.roots.filter((r) => r && typeof r.path === 'string' && r.path).map((r) => ({ id: String(r.id || newId()), name: String(r.name || rootName(r.path)), path: r.path })) + : typeof saved?.projectsRoot === 'string' ? rootsFrom(saved.projectsRoot) : d.roots + // an explicit DASHBOARD_ROOT always wins (tests) + if (process.env.DASHBOARD_ROOT) roots = [{ id: 'env', name: rootName(path.resolve(process.env.DASHBOARD_ROOT)), path: path.resolve(process.env.DASHBOARD_ROOT) }] + current = withActive({ + roots, + activeRoots: Array.isArray(saved?.activeRoots) ? saved.activeRoots : [saved?.activeRoot], + itchProfile: typeof saved?.itchProfile === 'string' ? saved.itchProfile : d.itchProfile, + backup, + }) + return current +} + +// Several folders can be shown at once: activeRoots = the selected ids (in list +// order, at least one). activeRoot = the first of them, projectsRoot = its path. +function withActive(s) { + const want = new Set((s.activeRoots ?? [s.activeRoot]).filter(Boolean)) + let active = s.roots.filter((r) => want.has(r.id)) + if (!active.length && s.roots[0]) active = [s.roots[0]] + const { activeRoot: _, ...rest } = s + return { ...rest, activeRoots: active.map((r) => r.id), activeRoot: active[0]?.id ?? '', projectsRoot: active[0]?.path ?? '' } +} + +// the selected folders [{ id, name, path }] +function activeRootList(s = get()) { + return s.roots.filter((r) => s.activeRoots.includes(r.id)) +} + +// What is written to settings.json (activeRoot/projectsRoot are derived, not stored). +function persist(next) { + const { projectsRoot, activeRoot, ...stored } = next + fs.mkdirSync(DATA_DIR, { recursive: true }) + fs.writeFileSync(FILE, JSON.stringify(stored, null, 2)) +} + +// Backups of several projects folders share the targets: the first folder goes +// straight into the target (as before), the others into a subfolder - their path +// below the first folder if they lie inside it, else their folder name. +function backupSubdir(rootPath, s = get()) { + const first = s.roots[0]?.path + if (!first || !rootPath || samePath(rootPath, first)) return '' + if (inside(rootPath, first)) return path.relative(path.resolve(first), path.resolve(rootPath)) + return rootName(path.resolve(rootPath)).replace(/[:\\/]/g, '') || 'Projekte' +} + +function get() { return current ?? load() } + +function isDir(p) { + try { return fs.statSync(p).isDirectory() } catch { return false } +} + +function configured() { + const s = get() + return !!s.projectsRoot && isDir(s.projectsRoot) +} + +const cleanList = (v, fallback) => + Array.isArray(v) ? [...new Set(v.map((x) => String(x).trim()).filter(Boolean))].slice(0, 50) : fallback + +// Validates and stores new settings. Throws with a German message on bad input. +function save(input) { + const s = get() + // path.resolve normalises ("D:\x\" → "D:\x") but keeps drive roots intact ("E:\") + const norm = (v) => (v.trim() ? path.resolve(v.trim().replace(/^"(.*)"$/, '$1')) : '') + let roots = s.roots + let activeRoots = Array.isArray(input.activeRoots) ? input.activeRoots.map(String) + : typeof input.activeRoot === 'string' ? [input.activeRoot] : s.activeRoots + let activeRoot = activeRoots[0] // only for the old single-folder form below + if (Array.isArray(input.roots)) { + const renamed = new Map() + roots = [] + for (const r of input.roots.slice(0, MAX_ROOTS)) { + const p = typeof r?.path === 'string' ? norm(r.path) : '' + if (!p) continue + if (!isDir(p)) throw new Error(`Projektordner existiert nicht: ${p}`) + if (roots.some((x) => samePath(x.path, p))) throw new Error(`Projektordner doppelt: ${p}`) + const old = s.roots.find((x) => x.id === r.id) + roots.push({ + id: old && samePath(old.path, p) ? old.id : newId(), + name: String(r.name ?? '').trim().slice(0, 40) || rootName(p), + path: p, + }) + // a selected folder stays selected even if its path (and so its id) changed + if (r.id) renamed.set(String(r.id), roots.at(-1).id) + } + if (!roots.length) throw new Error('Mindestens ein Projektordner ist nötig.') + activeRoots = activeRoots.map((id) => renamed.get(id)).filter(Boolean) + } else if (typeof input.projectsRoot === 'string') { + // old single-folder form: replaces the active folder + const p = norm(input.projectsRoot) + if (!p || !isDir(p)) throw new Error('Der Projektordner existiert nicht.') + const i = Math.max(0, roots.findIndex((r) => r.id === activeRoot)) + const existing = roots.find((r) => samePath(r.path, p)) + if (existing) activeRoots = [existing.id] + else { + roots = roots.slice() + roots[i] = { id: newId(), name: rootName(p), path: p } + activeRoots = [roots[i].id] + } + } + const sel = withActive({ roots, activeRoots }) + const projectsRoot = sel.projectsRoot + if (!projectsRoot || !isDir(projectsRoot)) throw new Error('Der Projektordner existiert nicht.') + let targets = s.backup.targets + if (Array.isArray(input.targets)) { + targets = [] + const seen = new Set() + for (const t of input.targets.slice(0, 10)) { + const p = typeof t?.path === 'string' ? norm(t.path) : '' + if (!p) continue + const a = p.toLowerCase() + if (seen.has(a)) throw new Error(`Backup-Ziel doppelt: ${p}`) + seen.add(a) + if (fs.existsSync(p) && !isDir(p)) throw new Error(`Backup-Ziel ist eine Datei, kein Ordner: ${p}`) + if (!isDir(p) && !isDir(path.dirname(p))) throw new Error(`Backup-Ziel nicht erreichbar (Laufwerk/NAS angeschlossen?): ${p}`) + const old = s.backup.targets.find((x) => x.id === t.id) + targets.push({ + // a changed path is a new target (its backup state starts fresh) + id: old && old.path.toLowerCase() === a ? old.id : newId(), + name: String(t.name ?? '').trim().slice(0, 40) || targetName(p), + path: p, + }) + } + } else if (typeof input.backupTarget === 'string') { + targets = targetsFrom(norm(input.backupTarget)) // old single-target form + } + // checked for every save, so a newly added projects folder can't hold a backup target either + for (const t of targets) { + const clash = roots.find((r) => samePath(t.path, r.path) || inside(t.path, r.path) || inside(r.path, t.path)) + if (clash) throw new Error(`Das Backup-Ziel darf nicht in einem Projektordner liegen (und keinen enthalten): ${t.path} ↔ ${clash.path}`) + } + let itchProfile = s.itchProfile ?? '' + if (typeof input.itchProfile === 'string') { + const v = input.itchProfile.trim().replace(/\/+$/, '') + // "sn09" or "sn09.itch.io" is enough + itchProfile = !v ? '' : /^https?:\/\//i.test(v) ? v : `https://${v.includes('.') ? v : `${v}.itch.io`}` + if (itchProfile && !/^https:\/\/[a-z0-9-]+\.itch\.io$/i.test(itchProfile)) throw new Error('itch.io-Profil: z. B. https://name.itch.io') + } + const next = withActive({ + roots, + activeRoots: sel.activeRoots, + itchProfile, + backup: { + targets, + excludeDirs: cleanList(input.excludeDirs, s.backup.excludeDirs), + excludeFiles: cleanList(input.excludeFiles, s.backup.excludeFiles), + }, + }) + persist(next) + // keep backup-projekte.bat in sync where it exists (it backs up the first folder to the first target) + const legacy = legacyBackupFile(roots[0].path) + if (legacy && fs.existsSync(legacy)) { + fs.writeFileSync(legacy, JSON.stringify({ source: roots[0].path, target: targets[0]?.path ?? '', targets, excludeDirs: next.backup.excludeDirs, excludeFiles: next.backup.excludeFiles }, null, 2) + '\n') + } + current = next + return current +} + +// Quick switch (dropdown next to the logo): which folders are shown (one id or a list). +function setActive(ids) { + const s = get() + const list = (Array.isArray(ids) ? ids : [ids]).map(String) + const sel = s.roots.filter((x) => list.includes(x.id)) + if (!sel.length) throw new Error('Projektordner nicht gefunden.') + const gone = sel.find((r) => !isDir(r.path)) + if (gone) throw new Error(`Projektordner nicht erreichbar: ${gone.path}`) + current = withActive({ ...s, activeRoots: sel.map((r) => r.id) }) + persist(current) + return current +} + +// Adds projects folders (dropdown "Ordner hinzufügen" / "Mehrere einlesen"); +// folders already in the list are skipped. activate: show (only) the new ones. +function addRoots(paths, activate = false) { + const s = get() + const fresh = (Array.isArray(paths) ? paths : []) + .filter((p) => typeof p === 'string' && p.trim()) + .filter((p, i, all) => !s.roots.some((r) => samePath(r.path, p)) && all.findIndex((q) => samePath(q, p)) === i) + if (!fresh.length) return { settings: s, added: [] } + const before = new Set(s.roots.map((r) => r.id)) + const next = save({ roots: [...s.roots, ...fresh.map((p) => ({ id: '', name: '', path: p }))] }) + const added = next.roots.filter((r) => !before.has(r.id)) + return { settings: activate && added[0] ? setActive(added.map((r) => r.id)) : next, added } +} + +// Direct subfolders of a folder (for "Mehrere einlesen"), with how many folders each holds. +function subfolders(dir) { + const p = typeof dir === 'string' && dir.trim() ? path.resolve(dir.trim().replace(/^"(.*)"$/, '$1')) : '' + if (!p || !isDir(p)) throw new Error('Ordner existiert nicht.') + const skip = new Set(['$recycle.bin', 'system volume information', 'recovery', 'config.msi', 'node_modules']) + const list = fs.readdirSync(p, { withFileTypes: true }) + .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !skip.has(e.name.toLowerCase())) + .map((e) => { + const full = path.join(p, e.name) + let count = 0 + try { count = fs.readdirSync(full, { withFileTypes: true }).filter((x) => x.isDirectory() && !x.name.startsWith('.')).length } catch {} + return { name: e.name, path: full, count } + }) + .sort((a, b) => a.name.localeCompare(b.name, 'de')) + return { path: p, folders: list.slice(0, 200) } +} + +module.exports = { get, load, save, setActive, addRoots, activeRootList, subfolders, backupSubdir, configured, targetName, DATA_DIR, APP_DIR, DEFAULT_EXCLUDE_DIRS } diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..8cf9e05 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,135 @@ +// Disk usage and cleanup. Sizes are slow to measure, so scans run in the +// background and land in \scan.json (per projects folder - several can +// be shown at once, see lib/settings.js). Which folders may be deleted is +// decided only by cleanup.ps1 (same safety rules as on the CLI): the one in +// \_Tools\Cleanup if it exists, else the copy shipped in tools\. +// A project is addressed by its projects folder (root) and folder name. +const fs = require('fs') +const path = require('path') +const { run, pool } = require('./proc') +const { DATA_DIR, APP_DIR } = require('./settings') + +const CACHE_FILE = path.join(DATA_DIR, 'scan.json') +const ALL_TIERS = 'Cache,Release,Output' + +let roots = [] // selected projects folders (paths) +let all = {} // root (lower case) -> { folder -> { at, sizeMB, candidates: [{Tier, MB, Skip, Path}], deletable: {Cache, Release, Output} } } +const state = { running: false, current: [], done: 0, total: 0, error: null } + +const rootKey = (r) => (r ?? '').toLowerCase() +const shipped = path.join(APP_DIR, 'tools', 'cleanup.ps1') +const own = (root) => (root ? path.join(root, '_Tools', 'Cleanup', 'cleanup.ps1') : '') + +function readAll(first) { + try { + const saved = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8')) + if (saved?.roots && typeof saved.roots === 'object') return saved.roots + // older formats: { root, projects } or the bare projects map of one folder + if (saved?.projects && typeof saved.root === 'string') return { [rootKey(saved.root)]: saved.projects } + if (saved && first) return { [rootKey(first)]: saved } + } catch {} + return {} +} + +let known = [] // all registered projects folders (their _Tools\Cleanup can stand in) + +// rootList: paths of the selected projects folders; registered: all of them +function init(rootList, registered = []) { + roots = (Array.isArray(rootList) ? rootList : [rootList]).filter(Boolean) + known = registered.filter(Boolean) + all = readAll(roots[0]) +} + +function save() { + fs.mkdirSync(DATA_DIR, { recursive: true }) + fs.writeFileSync(CACHE_FILE, JSON.stringify({ roots: all }, null, 1)) +} + +function busy() { return state.running } + +// cleanup.ps1 for a folder: its own, else one of another registered folder, else the shipped copy +function scriptFor(root) { + for (const s of [own(root), ...roots.map(own), ...known.map(own), shipped]) if (s && fs.existsSync(s)) return s + return null +} + +function available() { return !!scriptFor(roots[0]) } + +function psArgs(root, extra) { + return ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptFor(root), '-Root', root, ...extra, '-Json'] +} + +function parseJson(stdout) { + const text = stdout.trim() + const start = text.search(/[[{]/) + if (start < 0) throw new Error('cleanup.ps1 gave no JSON') + return JSON.parse(text.slice(start)) +} + +async function dirSizeMB(dir) { + // robocopy /L only lists; fast and copes with long node_modules paths + const r = await run('robocopy', [dir, 'C:\\__nul__', '/L', '/S', '/NJH', '/BYTES', '/FP', '/NC', '/NDL', '/NFL', '/XJ', '/R:0', '/W:0'], { timeout: 10 * 60 * 1000 }) + const line = r.stdout.split(/\r?\n/).find((l) => /^\s*Bytes\s*:/.test(l)) + const m = line && line.match(/:\s*(\d+)/) + return m ? Math.round(+m[1] / 1048576) : null +} + +async function scanProject(root, folder) { + const dir = path.join(root, folder) + const [sizeMB, cand] = await Promise.all([ + dirSizeMB(dir), + scriptFor(root) ? run('powershell.exe', psArgs(root, ['-Project', folder, '-Tier', ALL_TIERS]), { timeout: 10 * 60 * 1000 }) : null, + ]) + const candidates = cand ? parseJson(cand.stdout) : [] + const deletable = { Cache: 0, Release: 0, Output: 0 } + for (const c of candidates) if (!c.Skip) deletable[c.Tier] += c.MB + const d = (all[rootKey(root)] ??= {}) + d[folder] = { at: new Date().toISOString(), sizeMB, candidates, deletable } + save() + return d[folder] +} + +// Starts a background scan; returns immediately. items: [{ root, folder, key }] +function startScan(items) { + if (state.running) return false + Object.assign(state, { running: true, current: [], done: 0, total: items.length, error: null }) + pool(items, 3, async (it) => { + const label = it.key ?? it.folder + state.current.push(label) + try { await scanProject(it.root, it.folder) } catch (e) { state.error = `${label}: ${e.message}` } + state.current = state.current.filter((n) => n !== label) + state.done++ + }).finally(() => { state.running = false }) + return true +} + +// Deletes only the given paths (relative to the projects folder, as listed by +// the scan), then rescans the project. cleanup.ps1 checks every path again. +async function clean(root, folder, paths) { + const prefix = folder + path.sep + const only = paths.filter((p) => typeof p === 'string' && p.startsWith(prefix) && !p.includes('|')) + if (!only.length) throw new Error('nichts ausgewählt') + if (!scriptFor(root)) throw new Error('cleanup.ps1 nicht gefunden') + const r = await run('powershell.exe', psArgs(root, ['-Project', folder, '-Tier', ALL_TIERS, '-Only', only.join('|'), '-Apply']), { timeout: 30 * 60 * 1000 }) + const result = parseJson(r.stdout) + await scanProject(root, folder) + return result +} + +function get(root, folder) { return all[rootKey(root)]?.[folder] ?? null } + +// items: [{ root, folder }] +function totals(items) { + let sizeMB = 0, cacheMB = 0, allMB = 0, scanned = 0 + for (const it of items) { + const d = get(it.root, it.folder) + if (!d) continue + scanned++ + sizeMB += d.sizeMB ?? 0 + cacheMB += d.deletable.Cache + allMB += d.deletable.Cache + d.deletable.Release + d.deletable.Output + } + return { sizeMB, cacheMB, allMB, scanned } +} + +module.exports = { init, startScan, clean, get, totals, state, available, busy } diff --git a/lib/tech.js b/lib/tech.js new file mode 100644 index 0000000..85abdad --- /dev/null +++ b/lib/tech.js @@ -0,0 +1,320 @@ +// Detects what a project is made of (Unity, Node, .NET, ...) from marker files +// and builds the list of start actions. Actions are always built here on the +// server; the browser only sends back an action id. +const fs = require('fs') +const path = require('path') + +const SKIP = new Set([ + 'node_modules', '.git', 'dist', 'build', 'builds', 'out', 'bin', 'obj', 'target', 'venv', '.venv', 'env', + '__pycache__', '.gradle', '.idea', '.vscode', 'Library', 'Temp', 'Logs', 'output', '_archiv', '_Archiv', + 'sprite-generator', 'Spritegenerator', 'sprite-gen', 'design-gen', '.expo', '.claude', +]) +const NPM_SCRIPTS = ['dev', 'start', 'electron', 'android', 'web', 'build', 'preview', 'serve', 'tauri'] +const PY_MAIN = ['main.py', 'app.py', 'run.py', 'game.py', 'server.py', 'gui.py'] +const UNITY_EDITORS = 'C:\\Program Files\\Unity\\Hub\\Editor' +const UNITY_HUB = 'C:\\Program Files\\Unity Hub\\Unity Hub.exe' + +function ls(dir) { + try { return fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] } +} +function readJson(file) { + try { return JSON.parse(fs.readFileSync(file, 'utf-8')) } catch { return null } +} + +// Looks at the project root and its direct subfolders (e.g. "DesktopAnt\DesktopAnt"). +function detect(projectPath) { + const subdirs = ls(projectPath) + .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP.has(e.name)) + .map((e) => path.join(projectPath, e.name)) + const found = [] + for (const dir of [projectPath, ...subdirs]) { + const isRoot = dir === projectPath + const entries = ls(dir) + const names = new Set(entries.map((e) => e.name)) + const files = entries.filter((e) => e.isFile()).map((e) => e.name) + const rel = path.relative(projectPath, dir) + const unity = names.has('Assets') && names.has('ProjectSettings') + + if (unity) found.push({ type: 'unity', dir, rel }) + if (names.has('package.json')) { + const pkg = readJson(path.join(dir, 'package.json')) ?? {} + const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) } + const flavor = deps.electron ? 'electron' : deps.expo ? 'expo' : deps['@capacitor/core'] ? 'capacitor' : deps.vite ? 'vite' : deps.react ? 'react' : null + found.push({ + type: 'node', dir, rel, flavor, + scripts: Object.keys(pkg.scripts ?? {}), + scriptCmds: pkg.scripts ?? {}, + needsInstall: Object.keys(deps).length > 0 && !names.has('node_modules'), + }) + } + if (!unity) { + const sln = files.filter((f) => /\.sln$/i.test(f)) + const proj = files.filter((f) => /\.(cs|fs|vb)proj$/i.test(f)) + if (sln.length || proj.length) found.push({ type: 'dotnet', dir, rel, sln, proj }) + } + if (names.has('pubspec.yaml')) found.push({ type: 'flutter', dir, rel }) + if (['build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts'].some((n) => names.has(n))) { + found.push({ type: 'android', dir, rel, gradlew: names.has('gradlew.bat') }) + } + if (names.has('CMakeLists.txt')) found.push({ type: 'cmake', dir, rel }) + const ino = files.filter((f) => /\.ino$/i.test(f)) + if (ino.length) found.push({ type: 'arduino', dir, rel, ino }) + if (isRoot) { + const py = files.filter((f) => /\.py$/i.test(f)) + if (py.length || names.has('requirements.txt') || names.has('pyproject.toml')) { + const venv = path.join(dir, '.venv', 'Scripts', 'python.exe') + found.push({ type: 'python', dir, rel, py, venv: fs.existsSync(venv) ? venv : null }) + } + } + } + return found +} + +const TYPE_LABEL = { + unity: 'Unity', node: 'Node', dotnet: '.NET', flutter: 'Flutter', android: 'Android', + cmake: 'C++/CMake', arduino: 'Arduino', python: 'Python', web: 'Web', +} + +function summary(found) { + const labels = [] + for (const f of found) { + const l = f.type === 'node' && f.flavor ? f.flavor[0].toUpperCase() + f.flavor.slice(1) : TYPE_LABEL[f.type] + if (!labels.includes(l)) labels.push(l) + } + return { types: labels, needsInstall: found.some((f) => f.type === 'node' && f.needsInstall) } +} + +function unityEditor(dir) { + try { + const txt = fs.readFileSync(path.join(dir, 'ProjectSettings', 'ProjectVersion.txt'), 'utf-8') + const ver = txt.match(/m_EditorVersion:\s*(\S+)/)?.[1] + const exe = ver && path.join(UNITY_EDITORS, ver, 'Editor', 'Unity.exe') + return { ver, exe: exe && fs.existsSync(exe) ? exe : null } + } catch { return { ver: null, exe: null } } +} + +// ── startable programs & scripts ───────────────────────────────────────── +// Folders that never hold the project's own program (tests, drivers, caches, ...) +const EXE_SKIP_DIRS = /^(node_modules|\.git|\.gradle|\.gradle-local|gradle|Library|Temp|Logs|obj|\.venv.*|venv|env|__pycache__|tests?|Tests|symbols|CMakeFiles|_deps|drivers?|_archiv|output|sprite-?generator|spritegenerator|sprite-?gen|design-?gen|\.expo|\.idea|\.vscode|\.cache|\.claude|android|ios|packages|Packages)$/i +// Helper executables that are not "the app" +const EXE_SKIP_NAMES = /^(unins.*|.*setup.*|.*install.*|.*redist.*|.*crash.?handler.*|createdump|butler|adb|aapt2?|ffmpeg|ffprobe|7za?|python.*|pythonw|node|npm|remove|remover|elevate|squirrel|update|dotnet|apphost|notification_helper|chrome_.*|.*\.vshost)$/i +// Programs that exist next to the real app but are not what you want to start first +const EXE_SECONDARY = /(server|helper|updater|console|cli|worker|daemon|service)$/i +const SCRIPT_SKIP = /^(gradlew|gradle|gen|ctlstisc)\.(bat|cmd)$/i +// Where a copy of an exe came from - better sources win when the same exe exists several times +function exeRank(rel) { + const r = rel.toLowerCase() + if (/(^|\\)publish[^\\]*\\/.test(r)) return 6 + if (/(^|\\)release\\/.test(r) && !/\\bin\\/.test(r)) return 5 + if (/(^|\\)(dist|builds?|spiel|game)\\/.test(r)) return 4 + if (!r.includes('\\')) return 4 // next to the project + if (/\\bin\\release\\/.test(r) || /^bin\\release\\/.test(r)) return 3 + if (/\\bin\\debug\\/.test(r) || /^bin\\debug\\/.test(r)) return 1 + return 2 +} +const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '') + +function walkFiles(root, maxDepth, test) { + const out = [] + const queue = [{ dir: root, depth: 0 }] + let seen = 0 + while (queue.length) { + const { dir, depth } = queue.shift() + for (const e of ls(dir)) { + if (++seen > 20000) return out + if (e.isDirectory()) { + // "_name" subfolders hold vendored or archived stuff (_vbcable, _archiv, ...) + if (depth < maxDepth && !EXE_SKIP_DIRS.test(e.name) && !e.name.startsWith('_')) queue.push({ dir: path.join(dir, e.name), depth: depth + 1 }) + } else if (e.isFile() && test(e.name)) out.push(path.join(dir, e.name)) + } + } + return out +} + +function ago(ms) { + const d = Math.floor((Date.now() - ms) / 86400000) + return d <= 0 ? 'heute' : d === 1 ? 'gestern' : d < 30 ? `vor ${d} T.` : d < 365 ? `vor ${Math.floor(d / 30)} Mon.` : `vor ${Math.floor(d / 365)} J.` +} + +// The project's own programs: one entry per exe name (best copy), the one +// named like the project first, then newest. +function findPrograms(name, projectPath) { + const best = new Map() + for (const file of walkFiles(projectPath, 6, (n) => /\.exe$/i.test(n) && !EXE_SKIP_NAMES.test(n.replace(/\.exe$/i, '')))) { + const rel = path.relative(projectPath, file) + let mtime = 0 + try { mtime = fs.statSync(file).mtimeMs } catch {} + const key = path.basename(file).toLowerCase() + const cand = { file, rel, mtime, rank: exeRank(rel) } + const cur = best.get(key) + if (!cur || cand.rank > cur.rank || (cand.rank === cur.rank && cand.mtime > cur.mtime)) best.set(key, cand) + } + const pn = norm(name) + return [...best.values()] + .map((c) => { + const en = norm(path.basename(c.file, path.extname(c.file))) + return { ...c, match: nameMatches(pn, en) ? 1 : 0, secondary: EXE_SECONDARY.test(en) ? 1 : 0 } + }) + .sort((a, b) => (b.match - a.match) || (a.secondary - b.secondary) || (b.rank - a.rank) || (b.mtime - a.mtime)) + .slice(0, 12) +} + +// "TinyWold" (folder) should still match "TinyWorld.exe": contained, or a +// common start of at least 5 letters. +function nameMatches(projectNorm, exeNorm) { + if (!projectNorm || !exeNorm) return false + if (exeNorm.includes(projectNorm) || projectNorm.includes(exeNorm)) return true + let i = 0 + while (i < projectNorm.length && i < exeNorm.length && projectNorm[i] === exeNorm[i]) i++ + return i >= 5 +} + +// HTML pages that run by double-click: index.html up to 3 folders deep (game\index.html), +// any .html directly in a release folder (single-file builds) and a root page named like +// the project (Stammbaum\stammbaum.html). Pages that cannot run from file:// are left out: +// ES modules (Vite dev page and built dist - browsers block module scripts on file://) and +// absolute /paths. Those start via npm. +const HTML_SKIP_PARTS = /(^|\\)(public|src|docs?|archive|_?archiv|mockups?|templates?|backups?|old|alt|kopie|copy|bak|node_modules|coverage|test-results|playwright-report|cache|\.cache)(\\|$)/i +function findWebPages(name, projectPath) { + const out = [] + const pn = norm(name) + for (const file of walkFiles(projectPath, 3, (n) => /\.html?$/i.test(n))) { + const rel = path.relative(projectPath, file) + const dir = path.dirname(rel) + const base = path.basename(file, path.extname(file)) + const isIndex = /^index$/i.test(base) + const inRelease = /(^|\\)release$/i.test(dir) + const namedRoot = dir === '.' && nameMatches(pn, norm(base)) + if (!isIndex && !inRelease && !namedRoot) continue + if (HTML_SKIP_PARTS.test(dir)) continue + let head = '' + try { head = fs.readFileSync(file, 'utf-8').slice(0, 200000) } catch { continue } + if (/]+type=["']module["']/i.test(head) || /]+src=["']\/(?!\/)/i.test(head) || /\/@vite\//.test(head)) continue + let mtime = 0 + try { mtime = fs.statSync(file).mtimeMs } catch {} + const rank = inRelease ? 3 : /^(game|spiel|web|www|app|html)(\\|$)/i.test(dir) ? 2 : dir === '.' ? 1 : 0 + out.push({ file, rel, mtime, rank }) + } + // single-file release first, then game\index.html, then the root page + return out.sort((a, b) => (b.rank - a.rank) || (b.mtime - a.mtime)).slice(0, 6) +} + +// How a file is started: exe directly, html/lnk with the default app, bat/cmd in a console. +function fileAction(id, label, file, projectPath, detail) { + const rel = path.relative(projectPath, file) + const ext = path.extname(file).toLowerCase() + const base = { id, label, group: 'Programm', rel, file, detail } + if (ext === '.exe') return { ...base, kind: 'exe', exe: file, args: [], cwd: path.dirname(file) } + if (ext === '.bat' || ext === '.cmd') return { ...base, kind: 'console', cwd: path.dirname(file), command: `call "${path.basename(file)}"` } + return { ...base, kind: 'open' } +} + +// The program chosen in "Aktionen" (.dashboard.json "program", path inside the project) +function resolveProgram(projectPath, program) { + if (!program) return null + const file = path.resolve(projectPath, program) + if (!file.startsWith(projectPath + path.sep)) return null + return { file, exists: fs.existsSync(file) && fs.statSync(file).isFile() } +} + +// .bat/.cmd in the project root and one level below (e.g. Spiel\3D-Ansicht.bat) +function findScripts(projectPath) { + return walkFiles(projectPath, 1, (n) => /\.(bat|cmd)$/i.test(n) && !SCRIPT_SKIP.test(n)) + .map((file) => { + const base = path.basename(file) + const group = /^(build|publish|deploy|release|make|compile|pack)/i.test(base) ? 'Bauen' + : /(install|setup|einricht)/i.test(base) ? 'Einrichten' : 'Starten' + return { file, rel: path.relative(projectPath, file), base, group } + }) + .slice(0, 12) +} + +const where = (rel) => (rel ? ` (${rel})` : '') + +// Every action: { id, label, group, kind, cwd, command | exe+args | file } +// kind: console = visible cmd window, exe = start program, open = default app, vscode +function actions(name, projectPath, found, meta, tools) { + const list = [ + { id: 'vscode', label: 'In VS Code öffnen', group: 'Öffnen', kind: 'vscode', cwd: projectPath }, + { id: 'explorer', label: 'Ordner im Explorer', group: 'Öffnen', kind: 'open', file: projectPath }, + { id: 'console', label: 'Konsole im Projekt', group: 'Öffnen', kind: 'console', cwd: projectPath, command: 'git status 2>nul' }, + ] + if (meta.start) list.push({ id: 'custom', label: `Eigener Start: ${meta.start}`, group: 'Starten', kind: 'console', cwd: projectPath, command: meta.start }) + + // the program chosen for ▶ comes first; a missing file stays visible so it can be fixed + const chosen = resolveProgram(projectPath, meta.program) + if (chosen?.exists) { + list.push(fileAction('program', path.basename(chosen.file, path.extname(chosen.file)), chosen.file, projectPath, `${path.relative(projectPath, chosen.file)} · für ▶ festgelegt`)) + } + const chosenFile = chosen?.exists ? chosen.file.toLowerCase() : null + + for (const f of found) { + const r = f.rel + switch (f.type) { + case 'node': + if (f.needsInstall) list.push({ id: `npm-install:${r}`, label: `npm install${where(r)}`, group: 'Einrichten', kind: 'console', cwd: f.dir, command: 'npm install' }) + for (const s of NPM_SCRIPTS.filter((s) => f.scripts.includes(s))) { + // a Vite dev server alone opens nothing visible - let it open the browser; + // without node_modules the script would just fail, so install first + const vite = /^\s*vite(\s|$)(?!.*\bbuild\b)/.test(f.scriptCmds?.[s] ?? '') && !/--open/.test(f.scriptCmds?.[s] ?? '') + const cmd = `${f.needsInstall && s !== 'build' ? 'npm install && ' : ''}npm run ${s}${vite ? ' -- --open' : ''}` + list.push({ id: `npm:${r}:${s}`, label: `npm run ${s}${where(r)}${vite ? ' (Browser)' : ''}`, group: s === 'build' ? 'Bauen' : 'Starten', kind: 'console', cwd: f.dir, command: cmd }) + } + break + case 'dotnet': { + const target = f.sln[0] ?? f.proj[0] + list.push({ id: `dotnet-build:${r}:${target}`, label: `dotnet build ${target}`, group: 'Bauen', kind: 'console', cwd: f.dir, command: `dotnet build "${target}"` }) + for (const p of f.proj.slice(0, 4)) list.push({ id: `dotnet-run:${r}:${p}`, label: `dotnet run ${p}`, group: 'Starten', kind: 'console', cwd: f.dir, command: `dotnet run --project "${p}"` }) + break + } + case 'flutter': + list.push({ id: `flutter:${r}`, label: `flutter run${where(r)}`, group: 'Starten', kind: 'console', cwd: f.dir, command: 'flutter pub get && flutter run' }) + break + case 'android': + if (f.gradlew) list.push({ id: `gradle:${r}`, label: `Gradle assembleDebug${where(r)}`, group: 'Bauen', kind: 'console', cwd: f.dir, command: 'gradlew.bat assembleDebug' }) + break + case 'unity': { + const ed = unityEditor(f.dir) + if (ed.exe) list.push({ id: `unity:${r}`, label: `In Unity ${ed.ver} öffnen${where(r)}`, group: 'Starten', kind: 'exe', exe: ed.exe, args: ['-projectPath', f.dir] }) + else if (fs.existsSync(UNITY_HUB)) list.push({ id: `unity-hub:${r}`, label: `Unity Hub öffnen${ed.ver ? ` (braucht ${ed.ver})` : ''}`, group: 'Starten', kind: 'exe', exe: UNITY_HUB, args: [] }) + break + } + case 'python': { + const main = PY_MAIN.find((m) => f.py.includes(m)) ?? f.py.find((p) => p.toLowerCase() === `${name.toLowerCase()}.py`) ?? (f.py.length === 1 ? f.py[0] : null) + if (main) { + const py = f.venv ? `"${f.venv}"` : 'py -3.12' + list.push({ id: `py:${main}`, label: `Python: ${main}${f.venv ? ' (.venv)' : ''}`, group: 'Starten', kind: 'console', cwd: f.dir, command: `${py} "${main}"` }) + } + break + } + case 'arduino': + list.push({ id: `ino:${r}:${f.ino[0]}`, label: `Arduino: ${f.ino[0]}`, group: 'Starten', kind: 'open', file: path.join(f.dir, f.ino[0]) }) + break + } + } + for (const p of findPrograms(name, projectPath)) { + if (p.file.toLowerCase() === chosenFile) continue + list.push({ + id: `exe:${p.rel}`, label: path.basename(p.file, path.extname(p.file)), group: 'Programm', kind: 'exe', + exe: p.file, args: [], cwd: path.dirname(p.file), rel: p.rel, + detail: `${p.rel} · ${ago(p.mtime)}`, + }) + } + for (const w of findWebPages(name, projectPath)) { + if (w.file.toLowerCase() === chosenFile) continue + const label = /^index\.html?$/i.test(path.basename(w.file)) ? `Web: ${path.dirname(w.rel) === '.' ? name : path.dirname(w.rel)}` : `Web: ${path.basename(w.file)}` + list.push(fileAction(`html:${w.rel}`, label, w.file, projectPath, `${w.rel} · ${ago(w.mtime)} · im Browser`)) + } + for (const s of findScripts(projectPath)) { + list.push({ + id: `bat:${s.rel}`, label: s.base, group: s.group, kind: 'console', + cwd: path.dirname(s.file), command: `call "${s.base}"`, detail: s.rel, + }) + } + for (const g of tools.generators.filter((g) => g.kind === 'comfygen')) { + list.push({ id: `gen:${g.rel}`, label: `Generator-Konsole (${g.rel})`, group: 'Werkzeuge', kind: 'console', cwd: path.join(projectPath, g.rel), command: 'gen' }) + } + return list +} + +module.exports = { detect, summary, actions, resolveProgram, SKIP } diff --git a/lib/tools.js b/lib/tools.js new file mode 100644 index 0000000..4ba18d8 --- /dev/null +++ b/lib/tools.js @@ -0,0 +1,32 @@ +// Which projects use the shared generator in _Tools\ComfyGen (via gen.cmd) and +// which still carry their own copy of generator scripts. +const fs = require('fs') +const path = require('path') + +const GEN_DIR = /^(sprite-?generator|sprite-?gen|design-?gen|asset-?gen)$/i + +function ls(dir) { + try { return fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] } +} + +function toolInfo(projectPath) { + const generators = [] + const dirs = [projectPath, ...ls(projectPath).filter((e) => e.isDirectory() && !e.name.startsWith('.') && !/^(_archiv|node_modules)$/i.test(e.name)).map((e) => path.join(projectPath, e.name))] + for (const dir of dirs) { + for (const e of ls(dir)) { + if (!e.isDirectory() || !GEN_DIR.test(e.name)) continue + const gdir = path.join(dir, e.name) + const files = ls(gdir).filter((f) => f.isFile()).map((f) => f.name) + const shared = files.includes('gen.cmd') + generators.push({ + rel: path.relative(projectPath, gdir), + kind: shared ? 'comfygen' : 'copy', + scripts: files.filter((f) => f.endsWith('.py')), + hasOutput: fs.existsSync(path.join(gdir, 'output')), + }) + } + } + return { generators } +} + +module.exports = { toolInfo } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..7df7371 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,835 @@ +{ + "name": "project-dashboard", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "project-dashboard", + "version": "1.0.0", + "dependencies": { + "express": "^4.19.2", + "lucide-static": "1.58.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.6", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz", + "integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.15.1", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/lucide-static": { + "version": "1.58.0", + "resolved": "https://registry.npmjs.org/lucide-static/-/lucide-static-1.58.0.tgz", + "integrity": "sha512-VFE2ZEq3yEwjBH0El9CA9lHgDWKKXPKgKxFzX+/JN1FPa4maQbtl/pT4B62aJkUEpODT5octDsyGy7tPVE2svQ==", + "license": "ISC" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..78c3997 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "project-dashboard", + "version": "1.0.0", + "private": true, + "description": "Local Kanban dashboard for everything under D:\\Oculusquest\\Projekt", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.19.2", + "lucide-static": "1.58.0" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..4a2b955 --- /dev/null +++ b/public/app.js @@ -0,0 +1,1712 @@ +/* Project dashboard UI: board (kanban), gallery and list views, a side panel + to edit a project, see its git/storage/tool info and start actions. + Icons come from the Lucide sprite served at /icons.svg. */ + +const STATUS = [ + { key: 'idea', label: 'Idee', icon: 'lightbulb', color: '#94a3b8' }, + { key: 'active', label: 'Aktiv', icon: 'rocket', color: '#22c55e' }, + { key: 'paused', label: 'Pausiert', icon: 'circle-pause', color: '#f59e0b' }, + { key: 'done', label: 'Fertig', icon: 'circle-check', color: '#3b82f6' }, + { key: 'archived', label: 'Archiviert', icon: 'archive', color: '#8b5cf6' }, +] +const STATUS_BY = Object.fromEntries(STATUS.map((s) => [s.key, s])) +const PRIO_ORDER = { high: 0, medium: 1, low: 2 } +const PRIO_LABEL = { high: 'Hoch', medium: 'Mittel', low: 'Niedrig' } +const TECH_ICON = { + Unity: 'box', Node: 'hexagon', Electron: 'atom', Expo: 'smartphone', Capacitor: 'smartphone', Vite: 'zap', + React: 'atom', '.NET': 'code-xml', Flutter: 'feather', Android: 'smartphone', 'C++/CMake': 'cpu', + Python: 'square-terminal', Web: 'globe', Arduino: 'circuit-board', +} +const GIT_ICON = { green: 'cloud-check', yellow: 'cloud-upload', red: 'cloud-off' } +const TIER = { + Cache: { label: 'Cache', hint: 'immer neu erzeugbar', cls: 'ok', icon: 'recycle' }, + Release: { label: 'Fertiger Build', hint: 'Version – bewusst löschen', cls: 'warn', icon: 'package' }, + Output: { label: 'Rohbilder', hint: 'Generator-Output', cls: 'warn', icon: 'images' }, +} +const ACTION_ICON = { + 'Einrichten': 'download', 'Starten': 'play', 'Bauen': 'hammer', 'Werkzeuge': 'wand-sparkles', 'Öffnen': 'folder-open', +} + +let projects = [] +let totals = null +let scanState = null +let cleanupAvailable = false +let editing = null +let editingTasks = [] +let searchTerm = '' +let quickFilter = 'all' +let activeView = 'board' +let scanTimer = null + +/* ── helpers ──────────────────────────────────────────────────────────── */ + +const ic = (name, cls = '') => `` +// ?r= keeps the browser cache apart when two projects folders have a project of the same name +const thumbUrl = (name) => `/api/projects/${encodeURIComponent(name)}/thumb?r=${encodeURIComponent(activeRoots.join(','))}` +const api = (name, what) => `/api/projects/${encodeURIComponent(name)}/${what}` + +function escapeHtml(s) { + return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])) +} + +function timeAgo(iso) { + if (!iso) return '' + const days = Math.floor((Date.now() - new Date(iso)) / 86400000) + if (days <= 0) return 'heute' + if (days === 1) return 'gestern' + if (days < 30) return `vor ${days} T.` + if (days < 365) return `vor ${Math.floor(days / 30)} Mon.` + return `vor ${Math.floor(days / 365)} J.` +} + +function fmtMB(mb) { + if (mb == null) return '–' + if (mb >= 1024) return `${(mb / 1024).toFixed(1).replace('.', ',')} GB` + return `${Math.round(mb)} MB` +} + +function nameColor(name) { + let hash = 0 + for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0 + const h = Math.abs(hash) % 360 + return `linear-gradient(135deg, hsl(${h} 62% 58%), hsl(${(h + 40) % 360} 62% 48%))` +} + +function initialsOf(name) { + const parts = name.split(/[\s_\-.]+/).filter(Boolean) + if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase() + return name.slice(0, 2).toUpperCase() +} + +// Project icon with letter fallback: the image sits on top of the initials +// and removes itself when the project has no picture. +function avatar(p, cls = '') { + return `
${escapeHtml(initialsOf(p.name))}
` +} + +const deletableMB = (p) => p.storage ? p.storage.deletable.Cache + p.storage.deletable.Release + p.storage.deletable.Output : 0 +// last change = newest file in the project (server: lib/activity.js), else last commit / folder date +const lastActivity = (p) => p.lastChange?.at ?? p.lastCommit?.date ?? p.mtime + +function fmtDate(iso, withYear = true) { + if (!iso) return '–' + return new Date(iso).toLocaleDateString('de-DE', withYear ? { day: '2-digit', month: '2-digit', year: '2-digit' } : { day: '2-digit', month: '2-digit' }) +} +function changeTitle(p) { + const at = lastActivity(p) + const when = new Date(at).toLocaleString('de-DE', { dateStyle: 'full', timeStyle: 'short' }) + if (p.lastChange) return `Letzte Änderung: ${when}\n${p.lastChange.file}${p.lastChange.partial ? '\n(großes Projekt – nur teilweise durchsucht)' : ''}` + return p.lastChange === undefined ? `Wird ermittelt … (bisher: ${when})` : `Letzte Änderung: ${when}` +} +function sizeTitle(p) { + if (p.storage?.sizeMB == null) return 'Ordnergröße: noch nicht gescannt („Alle scannen“ oben)' + return `Ordnergröße: ${fmtMB(p.storage.sizeMB)} (gescannt ${timeAgo(p.storage.at)})${deletableMB(p) >= 1 ? ` · davon ${fmtMB(deletableMB(p))} aufräumbar` : ''}` +} +function factsHtml(p) { + return `
+ ${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'} + ${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))} +
` +} + +function gitHtml(git, short = false) { + const label = short ? ({ green: 'Gesichert', yellow: 'Ungesichert', red: 'Kein Remote' })[git.level] : git.label + return `${ic(GIT_ICON[git.level], 'sm')}${escapeHtml(label)}` +} + +// Backup state of one project (p.lastBackup from the server: own or full backup, newer one) +const BACKUP_FRESH_DAYS = 7 +function cloudInfo(p) { + const l = p.lastBackup + if (!l) return { level: 'red', short: 'nie', label: 'Backup: noch nie gesichert' } + const days = (Date.now() - new Date(l.at)) / 86400000 + const when = new Date(l.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' }) + const level = l.ok === false ? 'red' : days > BACKUP_FRESH_DAYS ? 'yellow' : 'green' + const extra = l.ok === false ? ' – unvollständig' : days > BACKUP_FRESH_DAYS ? ` – älter als ${BACKUP_FRESH_DAYS} Tage` : '' + return { level, short: timeAgo(l.at), label: `Backup: gesichert ${when} (${l.how})${extra}` } +} +function cloudBadge(p, cls = 'tbadge') { + const c = cloudInfo(p) + return `${ic('hard-drive')}` +} +function cloudChip(p) { + const c = cloudInfo(p) + return `${ic('hard-drive', 'sm')}${escapeHtml(c.short)}` +} + +// itch.io: p.published = { url, title, source: 'auto' | 'manual' } (server, lib/itch.js) +function pubTitle(p) { + const x = p.published + return x ? `Auf itch.io veröffentlicht${x.title ? `: ${x.title}` : ''} (${x.source === 'manual' ? 'manuell eingetragen' : 'automatisch erkannt'}) – Klick öffnet die Seite` : '' +} +function pubChip(p, short = false) { + if (!p.published) return '' + return `${ic('rocket', 'sm')}${short ? '' : 'itch.io'}` +} +function pubBadge(p) { + if (!p.published) return '' + return `${ic('rocket')}` +} + +function statusHtml(key) { + const s = STATUS_BY[key] ?? STATUS[0] + return `${ic(s.icon, 'sm')}${s.label}` +} + +function prioHtml(prio) { + const icon = prio === 'high' ? 'flame' : prio === 'low' ? 'chevron-down' : 'equal' + return `${ic(icon, 'sm')}${PRIO_LABEL[prio]}` +} + +// Which projects folder a project is from - only shown when several are on screen. +function rootTag(p, short = false) { + if (!multiRoot() || !p.rootName) return '' + const path = roots.find((r) => r.id === p.root)?.path ?? '' + return `${ic('folder', 'sm')}${short ? '' : ' '}${escapeHtml(p.rootName)}` +} + +function techChips(types) { + return (types ?? []).map((t) => `${ic(TECH_ICON[t] ?? 'code', 'sm')}${escapeHtml(t)}`).join('') +} + +function warnChips(p) { + const b = [] + if (deletableMB(p) >= 100) b.push(`${ic('brush-cleaning', 'sm')}${fmtMB(deletableMB(p))}`) + if (p.tech?.needsInstall) b.push(`${ic('download', 'sm')}npm install`) + if (p.tools?.generators?.some((g) => g.kind === 'copy')) b.push(`${ic('copy', 'sm')}Generator-Kopie`) + else if (p.tools?.generators?.length) b.push(`${ic('wand-sparkles', 'sm')}ComfyGen`) + if (!p.hasIcon) b.push(`${ic('image-off', 'sm')}kein Icon`) + return b.join('') +} + +/* ── data ─────────────────────────────────────────────────────────────── */ + +let rootDir = '' // first shown projects folder +let rootPaths = [] // all shown projects folders +let roots = [] // registered projects folders [{ id, name, path }] +let activeRoots = [] // ids of the shown ones (several possible) +const multiRoot = () => activeRoots.length > 1 + +async function load() { + const res = await fetch(`/api/projects?target=${encodeURIComponent(curTargetId())}`) + const data = await res.json() + projects = data.projects + totals = data.totals + scanState = data.scan + cleanupAvailable = data.cleanupAvailable + rootDir = data.root ?? '' + rootPaths = data.rootPaths ?? (rootDir ? [rootDir] : []) + roots = data.roots ?? [] + activeRoots = data.activeRoots ?? (data.activeRoot ? [data.activeRoot] : []) + renderRootPicker() + if (editing) editing = projects.find((p) => p.name === editing.name) ?? editing + render() + if (scanState?.running) pollScan() + // last-change dates are still being collected in the background → refresh once more + clearTimeout(load.again) + if (data.activityPending > 0) load.again = setTimeout(load, 2500) + if (data.setupNeeded) openSettings(true) // first start: choose the projects folder +} + +/* ── new project / clone ──────────────────────────────────────────────── */ + +const newDlg = document.getElementById('newDlg') + +function openNewProject(from = '') { + closeEditor() + const sel = document.getElementById('nFrom') + sel.innerHTML = `` + + [...projects].sort((a, b) => a.name.localeCompare(b.name, 'de')).map((p) => ``).join('') + sel.value = from + document.getElementById('nRoot').innerHTML = roots.map((r) => ``).join('') + // default: the folder of the template, else the first shown one + document.getElementById('nRoot').value = projects.find((p) => p.name === from)?.root ?? activeRoots[0] ?? '' + document.getElementById('nExcl').textContent = (settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.venv']).join(', ') + document.getElementById('nName').value = from ? `${from} - Kopie` : '' + document.getElementById('nError').style.display = 'none' + syncNewDlg() + newDlg.showModal() + document.getElementById('nName').select() +} + +function syncNewDlg() { + const clone = !!document.getElementById('nFrom').value + document.getElementById('nCloneOpts').hidden = !clone + document.getElementById('nEmptyHint').hidden = clone + document.getElementById('newTitle').textContent = clone ? 'Projekt klonen' : 'Neues Projekt' + document.querySelector('#nOk span').textContent = clone ? 'Klonen' : 'Anlegen' +} + +document.getElementById('nFrom').addEventListener('change', () => { + const from = document.getElementById('nFrom').value + const name = document.getElementById('nName') + // keep a typed name, replace only the suggested one + if (!name.value.trim() || / - Kopie$/.test(name.value)) name.value = from ? `${from} - Kopie` : '' + syncNewDlg() +}) +document.getElementById('nCancel').onclick = () => newDlg.close() +document.getElementById('btnNew').onclick = () => openNewProject('') +document.getElementById('btnClone').onclick = () => { if (editing) openNewProject(editing.name) } +document.getElementById('newForm').addEventListener('submit', async (e) => { + e.preventDefault() + const ok = document.getElementById('nOk') + const err = document.getElementById('nError') + const from = document.getElementById('nFrom').value + const root = document.getElementById('nRoot').value + err.style.display = 'none' + ok.disabled = true + const label = ok.querySelector('span').textContent + ok.querySelector('span').textContent = from ? 'Wird kopiert…' : 'Wird angelegt…' + try { + const r = await postJson('/api/projects/new', { + name: document.getElementById('nName').value, root, from, + withGit: document.getElementById('nGit').checked, skipBuild: document.getElementById('nSkipBuild').checked, + }) + newDlg.close() + toast(`${r.cloned ? 'Klon' : 'Projekt'} „${r.name}“ angelegt`, 'folder-plus') + if (r.shown) { + await load() + const p = projects.find((x) => x.name === r.key) + if (p) openEditor(p) + } + } catch (ex) { + err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(ex.message)}
` + err.style.display = '' + } finally { + ok.disabled = false + ok.querySelector('span').textContent = label + } +}) + +/* ── projects folder quick switch (dropdown next to the logo) ─────────── */ + +const rootMenu = document.getElementById('rootMenu') +const rootBtn = document.getElementById('rootBtn') + +// Each row: [☑ box = add/remove from the view] [name = show only this folder] +function renderRootPicker() { + const cur = roots.filter((r) => activeRoots.includes(r.id)) + document.getElementById('rootName').textContent = + !cur.length ? 'Projekte' : cur.length === 1 ? cur[0].name : cur.length === roots.length && cur.length > 2 ? `Alle Ordner (${cur.length})` : cur.map((r) => r.name).join(' + ') + rootBtn.title = cur.length ? `Projektordner – angezeigt:\n${cur.map((r) => r.path).join('\n')}` : 'Projektordner wählen' + rootMenu.setAttribute('aria-multiselectable', 'true') + rootMenu.innerHTML = roots.map((r) => { + const on = activeRoots.includes(r.id) + return `
+ +
` + }).join('') + + (roots.length > 1 ? `` : '') + + `${roots.length ? '
' : ''}` + + (hasPicker ? `` : '') + + ` + ` +} + +// Adds folders via the server and (optionally) switches to the first new one. +async function addRoots(paths, activate) { + const r = await postJson('/api/roots/add', { paths, activate }) + settingsCache = r + if (!r.added.length) { toast('Schon in der Liste', 'info'); return r } + if (activate) { closeEditor(); searchTerm = ''; document.getElementById('search').value = '' } + await load() + if (activate) await loadBackup() + toast(r.added.length === 1 ? `Projektordner „${r.added[0].name}“ hinzugefügt` : `${r.added.length} Projektordner hinzugefügt`, 'folder-plus') + return r +} + +// "Ordner hinzufügen…" (desktop app): folder dialog → add → switch to it +async function addRootByPicker() { + const chosen = await pickFolder('Ordner mit Projekten wählen', rootDir) + if (!chosen) return + try { await addRoots([chosen], true) } catch (e) { toast(e.message, 'triangle-alert') } +} + +// "Mehrere Ordner einlesen…": dialog with the subfolder checklist +const rootDlg = document.getElementById('rootDlg') +function openRootImport() { + document.getElementById('rdBody').innerHTML = '' + document.getElementById('rdError').style.display = 'none' + rootDlg.showModal() + document.getElementById('rdPath').focus() +} +function listRootImport() { + document.getElementById('rdError').style.display = 'none' + return importList({ + dir: document.getElementById('rdPath').value, + body: document.getElementById('rdBody'), + have: roots.map((r) => r.path.toLowerCase().replace(/[\\/]+$/, '')), + onAdd: async (picked) => { + try { + await addRoots(picked, document.getElementById('rdActivate').checked) + rootDlg.close() + } catch (e) { + const err = document.getElementById('rdError') + err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
` + err.style.display = '' + throw e + } + }, + }) +} +document.getElementById('rdList').onclick = listRootImport +document.getElementById('rdPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listRootImport() } }) +document.getElementById('rdPick').onclick = async () => { + const input = document.getElementById('rdPath') + const chosen = await pickFolder('Übergeordneten Ordner wählen', input.value) + if (chosen) { input.value = chosen; listRootImport() } +} +document.getElementById('rdClose').onclick = () => rootDlg.close() + +function toggleRootMenu(open = rootMenu.hidden) { + rootMenu.hidden = !open + rootBtn.setAttribute('aria-expanded', String(open)) + if (open) (rootMenu.querySelector('[aria-selected="true"]') ?? rootMenu.querySelector('button'))?.focus() +} + +// Shows the given folders (ids, in list order). keepOpen: the menu stays open (ticking boxes). +async function showRoots(ids, keepOpen = false) { + if (!keepOpen) toggleRootMenu(false) + ids = roots.map((r) => r.id).filter((id) => ids.includes(id)) + if (!ids.length || ids.join('|') === activeRoots.join('|')) return + const prev = activeRoots + activeRoots = ids // tick right away; the projects follow when loaded + renderRootPicker() + try { + await postJson('/api/roots/active', { ids }) + closeEditor() + searchTerm = '' + document.getElementById('search').value = '' + await load() + await loadBackup() + if (!keepOpen) toast(`Projektordner: ${roots.filter((r) => ids.includes(r.id)).map((r) => r.name).join(' + ')}`, 'folder-open') + } catch (e) { + activeRoots = prev + renderRootPicker() + toast(e.message, 'triangle-alert') + } +} + +rootBtn.onclick = (e) => { e.stopPropagation(); toggleRootMenu() } +rootMenu.addEventListener('click', (e) => { + e.stopPropagation() + const b = e.target.closest('button') + if (!b) return + if (b.hasAttribute('data-root-manage')) { toggleRootMenu(false); openSettings(false); return } + if (b.hasAttribute('data-root-add')) { toggleRootMenu(false); addRootByPicker(); return } + if (b.hasAttribute('data-root-import')) { toggleRootMenu(false); openRootImport(); return } + if (b.hasAttribute('data-root-all')) { showRoots(roots.map((r) => r.id)); return } + const t = b.dataset.rootToggle + if (t) { + const next = activeRoots.includes(t) ? activeRoots.filter((x) => x !== t) : [...activeRoots, t] + if (!next.length) return toast('Mindestens ein Ordner bleibt angezeigt', 'info') + showRoots(next, true) + return + } + showRoots([b.dataset.root]) +}) +rootMenu.addEventListener('keydown', (e) => { + const items = [...rootMenu.querySelectorAll('button')] + const i = items.indexOf(document.activeElement) + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus() } + if (e.key === 'Escape') { e.stopPropagation(); toggleRootMenu(false); rootBtn.focus() } +}) +document.addEventListener('click', () => { if (!rootMenu.hidden) toggleRootMenu(false) }) + +/* ── settings (projects folder, backup target) ────────────────────────── */ + +let settingsCache = null +let settingsSetup = false + +// In the desktop app (WebView2) the exe shows a real folder dialog; in a +// normal browser the user types the path. +const hasPicker = !!window.chrome?.webview +const pickWaiters = new Map() +if (hasPicker) { + window.chrome.webview.addEventListener('message', (e) => { + const m = e.data + if ((m?.type === 'folderPicked' || m?.type === 'filePicked') && pickWaiters.has(m.id)) { pickWaiters.get(m.id)(m.path ?? ''); pickWaiters.delete(m.id) } + }) +} else document.body.classList.add('no-picker') + +function pickDialog(type, title, initial) { + return new Promise((resolve) => { + const id = Math.random().toString(36).slice(2) + pickWaiters.set(id, resolve) + window.chrome.webview.postMessage({ type, id, title, initial }) + }) +} +const pickFolder = (title, initial) => pickDialog('pickFolder', title, initial) +const pickFile = (title, initial) => pickDialog('pickFile', title, initial) + +async function openSettings(setup) { + settingsSetup = !!setup + closeEditor(); closeBackup() + try { settingsCache = await (await fetch('/api/settings')).json() } catch {} + const s = settingsCache ?? { roots: [], backup: { targets: [], excludeDirs: [] } } + document.getElementById('fRoots').innerHTML = (s.roots ?? []).map((r) => rootRow(r, (s.activeRoots ?? [s.activeRoot]).includes(r.id))).join('') || rootRow() + document.getElementById('fImport').hidden = true + document.getElementById('fImportBody').innerHTML = '' + document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('') || targetRow() + document.getElementById('fExDirs').value = (s.backup?.excludeDirs ?? []).join(', ') + document.getElementById('fItchProfile').value = s.itchProfile ?? '' + loadItchStatus() + document.getElementById('spData').innerHTML = s.dataDir ? `${ic('database', 'sm')} Einstellungen gespeichert in ${escapeHtml(s.dataDir)}` : '' + document.getElementById('spWelcome').style.display = setup ? '' : 'none' + document.getElementById('spTitle').textContent = setup ? 'Einrichten' : 'Einstellungen' + document.getElementById('spError').style.display = 'none' + const panel = document.getElementById('spanel') + panel.classList.toggle('setup', settingsSetup) + panel.classList.add('open') + panel.setAttribute('aria-hidden', 'false') + document.getElementById('overlay').classList.add('open') +} + +// "12 Spiele gefunden · ohne Projekt: X, Y" under the itch.io profile field +async function loadItchStatus(refresh = false) { + const el = document.getElementById('spItch') + el.innerHTML = `${ic('loader', 'sm')} itch.io wird gelesen…` + try { + const r = refresh ? await postJson('/api/itch/refresh', {}) : await (await fetch('/api/itch')).json() + if (!r.profile) { el.innerHTML = 'Leer = keine itch.io-Anzeige.'; return } + const un = r.unmatched ?? [] + el.innerHTML = r.error + ? `${ic('triangle-alert', 'sm')} ${escapeHtml(r.error)}` + : `${ic('rocket', 'sm')} ${r.games.length} Spiele gefunden.` + + (un.length ? ` Ohne Projekt: ${un.map((g) => `${escapeHtml(g.title)}`).join(', ')} – im Projekt unter „Bearbeiten“ den Link eintragen.` : ' Alle einem Projekt zugeordnet.') + } catch (e) { el.textContent = e.message } +} +document.getElementById('btnItchRefresh').onclick = async () => { await loadItchStatus(true); load() } + +function closeSettings() { + if (settingsSetup) return // the projects folder is required + const panel = document.getElementById('spanel') + if (!panel.classList.contains('open')) return + panel.classList.remove('open') + panel.setAttribute('aria-hidden', 'true') + if (!editing && !document.getElementById('bpanel').classList.contains('open')) document.getElementById('overlay').classList.remove('open') +} + +async function saveSettings() { + const err = document.getElementById('spError') + err.style.display = 'none' + const body = { + roots: [...document.querySelectorAll('#fRoots .rrow')] + .map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value })) + .filter((r) => r.path.trim()), + activeRoots: settingsCache?.activeRoots ?? [], + targets: [...document.querySelectorAll('#fTargets .trow')] + .map((r) => ({ id: r.dataset.id, name: r.querySelector('.tname').value, path: r.querySelector('.tpath').value })) + .filter((t) => t.path.trim()), + excludeDirs: document.getElementById('fExDirs').value.split(',').map((x) => x.trim()).filter(Boolean), + itchProfile: document.getElementById('fItchProfile').value, + } + try { + settingsCache = await postJson('/api/settings', body) + settingsSetup = false + closeSettings() + toast('Einstellungen gespeichert', 'save') + await loadBackup() + await load() + } catch (e) { + err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
` + err.style.display = '' + } +} + +// "Durchsuchen…": data-for = input id, or (in a target/folder row) the row's path input +document.getElementById('spanel').addEventListener('click', async (e) => { + const b = e.target.closest('.pickbtn') + if (!b || !hasPicker) return + const row = b.closest('.trow, .rrow') + const input = row ? row.querySelector('.tpath') : document.getElementById(b.dataset.for) + const chosen = await pickFolder(b.dataset.title, input.value) + if (!chosen) return + input.value = chosen + const name = row?.querySelector('.tname') + if (name && !name.value) name.value = row.classList.contains('rrow') ? folderName(chosen) : shortTargetName(chosen) + if (b.dataset.for === 'fImportPath') listImport() +}) + +// projects folder rows: [name] [path] [Durchsuchen…] [↑] [x]; the active one is marked +const folderName = (p) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || p +function rootRow(r = { id: '', name: '', path: '' }, active = false) { + return `
+ + + + + +
` +} +const rowRootPaths = () => [...document.querySelectorAll('#fRoots .rrow .tpath')].map((i) => i.value.trim().toLowerCase().replace(/[\\/]+$/, '')).filter(Boolean) +function addRootRow(r) { + const box = document.getElementById('fRoots') + // replace a single empty row (first start) instead of adding below it + const empty = [...box.querySelectorAll('.rrow')].find((x) => !x.querySelector('.tpath').value.trim() && !x.querySelector('.tname').value.trim()) + if (empty && r) empty.remove() + box.insertAdjacentHTML('beforeend', rootRow(r)) + return box.lastElementChild +} +document.getElementById('fAddRoot').onclick = () => addRootRow().querySelector('.tpath').focus() +document.getElementById('fRoots').addEventListener('click', (e) => { + const row = e.target.closest('.rrow') + if (e.target.closest('[data-rrm]')) row.remove() + else if (e.target.closest('[data-rup]') && row.previousElementSibling) row.parentNode.insertBefore(row, row.previousElementSibling) +}) + +// "Mehrere einlesen…": list the subfolders of a folder, tick the ones to add +document.getElementById('fImportOpen').onclick = () => { + const box = document.getElementById('fImport') + box.hidden = !box.hidden + if (!box.hidden) document.getElementById('fImportPath').focus() +} +document.getElementById('fImportList').onclick = () => listImport() +document.getElementById('fImportPath').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); listImport() } }) +function listImport() { + return importList({ + dir: document.getElementById('fImportPath').value, + body: document.getElementById('fImportBody'), + have: rowRootPaths(), + onAdd: (picked) => { + for (const p of picked) addRootRow({ id: '', name: folderName(p), path: p }) + document.getElementById('fImport').hidden = true + toast(`${picked.length} Projektordner hinzugefügt – Speichern nicht vergessen`, 'folder-plus') + }, + }) +} + +// Lists the subfolders of `dir` in `body` as checkboxes (plus the folder itself); +// folders in `have` (lower-case paths) are shown as already added. onAdd(paths) gets the ticked ones. +async function importList({ dir, body, have, onAdd }) { + dir = (dir ?? '').trim() + if (!dir) return + body.innerHTML = `
${ic('loader', 'sm')} wird gelesen…
` + try { + const res = await fetch(`/api/subfolders?path=${encodeURIComponent(dir)}`) + const r = await res.json() + if (!res.ok) throw new Error(r.error ?? res.statusText) + const haveSet = new Set(have) + const known = (p) => haveSet.has(p.toLowerCase().replace(/[\\/]+$/, '')) + const item = (f, label, extra, self = false) => `` + body.innerHTML = `
+ ${item({ path: r.path }, `Diesen Ordner selbst (${escapeHtml(folderName(r.path))})`, `${r.folders.length} Projekte`, true)} + ${r.folders.map((f) => item(f, escapeHtml(f.name), `${f.count} Unterordner`)).join('') || '
Keine Unterordner.
'} +
+
+ + +
` + body.querySelector('[data-imp-all]').onclick = () => { + const boxes = [...body.querySelectorAll('input:not(:disabled):not([data-self])')] + const on = !boxes.every((c) => c.checked) + for (const c of boxes) c.checked = on + } + body.querySelector('[data-imp-add]').onclick = async (e) => { + const picked = [...body.querySelectorAll('input:checked:not(:disabled)')].map((c) => c.dataset.path) + if (!picked.length) return toast('Nichts ausgewählt', 'info') + const btn = e.currentTarget + btn.disabled = true + try { await onAdd(picked); body.innerHTML = '' } finally { btn.disabled = false } + } + } catch (e) { + body.innerHTML = `
${ic('triangle-alert')}
${escapeHtml(e.message)}
` + } +} + +// backup target rows in the settings: [name] [path] [Durchsuchen…] [x] +const shortTargetName = (p) => p.match(/^\\\\([^\\]+)/)?.[1] ?? (p.match(/^([A-Za-z]:)/) ? `${p.slice(0, 2)} ${p.split('\\').filter(Boolean).pop() ?? ''}`.trim() : p.split('\\').pop()) +function targetRow(t = { id: '', name: '', path: '' }) { + return `
+ + + + +
` +} +document.getElementById('fAddTarget').onclick = () => { + document.getElementById('fTargets').insertAdjacentHTML('beforeend', targetRow()) + document.querySelector('#fTargets .trow:last-child .tpath').focus() +} +document.getElementById('fTargets').addEventListener('click', (e) => { if (e.target.closest('[data-trm]')) e.target.closest('.trow').remove() }) +document.getElementById('btnSettings').onclick = () => openSettings(false) +document.getElementById('btnCloseSettings').onclick = closeSettings +document.getElementById('spCancel').onclick = closeSettings +document.getElementById('spSave').onclick = saveSettings + +async function postJson(url, body) { + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body ?? {}), + }) + let data = {} + try { data = await res.json() } catch {} + if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`) + return data +} + +async function patchProject(name, body) { + const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + patchProject.error = res.ok ? '' : ((await res.json().catch(() => ({}))).error ?? '') + return res.ok +} + +function toast(text, icon = 'info') { + const el = document.getElementById('toast') + el.innerHTML = `${ic(icon)}${escapeHtml(text)}` + el.classList.add('show') + clearTimeout(toast.t) + toast.t = setTimeout(() => el.classList.remove('show'), 3400) +} + +const runAction = async (name, id) => { + try { + const r = await postJson(api(name, 'run'), { id }) + toast(`Gestartet: ${r.label}`, 'play') + } catch (e) { toast(e.message, 'triangle-alert') } +} + +/* ── filtering & sorting ──────────────────────────────────────────────── */ + +const QUICK = [ + { key: 'all', label: 'Alle', icon: 'layers', test: () => true }, + { key: 'nobackup', label: 'Ohne Remote', icon: 'cloud-off', test: (p) => p.git.level === 'red' }, + { key: 'unsaved', label: 'Ungesichert', icon: 'cloud-upload', test: (p) => p.git.level === 'yellow' }, + { key: 'cleanable', label: 'Aufräumbar', icon: 'brush-cleaning', test: (p) => deletableMB(p) >= 100 }, + { key: 'install', label: 'npm install', icon: 'download', test: (p) => p.tech?.needsInstall }, + { key: 'noicon', label: 'Ohne Icon', icon: 'image-off', test: (p) => !p.hasIcon }, + { key: 'gencopy', label: 'Generator-Kopie', icon: 'copy', test: (p) => p.tools?.generators?.some((g) => g.kind === 'copy') }, + { key: 'itch', label: 'itch.io', icon: 'rocket', test: (p) => !!p.published }, + { key: 'noitch', label: 'Fertig, nicht auf itch', icon: 'circle-off', test: (p) => p.status === 'done' && !p.published }, +] + +function matchesSearch(p) { + const term = searchTerm.trim().toLowerCase() + if (!term) return true + return p.name.toLowerCase().includes(term) || + p.notes.toLowerCase().includes(term) || + (p.tags ?? []).some((t) => t.toLowerCase().includes(term)) || + (p.tech?.types ?? []).some((t) => t.toLowerCase().includes(term)) +} + +function visibleProjects({ useStatus = true } = {}) { + const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0] + const status = document.getElementById('fltStatus').value + return projects.filter((p) => matchesSearch(p) && q.test(p) && (!useStatus || status === 'all' || p.status === status)) +} + +function sortProjects(items) { + const sort = document.getElementById('fltSort').value + return [...items].sort((a, b) => { + if (sort === 'name') return a.name.localeCompare(b.name, 'de', { sensitivity: 'base' }) + if (sort === 'priority') return (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a))) + if (sort === 'size') return (b.storage?.sizeMB ?? -1) - (a.storage?.sizeMB ?? -1) + if (sort === 'clean') return deletableMB(b) - deletableMB(a) + return new Date(lastActivity(b)) - new Date(lastActivity(a)) + }) +} + +/* ── header: KPIs, quick filters ──────────────────────────────────────── */ + +function renderKpis() { + const t = totals ?? { sizeMB: 0, cacheMB: 0, allMB: 0, scanned: 0, noBackup: 0 } + const active = projects.filter((p) => p.status === 'active').length + const running = scanState?.running + const pct = running && scanState.total ? Math.round((scanState.done / scanState.total) * 100) : 0 + document.getElementById('kpis').innerHTML = ` +
${ic('layers', 'lg')}
${projects.length}
Projekte · ${active} aktiv
+
${ic('shield-alert', 'lg')}
${t.noBackup}
ohne Git-Remote
+
${ic('hard-drive', 'lg')}
${t.scanned ? fmtMB(t.sizeMB) : '–'}
${t.scanned ? `belegt (${t.scanned} gescannt)` : 'noch nicht gescannt'}
+
${ic('brush-cleaning', 'lg')}
${t.scanned ? fmtMB(t.allMB) : '–'}
${t.scanned ? `aufräumbar · Cache ${fmtMB(t.cacheMB)}` : 'aufräumbar'}
+
+ + ${running ? `
${escapeHtml(scanState.current.join(', '))}
` + : scanState?.error ? `
${ic('triangle-alert', 'sm')} Scan-Fehler
` + : '
Größe & löschbare Ordner messen
'} +
` + document.getElementById('btnScanAll').onclick = () => startScan(null) + for (const el of document.querySelectorAll('.kpi[data-quick]')) { + el.onclick = () => { quickFilter = quickFilter === el.dataset.quick ? 'all' : el.dataset.quick; render() } + } +} + +function renderQuickFilters() { + const base = projects.filter(matchesSearch) + document.getElementById('chipfilters').innerHTML = QUICK.map((q) => { + const n = base.filter(q.test).length + if (q.key !== 'all' && n === 0 && quickFilter !== q.key) return '' + return `` + }).join('') + for (const b of document.querySelectorAll('.fchip')) b.onclick = () => { quickFilter = b.dataset.q; render() } +} + +function render() { + document.getElementById('count').textContent = !rootDir ? 'Noch kein Projektordner gewählt' + : rootPaths.length > 1 ? `${projects.length} Projekte aus ${rootPaths.length} Ordnern` : `${projects.length} Ordner unter ${rootDir}` + renderKpis() + renderQuickFilters() + updateToolbarForView() + renderBoard() + renderGallery() + renderList() + renderTasks() +} + +// Status filter makes no sense on the board (columns = status), sorting none on tasks. +function updateToolbarForView() { + document.getElementById('selStatusWrap').style.display = activeView === 'board' ? 'none' : '' + document.getElementById('selSortWrap').style.display = activeView === 'tasks' ? 'none' : '' + document.getElementById('boardMode').style.display = activeView === 'board' ? '' : 'none' +} + +/* ── scan ─────────────────────────────────────────────────────────────── */ + +function pollScan() { + clearTimeout(scanTimer) + scanTimer = setTimeout(async () => { + try { scanState = await (await fetch('/api/scan')).json() } catch { return } + renderKpis() + if (scanState.running) pollScan() + else { + await load() + if (editing) loadDetails(editing.name) + toast('Scan fertig', 'circle-check') + } + }, 1500) +} + +async function startScan(name) { + try { + const r = await postJson('/api/scan', name ? { name } : {}) + scanState = r.state + renderKpis() + pollScan() + } catch (e) { toast(e.message, 'triangle-alert') } +} + +/* ── quick start ▶ ────────────────────────────────────────────────────── */ + +// p.quickStart comes from the server: own start command, main exe or first start action +function quickStartTitle(p) { + const q = p.quickStart + return q ? `Starten: ${q.label}${q.detail ? ` (${q.detail})` : ''}` : '' +} +function qsButton(p) { + if (!p.quickStart) return '' + return `` +} +// Card/row corner: [VS Code] [▶]. placeholder keeps rows aligned when a project has no ▶. +// explorer: also an [Explorer] button in front (gallery tiles). +function qsGroup(p, placeholder = false, explorer = false) { + const ex = explorer ? `` : '' + const vs = `` + return `${ex}${vs}${qsButton(p) || (placeholder ? '' : '')}` +} +function wireQuickStart(el, p) { + const wire = (b, fn) => { + b.onclick = (e) => { e.stopPropagation(); fn() } + b.draggable = false + b.addEventListener('mousedown', (e) => e.stopPropagation()) + } + for (const b of el.querySelectorAll('[data-qs]')) wire(b, () => runAction(p.name, p.quickStart.id)) + for (const b of el.querySelectorAll('[data-vs]')) wire(b, () => runAction(p.name, 'vscode')) + for (const b of el.querySelectorAll('[data-ex]')) wire(b, () => runAction(p.name, 'explorer')) +} + +/* ── board ────────────────────────────────────────────────────────────── */ + +// 'cards' = full cards, 'rows' = one compact line per project (both draggable) +let boardMode = (() => { try { return localStorage.getItem('dash.boardMode') === 'rows' ? 'rows' : 'cards' } catch { return 'cards' } })() + +function setBoardMode(mode) { + boardMode = mode === 'rows' ? 'rows' : 'cards' + for (const b of document.querySelectorAll('#boardMode button')) b.classList.toggle('active', b.dataset.mode === boardMode) + try { localStorage.setItem('dash.boardMode', boardMode) } catch {} + renderBoard() +} + +// compact two-line row: [prio] [icon] name / size · last change · git · backup · tasks [▶] +function rowHtml(p) { + const c = cloudInfo(p) + const open = (p.tasks ?? []).filter((t) => !t.done).length + const prioTitle = `Priorität ${PRIO_LABEL[p.priority]}` + return `
+ + ${avatar(p)} +
+ ${escapeHtml(p.name)} + + ${rootTag(p, true)} + ${ic('folder', 'sm')}${p.storage?.sizeMB != null ? fmtMB(p.storage.sizeMB) : '–'} + ${ic('file-pen', 'sm')}${fmtDate(lastActivity(p))}${fmtDate(lastActivity(p), false)} + ${ic(GIT_ICON[p.git.level], 'sm')} + ${ic('hard-drive', 'sm')} + ${open ? `${ic('list-checks', 'sm')}${open}` : ''} + ${p.published ? `${ic('rocket', 'sm')}` : ''} + +
+ ${qsGroup(p, true)} +
` +} + +function cardHtml(p) { + const total = (p.tasks ?? []).length + const done = (p.tasks ?? []).filter((t) => t.done).length + const tags = (p.tags ?? []).map((t) => `${ic('tag', 'sm')}${escapeHtml(t)}`).join('') + return ` +
${avatar(p)} +
${escapeHtml(p.name)}
+
${rootTag(p, true)}${prioHtml(p.priority)}
+ ${qsGroup(p)} +
+ ${p.lastCommit ? `
${ic('git-commit-horizontal', 'sm')}${escapeHtml(p.lastCommit.message)}
` : ''} + ${factsHtml(p)} +
${gitHtml(p.git)}${cloudChip(p)}${pubChip(p)}
+
${techChips(p.tech?.types)}${warnChips(p)}${tags}
+ ${p.notes ? `
${escapeHtml(p.notes)}
` : ''} + ${total ? `
${ic('list-checks', 'sm')}${done}/${total}
` : ''}` +} + +function renderBoard() { + const board = document.getElementById('board') + board.innerHTML = '' + const visible = visibleProjects({ useStatus: false }) + + for (const col of STATUS) { + const items = visible + .filter((p) => p.status === col.key) + .sort((a, b) => (PRIO_ORDER[a.priority] - PRIO_ORDER[b.priority]) || (new Date(lastActivity(b)) - new Date(lastActivity(a)))) + + const colEl = document.createElement('div') + colEl.className = 'column' + colEl.innerHTML = `

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

` + colEl.addEventListener('dragover', (e) => { e.preventDefault(); colEl.classList.add('drag-over') }) + colEl.addEventListener('dragleave', () => colEl.classList.remove('drag-over')) + colEl.addEventListener('drop', async (e) => { + e.preventDefault() + colEl.classList.remove('drag-over') + const name = e.dataTransfer.getData('text/plain') + const project = projects.find((p) => p.name === name) + if (!project || project.status === col.key) return + if (await patchProject(name, { status: col.key })) { toast(`${name} → ${col.label}`, col.icon); load() } + }) + // cards live in their own scroll area, so the page never grows + const cardsEl = document.createElement('div') + cardsEl.className = 'cards' + colEl.appendChild(cardsEl) + if (!items.length) cardsEl.innerHTML = `
${ic('inbox')}
` + + for (const p of items) { + const card = document.createElement('div') + card.className = boardMode === 'rows' ? 'card row' : 'card' + card.draggable = true + card.innerHTML = boardMode === 'rows' ? rowHtml(p) : cardHtml(p) + card.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', p.name); card.classList.add('dragging') }) + card.addEventListener('dragend', () => card.classList.remove('dragging')) + card.onclick = () => openEditor(p) + wireQuickStart(card, p) + cardsEl.appendChild(card) + } + board.appendChild(colEl) + } +} + +/* ── gallery ──────────────────────────────────────────────────────────── */ + +function renderGallery() { + const grid = document.getElementById('galleryGrid') + const items = sortProjects(visibleProjects()) + if (!items.length) { grid.innerHTML = `
${ic('search-x', 'xl')}
Keine Projekte gefunden.
`; return } + grid.innerHTML = '' + for (const p of items) { + const tile = document.createElement('div') + tile.className = 'tile' + tile.title = p.name + tile.innerHTML = ` +
${escapeHtml(initialsOf(p.name))} + + ${statusHtml(p.status)} + ${pubBadge(p)}${cloudBadge(p)}${ic(GIT_ICON[p.git.level])} +
+
+
${escapeHtml(p.name)}
${qsGroup(p, false, true)}
+
${techChips(p.tech?.types)}
+
${prioHtml(p.priority)}${rootTag(p, true)}${p.storage?.sizeMB != null ? `${ic('hard-drive', 'sm')} ${fmtMB(p.storage.sizeMB)} · ` : ''}${timeAgo(lastActivity(p))}
+
` + wireQuickStart(tile, p) + tile.onclick = () => openEditor(p) + grid.appendChild(tile) + } +} + +/* ── list ─────────────────────────────────────────────────────────────── */ + +// cls: used by CSS container queries to hide columns in narrow windows +const LIST_COLS = [ + { label: 'Projekt', sort: 'name' }, { label: 'Status', cls: 'c-status' }, { label: 'Git' }, { label: 'Backup' }, { label: 'Technik', cls: 'c-tech' }, + { label: 'Größe', sort: 'size', num: true }, { label: 'Aufräumbar', sort: 'clean', num: true, cls: 'c-clean' }, + { label: 'Aktivität', sort: 'mtime', cls: 'c-act' }, { label: '' }, +] + +function renderList() { + const table = document.getElementById('listTable') + const items = sortProjects(visibleProjects()) + const sort = document.getElementById('fltSort').value + table.innerHTML = `${LIST_COLS.map((c) => `${c.label}${c.sort === sort ? ' ' + ic('arrow-down', 'sm') : ''}`).join('')} + ${items.map((p) => ` +
${avatar(p)}${escapeHtml(p.name)}${rootTag(p, true)}
+
${statusHtml(p.status)}${pubChip(p, true)}
+ ${gitHtml(p.git, true)} + ${cloudChip(p)} +
${techChips(p.tech?.types)}${p.tech?.needsInstall ? `${ic('download', 'sm')}install` : ''}
+ ${fmtMB(p.storage?.sizeMB)} + ${p.storage ? fmtMB(deletableMB(p)) : '–'} + ${fmtDate(lastActivity(p))} · ${timeAgo(lastActivity(p))} +
+ ${p.quickStart ? `` : ''} + + + +
`).join('') || `Keine Projekte gefunden.`}` + for (const th of table.querySelectorAll('th[data-sort]')) { + th.onclick = () => { document.getElementById('fltSort').value = th.dataset.sort; render() } + } + for (const tr of table.querySelectorAll('tbody tr[data-name]')) { + const p = projects.find((x) => x.name === tr.dataset.name) + tr.onclick = () => openEditor(p) + wireQuickStart(tr, p) + for (const b of tr.querySelectorAll('button[data-a]')) { + b.onclick = (e) => { + e.stopPropagation() + if (b.dataset.a === 'details') openEditor(p) + else runAction(p.name, b.dataset.a) + } + } + } +} + +function setView(view) { + activeView = view + for (const el of document.querySelectorAll('.view')) el.classList.toggle('active', el.id === view) + for (const btn of document.querySelectorAll('#tabs button')) btn.classList.toggle('active', btn.dataset.view === view) + updateToolbarForView() + try { localStorage.setItem('dash.view', view) } catch {} +} + +/* ── tasks view (all projects) ────────────────────────────────────────── */ + +let taskMode = 'open' // open | done | all +const STATUS_ORDER = { active: 0, paused: 1, idea: 2, done: 3, archived: 4 } + +const newTaskId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6) + +// Saves a project's full task list; the UI updates first, a failure reloads. +async function saveTasks(p, tasks) { + p.tasks = tasks + renderTasks() + updateTaskCount() + if (!(await patchProject(p.name, { tasks }))) { toast('Speichern fehlgeschlagen', 'triangle-alert'); load() } +} + +function updateTaskCount() { + const open = projects.reduce((n, p) => n + (p.tasks ?? []).filter((t) => !t.done).length, 0) + document.getElementById('taskCount').textContent = open || '' +} + +function renderTasks() { + updateTaskCount() + const term = searchTerm.trim().toLowerCase() + const q = QUICK.find((x) => x.key === quickFilter) ?? QUICK[0] + const status = document.getElementById('fltStatus').value + + // project picker for "add": active projects first + const sel = document.getElementById('taskProject') + const prev = sel.value || editing?.name + const ordered = [...projects].sort((a, b) => (STATUS_ORDER[a.status] - STATUS_ORDER[b.status]) || a.name.localeCompare(b.name, 'de')) + sel.innerHTML = ordered.map((p) => ``).join('') + if (prev && projects.some((p) => p.name === prev)) sel.value = prev + + const groups = [] + for (const p of ordered) { + if (!q.test(p) || (status !== 'all' && p.status !== status)) continue + const projectHit = !term || p.name.toLowerCase().includes(term) || (p.tags ?? []).some((t) => t.toLowerCase().includes(term)) + const tasks = (p.tasks ?? []).filter((t) => + (taskMode === 'all' || (taskMode === 'open' ? !t.done : t.done)) && + (projectHit || t.text.toLowerCase().includes(term))) + if (tasks.length) groups.push({ p, tasks }) + } + + const el = document.getElementById('taskGroups') + el.classList.toggle('isEmpty', !groups.length) + if (!groups.length) { + el.innerHTML = `
${ic(taskMode === 'done' ? 'inbox' : 'party-popper', 'xl')}
${taskMode === 'open' ? 'Keine offenen Aufgaben.' : 'Keine Aufgaben gefunden.'}
+
Oben ein Projekt wählen und eine Aufgabe eintragen.
` + return + } + el.innerHTML = groups.map(({ p, tasks }) => { + const all = p.tasks ?? [] + const done = all.filter((t) => t.done).length + return `
+
${avatar(p)}${escapeHtml(p.name)}${statusHtml(p.status)}${done}/${all.length}
+
+ ${tasks.map((t) => `
+ ${escapeHtml(t.text)} +
`).join('')} +
+
` + }).join('') + + for (const g of el.querySelectorAll('.tgroup')) { + const p = projects.find((x) => x.name === g.dataset.name) + g.querySelector('.tg-head').onclick = () => openEditor(p) + for (const row of g.querySelectorAll('.titem')) { + const id = row.dataset.id + row.querySelector('input').onchange = (e) => + saveTasks(p, (p.tasks ?? []).map((t) => (t.id === id ? { ...t, done: e.target.checked } : t))) + row.querySelector('.del').onclick = () => saveTasks(p, (p.tasks ?? []).filter((t) => t.id !== id)) + } + const input = g.querySelector('.tg-add input') + input.onkeydown = (e) => { + if (e.key !== 'Enter' || !input.value.trim()) return + const text = input.value.trim() + saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }]).then(() => { + const again = document.querySelector(`.tgroup[data-name="${CSS.escape(p.name)}"] .tg-add input`) + again?.focus() + }) + } + } +} + +function addTaskTop() { + const input = document.getElementById('taskNew') + const text = input.value.trim() + const p = projects.find((x) => x.name === document.getElementById('taskProject').value) + if (!text || !p) return + input.value = '' + if (taskMode === 'done') setTaskMode('open') + saveTasks(p, [...(p.tasks ?? []), { id: newTaskId(), text, done: false }]) + toast(`Aufgabe zu ${p.name} hinzugefügt`, 'list-checks') + input.focus() +} + +function setTaskMode(mode) { + taskMode = mode + for (const b of document.querySelectorAll('#taskMode button')) b.classList.toggle('active', b.dataset.mode === mode) + renderTasks() +} + +/* ── side panel ───────────────────────────────────────────────────────── */ + +function setSection(sec) { + for (const el of document.querySelectorAll('.psec')) el.classList.toggle('active', el.id === `sec-${sec}`) + for (const btn of document.querySelectorAll('#ptabs button')) btn.classList.toggle('active', btn.dataset.sec === sec) +} + +function renderTaskList() { + const ul = document.getElementById('taskList') + ul.innerHTML = '' + for (const t of editingTasks) { + const li = document.createElement('li') + li.className = t.done ? 'done' : '' + const cb = document.createElement('input') + cb.type = 'checkbox' + cb.checked = t.done + cb.onchange = () => { t.done = cb.checked; renderTaskList() } + const span = document.createElement('span') + span.textContent = t.text + const del = document.createElement('button') + del.className = 'btn ghost' + del.innerHTML = ic('trash', 'sm') + del.onclick = () => { editingTasks = editingTasks.filter((x) => x !== t); renderTaskList() } + li.append(cb, span, del) + ul.appendChild(li) + } +} + +function addTaskFromInput() { + const input = document.getElementById('taskInput') + const text = input.value.trim() + if (!text) return + editingTasks.push({ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text, done: false }) + input.value = '' + renderTaskList() + input.focus() +} + +// cleanup paths are "\rest" (relative to the projects folder) → "rest" +const inProject = (p) => p.slice(p.indexOf('\\') + 1) + +function section(icon, title, body) { + return `

${ic(icon)}${title}

${body}
` +} + +function renderInfo(name, d) { + const g = d.git + const key = d.sshKey + const keyHint = key + ? `
${ic('key-round', 'sm')} SSH-Schlüssel: ${escapeHtml(key.file)}
` + : `
${ic('key-round', 'sm')} Kein SSH-Schlüssel gefunden. Anlegen mit ssh-keygen -t ed25519, dann den Inhalt von .ssh\\id_ed25519.pub bei GitHub/GitLab eintragen.
` + const pushBox = !g.remote ? '' : g.dirty + ? `
+ + + +
` + : `
` + const gitBody = g.isRepo + ? `
+
Status
${gitHtml(g)}
+
Branch
${ic('git-branch', 'sm')} ${escapeHtml(g.branch)}${g.upstream ? ` → ${escapeHtml(g.upstream)}` : ''}
+
Letzter Commit
${g.lastCommit ? `${g.lastCommit.date} · ${escapeHtml(g.lastCommit.message)}` : '–'}
+
+ +
+ + +
+ ${g.remote ? '' : '
Noch kein Remote – das Projekt liegt nur auf dieser Platte.
'} + ${pushBox} + ${keyHint} +
Push läuft in einem eigenen Konsolenfenster (dort erscheinen SSH-Passphrase und Fehler).
` + : `
${gitHtml(g)}
Kein Git-Repository – Änderungen sind nirgends gesichert.
+
` + + const gens = d.tools.generators + const genBody = gens.length + ? `
${gens.map((x) => `
${escapeHtml(x.rel)}
${x.kind === 'comfygen' + ? `${ic('wand-sparkles', 'sm')}nutzt _Tools\\ComfyGen` + : `${ic('copy', 'sm')}eigene Kopie
${escapeHtml(x.scripts.join(', '))}
`}
`).join('')}
` + : '
Kein Generator-Ordner.
' + + const genDir = gens.find((x) => x.kind === 'comfygen') + const iconBody = d.icon + ? `
${escapeHtml(d.icon)}
` + : `
${ic('image-off', 'sm')}kein Icon gefunden
+
${genDir ? 'Mit ComfyGen erzeugen (Prompt „icon“ in prompts.py eintragen):' : 'Generator-Vorlage aus _Tools\\ComfyGen\\template kopieren, dann:'}
+ cd "${escapeHtml(d.path)}\\${escapeHtml(genDir ? genDir.rel : 'sprite-generator')}" && gen generate icon && gen adopt icon` + + const s = d.storage + let storageBody + if (!s) storageBody = '
Noch nicht gescannt.
' + else { + const rows = s.candidates.filter((c) => c.MB >= 1 || c.Skip) + storageBody = `
Größe
${fmtMB(s.sizeMB)} · gescannt ${timeAgo(s.at)}
+
Löschbar
Cache ${fmtMB(s.deletable.Cache)} · Builds ${fmtMB(s.deletable.Release)} · Rohbilder ${fmtMB(s.deletable.Output)}
` + storageBody += rows.length + ? `${rows.map((c) => ` + + + + `).join('')}
${escapeHtml(inProject(c.Path))}${ic(TIER[c.Tier].icon, 'sm')}${TIER[c.Tier].label}${c.Skip ? ` ${ic('lock', 'sm')}in git` : ''}${fmtMB(c.MB)}
+
+
Cache ist vorausgewählt (immer neu erzeugbar). Fertige Builds und Rohbilder nur bewusst anhaken.
` + : `
${ic('sparkles', 'sm')} Nichts zum Aufräumen.
` + } + storageBody += `
` + + document.getElementById('sec-info').innerHTML = + section('cloud', 'Git & Backup', gitBody) + + section('cpu', 'Technik', `
${techChips(d.tech.types) || 'nicht erkannt'}${d.tech.needsInstall ? `${ic('download', 'sm')}npm install nötig` : ''}
`) + + section('hard-drive', 'Speicher', storageBody) + + section('wand-sparkles', 'Generator', genBody) + + section('image', 'App-Icon', iconBody) + + document.getElementById('btnScanOne').onclick = () => startScan(name) + const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn } + const refreshInfo = () => { load(); loadDetails(name) } + on('btnPush', async () => { + try { await postJson(api(name, 'push')); toast('Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') } + }) + on('btnCommitPush', async () => { + const msg = document.getElementById('gMsg').value.trim() + if (!msg) { document.getElementById('gMsg').focus(); return toast('Bitte eine Commit-Nachricht eingeben', 'info') } + try { await postJson(api(name, 'push'), { message: msg }); toast('Commit & Push läuft in eigener Konsole', 'cloud-upload') } catch (e) { toast(e.message, 'triangle-alert') } + }) + on('btnRemote', async () => { + try { await postJson(api(name, 'remote'), { url: document.getElementById('gRemote').value }); toast('Remote gespeichert', 'link'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') } + }) + const rem = document.getElementById('gRemote') + if (rem) rem.onkeydown = (e) => { if (e.key === 'Enter') document.getElementById('btnRemote').click() } + on('btnGitInit', async () => { + try { await postJson(api(name, 'git-init')); toast('Git eingerichtet (Branch main)', 'git-branch'); refreshInfo() } catch (e) { toast(e.message, 'triangle-alert') } + }) + on('btnCopyKey', async () => { + try { await navigator.clipboard.writeText(d.sshKey.key); toast('SSH-Schlüssel kopiert', 'copy') } catch { toast('Kopieren nicht möglich', 'triangle-alert') } + }) + const clean = document.getElementById('btnClean') + if (clean) clean.onclick = async () => { + const paths = [...document.querySelectorAll('.candcb:checked')].map((cb) => cb.dataset.path) + if (!paths.length) return toast('Nichts ausgewählt') + const mb = s.candidates.filter((c) => paths.includes(c.Path)).reduce((a, c) => a + c.MB, 0) + if (!confirm(`${paths.length} Ordner (${fmtMB(mb)}) in „${name}“ endgültig löschen?\n\n${paths.map(inProject).join('\n')}`)) return + clean.disabled = true + clean.innerHTML = `${ic('loader')}Lösche…` + try { + const r = await postJson(api(name, 'clean'), { paths }) + toast(`${r.deleted.length} gelöscht, ${String(r.freedGB).replace('.', ',')} GB frei${r.failed.length ? ` · ${r.failed.length} gesperrt (Programm offen?)` : ''}`, 'brush-cleaning') + await load() + loadDetails(name) + } catch (e) { toast(e.message, 'triangle-alert'); clean.disabled = false; clean.innerHTML = `${ic('trash')}Ausgewählte löschen` } + } +} + +function renderActions(name, d) { + const groups = {} + for (const a of d.actions) (groups[a.group] ??= []).push(a) + const order = ['Einrichten', 'Starten', 'Bauen', 'Werkzeuge', 'Öffnen'] + const ACT_ICON = (a) => a.id === 'vscode' ? 'code-xml' : a.id === 'explorer' ? 'folder-open' : a.id === 'console' ? 'square-terminal' + : a.id.startsWith('unity') ? 'box' : a.id.startsWith('exe:') ? 'app-window' : a.id.startsWith('bat:') ? 'file-terminal' : a.id === 'web' ? 'globe' : a.id.startsWith('gen:') ? 'wand-sparkles' + : a.id.startsWith('npm-install') ? 'download' : ACTION_ICON[a.group] + + // the project's own programs (exe + html pages) come first, as big start buttons; + // the pin chooses which one the ▶ on the cards starts + const programs = groups['Programm'] ?? [] + const hasBuild = !!groups['Bauen'] + const prog = d.program // { rel, missing } or null + const progHtml = (programs.length + ? `
${programs.map((a, i) => { + const pinned = a.id === 'program' + return `
+ + ${a.rel ? `` : ''} +
` + }).join('')}
` + : `
Keine fertige exe oder HTML-Seite im Projekt gefunden.${hasBuild ? ' Unter „Bauen“ erzeugen, dann hier starten.' : ''}
`) + + (prog?.missing ? `
${ic('triangle-alert', 'sm')} Festgelegte Datei fehlt: ${escapeHtml(prog.rel)} – neu wählen oder zurücksetzen.
` : '') + + `
+ +
+ + ${hasPicker ? `` : ''} + + ${prog ? `` : ''} +
+
` + + projectLastBackup = d.lastBackup ?? null + projectTargets = d.backupTargets ?? [] + document.getElementById('sec-actions').innerHTML = section('app-window', 'Programm starten', progHtml) + + (name === '_Tools' ? '' : section('hard-drive-upload', 'Sichern', '
')) + + order.filter((g) => groups[g]).map((g) => + section(ACTION_ICON[g], g, `
${groups[g].map((a) => + ``).join('')}
`)).join('') + + `
${ic('shield-check', 'sm')} Programme starten direkt, Befehle und .bat laufen sichtbar in einem eigenen Konsolenfenster. Eigenen Start-Befehl unter „Bearbeiten“ festlegen.
` + for (const btn of document.querySelectorAll('#sec-actions .act')) btn.onclick = () => runAction(name, btn.dataset.id) + for (const btn of document.querySelectorAll('#sec-actions .pin')) btn.onclick = () => setProgram(name, btn.dataset.rel) + const input = document.getElementById('fProgram') + document.getElementById('btnSetProgram').onclick = () => setProgram(name, input.value) + input.onkeydown = (e) => { if (e.key === 'Enter') setProgram(name, input.value) } + document.getElementById('btnClearProgram')?.addEventListener('click', () => setProgram(name, '')) + document.getElementById('btnPickProgram')?.addEventListener('click', async () => { + const file = await pickFile(`Programm für ${name} wählen`, d.path) + if (file) setProgram(name, file) + }) + renderProjectBackup(name) + if (!backup) loadBackup() +} + +// Saves the program the ▶ starts ('' = choose automatically again). +async function setProgram(name, program) { + try { + const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ program }), + }) + const r = await res.json().catch(() => ({})) + if (!res.ok) throw new Error(r.error ?? 'Speichern fehlgeschlagen') + toast(r.program ? `▶ startet jetzt: ${r.program}` : '▶ wählt wieder automatisch', 'pin') + if (editing?.name === name) { editing.program = r.program; loadDetails(name) } + load() + } catch (e) { toast(e.message, 'triangle-alert') } +} + +/* ── per-project backup ("Sichern" in Aktionen) ─────────────────────── */ + +let projectLastBackup = null +let projectTargets = [] // [{ id, name, last }] – this project on every backup target + +function renderProjectBackup(name) { + const el = document.getElementById('pbackupBody') + if (!el || editing?.name !== name) return + const b = backup + const t = curTarget() + const busy = backupBusy() + // the job belongs to this project; while it runs it also decides the shown target + const mine = b && b.scope === name && (busy || b.target === t?.id) + const last = projectLastBackup + if (b?.notConfigured) { + el.innerHTML = `
${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt (z. B. externe Platte oder NAS).
+
` + document.getElementById('pbSetup').onclick = () => openSettings(false) + return + } + const shownT = busy && mine ? (b.targets.find((x) => x.id === b.target) ?? t) : t + let html = targetTabs(busy ? b.target : null) + `
Zuletzt gesichert
${last + ? `${new Date(last.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(last.at)}) · ${last.how}` + : 'noch nie'}
+
Ziel
${escapeHtml(shownT ? `${shownT.path}\\${name}` : '…')}
+ ${projectTargets.length > 1 ? `
Alle Ziele
${projectTargets.map((x) => { + const lv = !x.last ? 'red' : (Date.now() - new Date(x.last.at)) / 86400000 > BACKUP_FRESH_DAYS ? 'yellow' : 'green' + return `${ic('hard-drive', 'sm')}${escapeHtml(x.name)} · ${x.last ? timeAgo(x.last.at) : 'nie'}` + }).join('')}
` : ''}
` + + if (busy && mine && b.phase === 'checking') { + html += `
${ic('loader')}
Prüfe, was im Backup fehlt…
` + } else if (busy && mine && b.phase === 'copying') { + const pr = b.progress + const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0 + html += `
Kopiere… ${pct} %${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
+
+
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
+
${escapeHtml(pr.current)}
` + } else if (busy) { + html += `
${ic('hourglass')}
Es läuft gerade ein anderes Backup (${b.scope ? escapeHtml(b.scope) : 'alle Projekte'}). Danach geht es hier.
` + } else if (mine && b.phase === 'done') { + const l = shownT?.lastByProject?.[name] + html += l && l.files + ? `
${ic('circle-check')}
Gesichert. ${l.files.toLocaleString('de-DE')} Dateien (${fmtBytes(l.bytes)}) neu ins Backup kopiert.
` + : `
${ic('circle-check')}
Alles aktuell. Im Backup fehlte nichts.
` + } else if (mine && b.phase === 'error') { + html += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` + } else if (mine && b.phase === 'cancelled') { + html += `
${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
` + } + + html += `
${busy && mine + ? `` + : ``}
+
Prüft das Projekt im Backup und kopiert nur fehlende und geänderte Dateien. Gelöscht wird dort nichts.
` + el.innerHTML = html + + const save = document.getElementById('pbSave') + if (save) save.onclick = async () => { + try { + backup = await postJson('/api/backup/check', { project: name, autoCopy: true, target: curTargetId() }) + renderProjectBackup(name) + loadBackup() + } catch (e) { toast(e.message, 'triangle-alert') } + } + const cancel = document.getElementById('pbCancel') + if (cancel) cancel.onclick = () => backupAction('cancel') +} + +async function loadDetails(name) { + try { + const res = await fetch(`${api(name, 'details')}?target=${encodeURIComponent(curTargetId())}`) + const d = await res.json() + if (!res.ok) throw new Error(d.error) + if (editing?.name !== name) return + renderInfo(name, d) + renderActions(name, d) + } catch (e) { + document.getElementById('sec-info').innerHTML = `
Fehler: ${escapeHtml(e.message)}
` + } +} + +function openEditor(p) { + closeBackup() + editing = p + editingTasks = (p.tasks ?? []).map((t) => ({ ...t })) + document.getElementById('pAvatar').innerHTML = avatar(p, 'lg') + document.getElementById('panelTitle').textContent = p.name + document.getElementById('panelSub').innerHTML = `${statusHtml(p.status)}${gitHtml(p.git, true)}${techChips(p.tech?.types)}${pubChip(p)}` + document.getElementById('fStatus').value = p.status + document.getElementById('fPriority').value = p.priority + document.getElementById('fTags').value = (p.tags ?? []).join(', ') + document.getElementById('fThumb').value = p.thumbnail ?? '' + document.getElementById('fStart').value = p.start ?? '' + document.getElementById('fItch').value = p.itch ?? '' + document.getElementById('fItchHint').innerHTML = p.itch === '-' + ? `${ic('circle-off', 'sm')} als „nicht veröffentlicht“ markiert` + : p.published?.source === 'auto' + ? `${ic('sparkles', 'sm')} automatisch erkannt: ${escapeHtml(p.published.title)} – ${escapeHtml(p.published.url)}` + : p.published ? '' : `${ic('info', 'sm')} nicht auf dem itch.io-Profil gefunden` + document.getElementById('fNotes').value = p.notes + renderTaskList() + const loading = `
${ic('loader', 'sm')} Lädt…
` + document.getElementById('sec-info').innerHTML = loading + document.getElementById('sec-actions').innerHTML = loading + document.getElementById('overlay').classList.add('open') + document.getElementById('panel').classList.add('open') + document.getElementById('panel').setAttribute('aria-hidden', 'false') + loadDetails(p.name) +} + +function closeEditor() { + editing = null + editingTasks = [] + document.getElementById('overlay').classList.remove('open') + document.getElementById('panel').classList.remove('open') + document.getElementById('panel').setAttribute('aria-hidden', 'true') +} + +async function saveEditor() { + if (!editing) return + const body = { + status: document.getElementById('fStatus').value, + priority: document.getElementById('fPriority').value, + notes: document.getElementById('fNotes').value, + tags: document.getElementById('fTags').value.split(',').map((s) => s.trim()).filter(Boolean), + thumbnail: document.getElementById('fThumb').value.trim(), + start: document.getElementById('fStart').value.trim(), + itch: document.getElementById('fItch').value.trim(), + tasks: editingTasks, + } + if (await patchProject(editing.name, body)) { + toast('Gespeichert', 'save') + closeEditor() + load() + } else toast(patchProject.error || 'Speichern fehlgeschlagen', 'triangle-alert') +} + +/* ── backup (NAS) ─────────────────────────────────────────────────────── */ + +let backup = null +let backupTimer = null +const fmtBytes = (b) => (b ?? 0) < 1048576 ? `${Math.max(b ? 1 : 0, Math.round((b ?? 0) / 1024))} KB` : fmtMB(b / 1048576) +const backupBusy = () => backup && (backup.phase === 'checking' || backup.phase === 'copying') + +// Selected backup target (several possible): cards, tiles and "Sichern" use this one. +let backupTargetId = '' +try { backupTargetId = localStorage.getItem('dash.backupTarget') ?? '' } catch {} +function curTarget() { + const list = backup?.targets ?? [] + return list.find((t) => t.id === backupTargetId) ?? list[0] ?? null +} +const curTargetId = () => curTarget()?.id ?? backupTargetId +function selectTarget(id) { + if (id === curTargetId()) return + backupTargetId = id + try { localStorage.setItem('dash.backupTarget', id) } catch {} + renderBackupButton() + if (document.getElementById('bpanel').classList.contains('open')) renderBackup() + load() + if (editing) loadDetails(editing.name) +} +// reiter for the targets; disabled while a backup runs on another one +function targetTabs(busyId) { + const list = backup?.targets ?? [] + if (list.length < 2) return '' + const cur = curTargetId() + return `
${list.map((t) => ``).join('')}
` +} +document.addEventListener('click', (e) => { + const b = e.target.closest('.ttabs [data-target]') + if (b && !b.disabled) selectTarget(b.dataset.target) +}) + +async function loadBackup() { + const wasBusy = backupBusy() + try { backup = await (await fetch('/api/backup')).json() } catch { return } + if (wasBusy && !backupBusy()) load() // refresh the backup badges on cards/tiles/list + renderBackupButton() + if (document.getElementById('bpanel').classList.contains('open')) renderBackup() + if (editing) { + const own = curTarget()?.lastByProject?.[editing.name] + if (own && (!projectLastBackup || own.at > projectLastBackup.at)) projectLastBackup = { ...own, how: 'Projekt' } + renderProjectBackup(editing.name) + } + clearTimeout(backupTimer) + if (backupBusy()) backupTimer = setTimeout(loadBackup, 1000) +} + +function renderBackupButton() { + const sub = document.getElementById('backupSub') + if (!backup) return + const btn = document.getElementById('btnBackup') + btn.title = (backup.targets ?? []).map((t) => `${t.name}: ${t.last ? 'zuletzt ' + timeAgo(t.last.at) : 'noch nie komplett gesichert'}`).join('\n') || 'Backup-Ziel einrichten' + if (backup.notConfigured) { sub.textContent = '· einrichten'; sub.classList.add('warn'); return } + const t = curTarget() + const last = t?.last + const prefix = backup.targets.length > 1 ? `· ${t.name} ` : '· ' + if (backup.phase === 'checking') sub.textContent = '· prüft…' + else if (backup.phase === 'copying') { + const pr = backup.progress + sub.textContent = `· ${pr.bytesTotal ? Math.round((pr.bytes / pr.bytesTotal) * 100) : 0} %` + } else if (last) sub.textContent = `${prefix}${timeAgo(last.at)}` + else sub.textContent = `${prefix}noch nie` + const old = last && (Date.now() - new Date(last.at)) > 7 * 86400000 + sub.classList.toggle('warn', !last || old || last.ok === false) +} + +async function backupAction(what) { + try { + backup = await postJson(`/api/backup/${what}`, what === 'check' ? { target: curTargetId() } : {}) + renderBackup() + loadBackup() + } catch (e) { toast(e.message, 'triangle-alert') } +} + +function renderBackup() { + let b = backup + if (!b) return + if (b.notConfigured) { + document.getElementById('bpTarget').textContent = 'kein Ziel festgelegt' + document.getElementById('bpBody').innerHTML = `
${ic('hard-drive-upload')}
Noch kein Backup-Ziel festgelegt. Wähle einen Ordner auf einer externen Platte, einem NAS oder einem anderen Laufwerk.
+
` + document.getElementById('bpSetup').onclick = () => openSettings(false) + return + } + // a running job shows its own target; otherwise the selected one (and its last result only if the job was for it) + const busy = backupBusy() + const jobT = b.targets.find((t) => t.id === b.target) + const t = busy && jobT ? jobT : curTarget() + const phase = busy || (jobT && jobT.id === t.id) ? b.phase : 'idle' + document.getElementById('bpTarget').innerHTML = `${ic('folder', 'sm')} ${escapeHtml(b.source)} ${ic('arrow-right', 'sm')} ${escapeHtml(t.path)}` + const tl = t.last + const last = tl + ? `
Letztes Backup
${new Date(tl.at).toLocaleString('de-DE', { dateStyle: 'medium', timeStyle: 'short' })} (${timeAgo(tl.at)})
+
Kopiert
${tl.files.toLocaleString('de-DE')} Dateien · ${fmtBytes(tl.bytes)}${tl.ok === false ? ' · unvollständig' : ''}
` + : `
Auf „${escapeHtml(t.name)}“ wurde über das Dashboard noch kein Komplett-Backup gemacht.
` + + let body = targetTabs(busy ? b.target : null) + section('clock-3', `Status – ${escapeHtml(t.name)}`, last) + b = { ...b, phase } + if (b.scope && b.phase !== 'idle') { + body += `
${ic('folder')}
Der aktuelle Lauf betrifft nur das Projekt ${escapeHtml(b.scope)} (gestartet über „Sichern“ im Projekt).
` + } + + if (b.phase === 'checking') { + body += `
${ic('loader')}
Prüfe, was neu ist und im Backup fehlt…
Dauert über das Netzwerk etwa 1–2 Minuten.
+
` + } else if (b.phase === 'copying') { + const pr = b.progress + const pct = pr.bytesTotal ? Math.min(100, Math.round((pr.bytes / pr.bytesTotal) * 100)) : 0 + body += section('hard-drive-upload', 'Kopiere…', ` +
${pct} %${fmtBytes(pr.bytes)} / ${fmtBytes(pr.bytesTotal)}
+
+
${pr.files.toLocaleString('de-DE')} / ${pr.filesTotal.toLocaleString('de-DE')} Dateien
+
${escapeHtml(pr.current)}
`) + + `
+
Das Fenster bitte offen lassen, bis das Backup fertig ist.
` + } else if (b.phase === 'ready' && b.check) { + const c = b.check + if (!c.files) { + body += `
${ic('circle-check')}
Alles aktuell. Im Backup fehlt nichts.
` + } else { + body += section('scan-search', `Ergebnis der Prüfung ${timeAgo(c.at)}`, ` +
+
${ic('file-plus', 'sm')}Neu
${c.newFiles.toLocaleString('de-DE')}
${fmtBytes(c.newBytes)}
+
${ic('file-pen', 'sm')}Geändert
${c.changedFiles.toLocaleString('de-DE')}
${fmtBytes(c.changedBytes)}
+
${ic('archive', 'sm')}Nur im Backup
${c.extraFiles.toLocaleString('de-DE')}
bleiben erhalten
+
+ ${c.projects.slice(0, 15).map((p) => ``).join('')}
${escapeHtml(p.name)}${p.files.toLocaleString('de-DE')} Dateien${fmtBytes(p.bytes)}
+ ${c.projects.length > 15 ? `
+ ${c.projects.length - 15} weitere Projekte
` : ''}`) + } + body += `
+ + ${c.files ? `` : ''} +
` + } else { + if (b.phase === 'done') body += `
${ic('circle-check')}
Backup fertig. ${tl && !b.scope ? `${tl.files.toLocaleString('de-DE')} Dateien, ${fmtBytes(tl.bytes)} kopiert.` : ''}
` + if (b.phase === 'cancelled') body += `
${ic('circle-x')}
Abgebrochen. Bereits kopierte Dateien bleiben im Backup.
` + if (b.phase === 'error') body += `
${ic('triangle-alert')}
${escapeHtml(b.error)}
` + body += `
` + } + + body += `
${ic('shield-check', 'sm')} Im Backup wird nie etwas gelöscht – nur neue und geänderte Dateien kommen dazu. + Nicht gesichert (wird neu erzeugt): ${escapeHtml((settingsCache?.backup?.excludeDirs ?? ['node_modules', '__pycache__', '.gradle', '.venv']).join(', '))}. + Ziel und Ausnahmen: Einstellungen (Zahnrad oben).
` + + document.getElementById('bpBody').innerHTML = body + const on = (id, fn) => { const el = document.getElementById(id); if (el) el.onclick = fn } + on('bpCheck', () => backupAction('check')) + on('bpCopy', () => backupAction('copy')) + on('bpCancel', () => backupAction('cancel')) +} + +function openBackup() { + closeEditor() + document.getElementById('overlay').classList.add('open') + document.getElementById('bpanel').classList.add('open') + document.getElementById('bpanel').setAttribute('aria-hidden', 'false') + renderBackup() + loadBackup() +} + +function closeBackup() { + document.getElementById('bpanel').classList.remove('open') + document.getElementById('bpanel').setAttribute('aria-hidden', 'true') + if (!editing) document.getElementById('overlay').classList.remove('open') +} + +/* ── theme ────────────────────────────────────────────────────────────── */ + +// Theme mode: 'light', 'dark' or 'system' (follows Windows, also live when it changes). +const systemDark = matchMedia('(prefers-color-scheme: dark)') +let themeMode = 'system' + +function applyTheme() { + const theme = themeMode === 'system' ? (systemDark.matches ? 'dark' : 'light') : themeMode + document.documentElement.dataset.theme = theme + for (const b of document.querySelectorAll('#themeSeg button')) b.classList.toggle('active', b.dataset.mode === themeMode) +} +function setThemeMode(mode) { + themeMode = ['light', 'dark', 'system'].includes(mode) ? mode : 'system' + applyTheme() + try { localStorage.setItem('dash.theme', themeMode) } catch {} +} +function initTheme() { + let saved = null + try { saved = localStorage.getItem('dash.theme') } catch {} + saved = new URLSearchParams(location.search).get('theme') ?? saved + themeMode = ['light', 'dark', 'system'].includes(saved) ? saved : 'system' + applyTheme() +} +systemDark.addEventListener('change', () => { if (themeMode === 'system') applyTheme() }) +for (const b of document.querySelectorAll('#themeSeg button')) b.onclick = () => setThemeMode(b.dataset.mode) + +/* ── wiring ───────────────────────────────────────────────────────────── */ + +document.getElementById('btnCancel').onclick = closeEditor +document.getElementById('btnClose').onclick = closeEditor +document.getElementById('btnSave').onclick = saveEditor +document.getElementById('btnAddTask').onclick = addTaskFromInput +document.getElementById('taskInput').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskFromInput() }) +document.getElementById('btnOpenFolder').onclick = () => { if (editing) runAction(editing.name, 'explorer') } +document.getElementById('btnVsCode').onclick = () => { if (editing) runAction(editing.name, 'vscode') } +document.getElementById('overlay').onclick = () => { closeEditor(); closeBackup(); closeSettings() } +document.getElementById('btnBackup').onclick = () => (backup?.notConfigured ? openSettings(false) : openBackup()) +for (const b of document.querySelectorAll('#taskMode button')) b.onclick = () => setTaskMode(b.dataset.mode) +for (const b of document.querySelectorAll('#boardMode button')) { b.onclick = () => setBoardMode(b.dataset.mode); b.classList.toggle('active', b.dataset.mode === boardMode) } +document.getElementById('taskNewBtn').onclick = addTaskTop +document.getElementById('taskNew').addEventListener('keydown', (e) => { if (e.key === 'Enter') addTaskTop() }) +document.getElementById('btnCloseBackup').onclick = closeBackup +document.getElementById('search').addEventListener('input', (e) => { searchTerm = e.target.value; render() }) +for (const btn of document.querySelectorAll('#tabs button')) btn.onclick = () => { setView(btn.dataset.view); render() } +for (const btn of document.querySelectorAll('#ptabs button')) btn.onclick = () => setSection(btn.dataset.sec) +document.getElementById('fltStatus').addEventListener('change', render) +document.getElementById('fltSort').addEventListener('change', render) +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { if (!rootMenu.hidden) { toggleRootMenu(false); return } closeEditor(); closeBackup(); closeSettings() } + if (e.key === '/' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') { e.preventDefault(); document.getElementById('search').focus() } +}) + +// Deep links: #gallery, #list, #board/ (opens the panel), #list//info +const [hashView, hashProject, hashSec] = decodeURIComponent(location.hash.slice(1)).split('/') +const VIEWS = ['board', 'gallery', 'list', 'tasks'] +initTheme() +if (VIEWS.includes(hashView)) setView(hashView) +else try { const v = localStorage.getItem('dash.view'); if (VIEWS.includes(v)) setView(v) } catch {} +function openFromHash(project, sec) { + const p = project && projects.find((x) => x.name === project) + if (p) { openEditor(p); if (sec) setSection(sec) } +} +load().then(() => { openFromHash(hashProject, hashSec); if (hashView === 'backup') openBackup() }) +loadBackup() +window.addEventListener('hashchange', () => { + const [v, project, sec] = decodeURIComponent(location.hash.slice(1)).split('/') + if (VIEWS.includes(v)) { setView(v); render() } + openFromHash(project, sec) +}) diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..ba1f264 --- /dev/null +++ b/public/index.html @@ -0,0 +1,770 @@ + + + + +Projekte + + + + + +
+
+
+ +
+ +
+ +
+
+
+ + + + +
+ + + + +
+ + + +
+
+
+ +
+ +
+
+
+
+ + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ + + +
+
+ + + +
+
+
+
+
+ +
+ + + + + + + +
+

Projektordner einlesen

+
Übergeordneten Ordner wählen und ankreuzen, was als Projektordner dazukommen soll – der Ordner selbst und/oder seine Unterordner.
+
+ + + +
+
+ + +
+
+
+ + +
+

Neues Projekt

+ + + + + + +
+ + +
Nie kopiert: . Der Klon startet als „Idee“, ohne itch.io-Link und nur mit offenen Aufgaben.
+
+
Legt einen leeren Ordner mit README.md an. Für ein Spiel/eine App aus den Library-Vorlagen: Skill neues-projekt in Claude Code.
+ +
+ + +
+
+
+ +
+ + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..49b5a41 --- /dev/null +++ b/server.js @@ -0,0 +1,618 @@ +// Local project dashboard - scans every folder in ROOT_DIR, reads an +// optional .dashboard.json per project for status/priority/notes/tasks, and +// serves a small Kanban UI to view/edit them. No accounts, no database - +// state lives as a JSON file inside each project folder. +// +// Also shows git/backup status, detected tech, disk usage (via +// _Tools\Cleanup\cleanup.ps1), generator usage and app icons, and can start +// predefined actions in a visible console window. +// +// Security: listens on 127.0.0.1 only, and every request must carry a local +// Host header and (for writes) a local Origin, so other web pages can't drive it. +const express = require('express') +const fs = require('fs') +const path = require('path') +const { pool, openConsole, openDetached, run } = require('./lib/proc') +const { gitInfo, setRemote, initRepo, sshKey } = require('./lib/git') +const tech = require('./lib/tech') +const { toolInfo } = require('./lib/tools') +const icons = require('./lib/icons') +const storage = require('./lib/storage') +const backup = require('./lib/backup') +const settings = require('./lib/settings') +const activity = require('./lib/activity') +const itch = require('./lib/itch') +const create = require('./lib/create') + +// The projects folder comes from the settings (lib/settings.js) and can be +// changed at runtime; '' until it is set up. DASHBOARD_PORT allows a test instance. +let ROOT_DIR = '' +const STATUS_FILE = '.dashboard.json' +const HOST = '127.0.0.1' +const PORT = Number(process.env.DASHBOARD_PORT) || 4848 +const ALLOWED_HOSTS = new Set([`localhost:${PORT}`, `127.0.0.1:${PORT}`]) + +const STATUSES = ['idea', 'active', 'paused', 'done', 'archived'] +const PRIORITIES = ['low', 'medium', 'high'] + +// Thumbnail discovery: every project folder is scanned (shallow, breadth-first) +// for a representative image. A project can override the pick by setting +// "thumbnail": "relative/path.png" in its .dashboard.json. A real app icon +// (lib/icons.js) wins over a generic image. +const IMAGE_EXT = { '.png': 3, '.jpg': 3, '.jpeg': 3, '.webp': 3, '.gif': 2, '.bmp': 2, '.svg': 2, '.ico': 1 } +const SKIP_DIRS = new Set([ + 'node_modules', '.git', '.svn', 'dist', 'build', 'out', 'bin', 'obj', 'target', + 'venv', '.venv', 'env', '__pycache__', '.gradle', '.idea', '.vscode', 'Library', + 'Temp', 'Logs', 'coverage', 'vendor', '.next', '.cache', +]) +const PREFERRED_NAMES = ['icon', 'logo', 'thumb', 'thumbnail', 'preview', 'screenshot', 'cover', 'banner', 'splash', 'title', 'header', 'app_icon', 'appicon'] +const MAX_DEPTH = 3 +const MAX_ENTRIES = 3000 +const THUMB_TTL_MS = 5 * 60 * 1000 +const thumbCache = new Map() // project name -> { file: string|null, at: number } + +function scoreImage(fileName, depth) { + const lower = fileName.toLowerCase() + const ext = path.extname(lower) + const base = path.basename(lower, ext) + let score = IMAGE_EXT[ext] ?? 0 + if (PREFERRED_NAMES.includes(base)) score += 20 + else if (PREFERRED_NAMES.some((n) => base.includes(n))) score += 12 + score += Math.max(0, 6 - depth * 2) // shallower files win + return score +} + +function sanitizeTasks(tasks) { + if (!Array.isArray(tasks)) return [] + return tasks.slice(0, 200).map((t) => ({ + id: String(t?.id ?? Date.now() + Math.random().toString(36).slice(2)), + text: String(t?.text ?? '').slice(0, 500), + done: !!t?.done, + })).filter((t) => t.text.length > 0) +} + +function readStatusFile(projectPath) { + const file = path.join(projectPath, STATUS_FILE) + try { + const raw = fs.readFileSync(file, 'utf-8') + const data = JSON.parse(raw) + return { + status: STATUSES.includes(data.status) ? data.status : 'idea', + priority: PRIORITIES.includes(data.priority) ? data.priority : 'medium', + notes: typeof data.notes === 'string' ? data.notes : '', + tags: Array.isArray(data.tags) ? data.tags.map(String).slice(0, 10) : [], + tasks: sanitizeTasks(data.tasks), + thumbnail: typeof data.thumbnail === 'string' ? data.thumbnail.slice(0, 300) : '', + start: typeof data.start === 'string' ? data.start.slice(0, 300) : '', + program: typeof data.program === 'string' ? data.program.slice(0, 300) : '', + itch: typeof data.itch === 'string' ? data.itch.slice(0, 300) : '', + updatedAt: data.updatedAt ?? null, + } + } catch { + return { status: 'idea', priority: 'medium', notes: '', tags: [], tasks: [], thumbnail: '', start: '', program: '', itch: '', updatedAt: null } + } +} + +// Breadth-first walk of the project folder, returning the best-scoring image +// path (absolute) or null. Bounded by depth and total entries so a huge folder +// can't stall the request. +function scanForImage(projectPath) { + let queue = [{ dir: projectPath, depth: 0 }] + let seen = 0 + let best = null + let bestScore = -1 + while (queue.length) { + const { dir, depth } = queue.shift() + let entries + try { + entries = fs.readdirSync(dir, { withFileTypes: true }) + } catch { + continue + } + for (const e of entries) { + if (++seen > MAX_ENTRIES) return best + if (e.isDirectory()) { + if (depth >= MAX_DEPTH || e.name.startsWith('.') || SKIP_DIRS.has(e.name)) continue + queue.push({ dir: path.join(dir, e.name), depth: depth + 1 }) + continue + } + if (!e.isFile()) continue + const ext = path.extname(e.name).toLowerCase() + if (!(ext in IMAGE_EXT)) continue + const score = scoreImage(e.name, depth) + if (score > bestScore) { + bestScore = score + best = path.join(dir, e.name) + } + } + } + return best +} + +function findThumbnail(name, projectPath) { + const cached = thumbCache.get(name) + if (cached && Date.now() - cached.at < THUMB_TTL_MS) return cached.file + + let file = null + const override = readStatusFile(projectPath).thumbnail + if (override) { + const candidate = path.resolve(projectPath, override) + if (candidate.startsWith(projectPath + path.sep) && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { + file = candidate + } + } + if (!file) file = icons.findIcon(projectPath) + if (!file) file = scanForImage(projectPath) + + thumbCache.set(name, { file, at: Date.now() }) + return file +} + +// Several projects folders can be shown at once (ROOTS). A project is named in +// the API by its key: the folder name, or "Folder (Projects folder)" when the +// same folder name exists in more than one shown projects folder. +let ROOTS = [] // [{ id, name, path }] shown, path resolved +let projMap = new Map() // key -> { key, folder, root } + +// Folders that are never projects (drive roots of a friend's PC may contain these) +const NOT_PROJECTS = new Set(['project-dashboard', '$recycle.bin', 'system volume information', 'recovery', 'config.msi']) + +function projectList() { + const raw = [] + for (const root of ROOTS) { + let entries + try { entries = fs.readdirSync(root.path, { withFileTypes: true }) } catch { continue } + for (const e of entries) { + if (e.isDirectory() && !e.name.startsWith('.') && !NOT_PROJECTS.has(e.name.toLowerCase())) raw.push({ folder: e.name, root }) + } + } + const count = new Map() + for (const p of raw) count.set(p.folder.toLowerCase(), (count.get(p.folder.toLowerCase()) ?? 0) + 1) + const used = new Set() + const list = raw.map((p) => { + let key = count.get(p.folder.toLowerCase()) > 1 ? `${p.folder} (${p.root.name})` : p.folder + while (used.has(key.toLowerCase())) key += ` [${p.root.id}]` + used.add(key.toLowerCase()) + return { key, folder: p.folder, root: p.root } + }) + projMap = new Map(list.map((p) => [p.key, p])) + return list +} + +function projectNames() { return projectList().map((p) => p.key) } + +// key -> { key, folder, root, path } or null +function projectRef(key) { + if (typeof key !== 'string' || !key) return null + const p = projMap.get(key) ?? (projectList(), projMap.get(key)) + return p ? { ...p, path: path.join(p.root.path, p.folder) } : null +} +// key of a project folder (for lib/backup.js) +function keyOf(rootPath, folder) { + for (const p of projMap.values()) if (p.folder === folder && p.root.path.toLowerCase() === rootPath.toLowerCase()) return p.key + return folder +} + +// Resolves a project key to its directory, or null if it isn't an existing +// direct child of a shown projects folder (guards the write/open endpoints +// against path traversal). +function resolveProject(key) { + const p = projectRef(key) + if (!p) return null + if (!fs.existsSync(p.path) || !fs.statSync(p.path).isDirectory() || path.dirname(p.path) !== p.root.path) return null + return p.path +} + +// Applies the current settings: projects folders, backup target, caches. +function applySettings() { + const s = settings.get() + ROOTS = settings.configured() + ? settings.activeRootList(s).map((r) => ({ ...r, path: path.resolve(r.path) })).filter((r) => fs.existsSync(r.path)) + : [] + ROOT_DIR = ROOTS[0]?.path ?? '' + projectList() + storage.init(ROOTS.map((r) => r.path), s.roots.map((r) => r.path)) + backup.init(ROOTS.map((r) => r.path), keyOf) + thumbCache.clear() + quickCache.clear() + icons.clear() + activity.clear() + activity.warm([...projMap.values()].map((p) => path.join(p.root.path, p.folder))) +} + +function storageSummary(p) { + const s = storage.get(p.root.path, p.folder) + if (!s) return null + return { at: s.at, sizeMB: s.sizeMB, deletable: s.deletable } +} + +// target = backup target id whose "last backup" the cards show (default: the first) +async function describeProject(p, target) { + const projectPath = path.join(p.root.path, p.folder) + const stat = fs.statSync(projectPath) + const meta = readStatusFile(projectPath) + const found = tech.detect(projectPath) + const tools = toolInfo(projectPath) + const git = await gitInfo(projectPath) + return { + name: p.key, + folder: p.folder, + root: p.root.id, + rootName: p.root.name, + mtime: stat.mtime.toISOString(), + lastCommit: git.lastCommit, + git, + tech: tech.summary(found), + tools, + hasIcon: !!icons.findIcon(projectPath), + quickStart: quickStartFor(p.key, projectPath), + lastChange: activity.lastChange(projectPath), + lastBackup: backup.lastFor(p.root.path, p.folder, target), + storage: storageSummary(p), + ...meta, + published: itch.forProject(p.folder, meta.itch), + } +} + +async function listProjects(target) { + await itch.ensure() + const list = await pool(projectList(), 8, (p) => describeProject(p, target)) + return list.sort((a, b) => new Date(b.mtime) - new Date(a.mtime)) +} + +// tech.actions matches programs against the folder name; the key names the console windows +function actionsFor(key, projectPath) { + const found = tech.detect(projectPath) + return tech.actions(path.basename(projectPath), projectPath, found, readStatusFile(projectPath), toolInfo(projectPath)) +} + +// The ▶ button on cards: the program chosen in "Aktionen", else own start command, else the main program (exe/html), +// else a start script of the project ("Soundclick starten.bat", run.bat, ...), +// else the first "Starten" action (Unity, npm run dev, Python, ...). +// Finding programs walks the project folder, so the pick is cached a while. +const QUICK_TTL_MS = 3 * 60 * 1000 +const quickCache = new Map() // name -> { value, at } +function quickStartFor(name, projectPath) { + const c = quickCache.get(name) + if (c && Date.now() - c.at < QUICK_TTL_MS) return c.value + let value = null + try { + const list = actionsFor(name, projectPath) + const startScript = (a) => a.group === 'Starten' && a.id.startsWith('bat:') && /(start|run|launch|spiel|play|öffne|open)/i.test(a.label) + const pick = list.find((a) => a.id === 'program') ?? list.find((a) => a.id === 'custom') ?? list.find((a) => a.group === 'Programm') + ?? list.find(startScript) ?? list.find((a) => a.group === 'Starten') + if (pick) value = { id: pick.id, label: pick.label, detail: pick.detail ?? '', kind: pick.kind === 'console' ? 'cmd' : 'exe' } + } catch {} + quickCache.set(name, { value, at: Date.now() }) + return value +} + +// Wraps async handlers so a thrown error becomes a 500 instead of a crash. +const handle = (fn) => async (req, res) => { + try { await fn(req, res) } catch (e) { if (!res.headersSent) res.status(500).json({ error: String(e.message ?? e) }) } +} + +const app = express() + +// Blocks other web pages (CSRF) and DNS rebinding: Host must be local, and +// writes must come from this dashboard's own origin. +app.use((req, res, next) => { + if (!ALLOWED_HOSTS.has(req.headers.host)) return res.status(403).send('forbidden host') + if (req.method !== 'GET' && req.method !== 'HEAD') { + const origin = req.headers.origin + if (!origin || !ALLOWED_HOSTS.has(origin.replace(/^https?:\/\//, ''))) return res.status(403).json({ error: 'forbidden origin' }) + } + next() +}) +app.use(express.json()) +app.use(express.static(path.join(__dirname, 'public'))) + +// Lucide icon sprite (ISC license), used as +const ICON_SPRITE = path.join(__dirname, 'node_modules', 'lucide-static', 'sprite.svg') +app.get('/icons.svg', (req, res) => { + res.setHeader('Cache-Control', 'public, max-age=86400') + res.sendFile(ICON_SPRITE, (err) => { if (err && !res.headersSent) res.status(404).end() }) +}) + +app.get('/api/projects', handle(async (req, res) => { + const list = await listProjects(String(req.query.target ?? '') || null) + const s = settings.get() + res.json({ + root: ROOT_DIR, + rootPaths: ROOTS.map((r) => r.path), + roots: s.roots, + activeRoot: s.activeRoot, + activeRoots: s.activeRoots, + setupNeeded: !ROOT_DIR, + projects: list, + totals: { ...storage.totals(list.map((p) => ({ root: ROOTS.find((r) => r.id === p.root)?.path, folder: p.folder }))), noBackup: list.filter((p) => p.git.level === 'red').length }, + scan: storage.state, + cleanupAvailable: storage.available(), + activityPending: activity.pending(), + }) +})) + +// itch.io profile: games found + which project claims them (lib/itch.js) +async function itchStatus() { + const s = itch.state + const claimed = projectList().map((p) => itch.forProject(p.folder, readStatusFile(path.join(p.root.path, p.folder)).itch)?.url).filter(Boolean) + return { profile: s.profile, at: s.at, error: s.error, games: s.games, unmatched: itch.unmatched(claimed) } +} +app.get('/api/itch', handle(async (req, res) => { await itch.ensure(); res.json(await itchStatus()) })) +app.post('/api/itch/refresh', handle(async (req, res) => { await itch.refresh(); res.json(await itchStatus()) })) + +// Settings: projects folder, backup target, excludes (lib/settings.js) +app.get('/api/settings', (req, res) => { + res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR }) +}) +app.post('/api/settings', (req, res) => { + if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' }) + try { + settings.save(req.body ?? {}) + applySettings() + res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR }) + } catch (e) { + res.status(400).json({ error: String(e.message ?? e) }) + } +}) +// Which registered projects folders are shown (dropdown next to the logo). body: { ids: [...] } or { id } +app.post('/api/roots/active', (req, res) => { + if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' }) + try { + settings.setActive(Array.isArray(req.body?.ids) ? req.body.ids : String(req.body?.id ?? '')) + applySettings() + res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR }) + } catch (e) { + res.status(400).json({ error: String(e.message ?? e) }) + } +}) +// New project (empty) or clone of a project of the active folder (lib/create.js). +// body: { name, root (folder id, default: active), from (project name), withGit, skipBuild } +app.post('/api/projects/new', handle(async (req, res) => { + const s = settings.get() + const b = req.body ?? {} + const root = s.roots.find((r) => r.id === (b.root || s.activeRoot)) + if (!root || !fs.existsSync(root.path)) return res.status(400).json({ error: 'Projektordner nicht gefunden.' }) + let from = null + if (b.from) { + from = resolveProject(String(b.from)) + if (!from) return res.status(404).json({ error: 'Vorlage nicht gefunden.' }) + } + try { + const r = await create.create({ rootPath: path.resolve(root.path), name: b.name, from, withGit: !!b.withGit, skipBuild: b.skipBuild !== false }) + const shown = ROOTS.some((x) => x.id === root.id) + if (shown) { activity.warm([r.path]); projectList() } + // key: the name the UI knows it by (may get "(Ordner)" when the name exists in another shown folder) + res.json({ ...r, root: root.id, shown, key: shown ? keyOf(path.resolve(root.path), r.name) : r.name }) + } catch (e) { + res.status(400).json({ error: String(e.message ?? e) }) + } +})) +// Adds projects folders from the dropdown. body: { paths: [...], activate } +app.post('/api/roots/add', (req, res) => { + if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' }) + try { + const before = settings.get().activeRoots.join('|') + const { settings: s, added } = settings.addRoots(req.body?.paths, !!req.body?.activate) + if (s.activeRoots.join('|') !== before) applySettings() + res.json({ ...s, added, configured: !!ROOT_DIR, dataDir: settings.DATA_DIR }) + } catch (e) { + res.status(400).json({ error: String(e.message ?? e) }) + } +}) +// Subfolders of a folder, for adding several projects folders at once +app.get('/api/subfolders', (req, res) => { + try { res.json(settings.subfolders(String(req.query.path ?? ''))) } catch (e) { res.status(400).json({ error: String(e.message ?? e) }) } +}) + +app.patch('/api/projects/:name', (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + const current = readStatusFile(projectPath) + const { status, priority, notes, tags, tasks, thumbnail, start, program, itch: itchLink } = req.body ?? {} + // itch: '' = automatic, '-' = not published, otherwise the game's page + let nextItch = current.itch + if (typeof itchLink === 'string') { + const v = itchLink.trim() + if (v && v !== '-' && !/^https:\/\/[a-z0-9-]+\.itch\.io\/[^\s"<>]+$/i.test(v)) return res.status(400).json({ error: 'itch.io-Link: z. B. https://name.itch.io/spiel – oder „-“ für „nicht veröffentlicht“' }) + nextItch = v.slice(0, 300) + } + // program: absolute path (file dialog) or relative; stored relative, must lie inside the project + let nextProgram = current.program + if (typeof program === 'string') { + const p = program.trim().replace(/^"|"$/g, '') + if (!p) nextProgram = '' + else { + const abs = path.resolve(projectPath, p) + if (!abs.startsWith(projectPath + path.sep)) return res.status(400).json({ error: 'Die Datei muss im Projektordner liegen.' }) + if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return res.status(400).json({ error: `Datei nicht gefunden: ${p}` }) + nextProgram = path.relative(projectPath, abs).slice(0, 300) + } + } + const next = { + status: STATUSES.includes(status) ? status : current.status, + priority: PRIORITIES.includes(priority) ? priority : current.priority, + notes: typeof notes === 'string' ? notes : current.notes, + tags: Array.isArray(tags) ? tags.map(String).slice(0, 10) : current.tags, + tasks: tasks !== undefined ? sanitizeTasks(tasks) : current.tasks, + thumbnail: typeof thumbnail === 'string' ? thumbnail.slice(0, 300) : current.thumbnail, + start: typeof start === 'string' ? start.replace(/[\r\n]+/g, ' ').slice(0, 300) : current.start, + program: nextProgram, + itch: nextItch, + updatedAt: new Date().toISOString(), + } + fs.writeFileSync(path.join(projectPath, STATUS_FILE), JSON.stringify(next, null, 2)) + thumbCache.delete(req.params.name) + icons.forget(projectPath) + quickCache.delete(req.params.name) + res.json(next) +}) + +// Serves the project's thumbnail image; 404 when the folder has no usable +// image (the UI then falls back to a generated letter tile). +app.get('/api/projects/:name/thumb', (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).end() + const file = findThumbnail(req.params.name, projectPath) + if (!file) return res.status(404).end() + res.setHeader('Cache-Control', 'public, max-age=300') + res.sendFile(file, (err) => { if (err && !res.headersSent) res.status(404).end() }) +}) + +// The program chosen for ▶ ({ rel, missing }) or null. +function programInfo(projectPath) { + const rel = readStatusFile(projectPath).program + if (!rel) return null + const r = tech.resolveProgram(projectPath, rel) + return { rel, missing: !r?.exists } +} + +// Everything the editor's Info/Aktionen tabs need. +app.get('/api/projects/:name/details', handle(async (req, res) => { + const name = req.params.name + const projectPath = resolveProject(name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + const icon = icons.findIcon(projectPath) + const p = projectRef(name) + res.json({ + git: await gitInfo(projectPath), + tech: tech.summary(tech.detect(projectPath)), + tools: toolInfo(projectPath), + icon: icon ? path.relative(projectPath, icon) : null, + storage: storage.get(p.root.path, p.folder), + lastBackup: backup.lastFor(p.root.path, p.folder, String(req.query.target ?? '') || null), + backupTargets: backup.lastOnAllTargets(p.root.path, p.folder), + actions: actionsFor(name, projectPath).map(({ id, label, group, detail, rel }) => ({ id, label, group, detail, rel })), + program: programInfo(projectPath), + path: projectPath, + sshKey: sshKey(), + }) +})) + +// Opens the project folder in Windows Explorer. +app.post('/api/projects/:name/open', (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + try { + openDetached('explorer.exe', [projectPath]) + res.json({ ok: true }) + } catch (e) { + res.status(500).json({ error: String(e) }) + } +}) + +// Runs one of the server-built actions; the body only names its id. +app.post('/api/projects/:name/run', handle(async (req, res) => { + const name = req.params.name + const projectPath = resolveProject(name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + const action = actionsFor(name, projectPath).find((a) => a.id === req.body?.id) + if (!action) return res.status(400).json({ error: 'unknown action' }) + const target = action.kind === 'exe' ? action.exe : action.kind === 'open' ? action.file : null + if (target && !fs.existsSync(target)) { + quickCache.delete(name) + return res.status(400).json({ error: `Nicht gefunden: ${path.relative(projectPath, target) || target}` }) + } + switch (action.kind) { + case 'console': openConsole(`${name} ${action.id}`, action.cwd, action.command, { raw: action.id === 'custom' }); break + case 'exe': openDetached(action.exe, action.args, action.cwd); break + case 'open': openDetached('explorer.exe', [action.file]); break + case 'vscode': { + // code is a .cmd shim, so go through cmd; the path was checked by resolveProject + const r = await run('cmd.exe', ['/c', 'code', projectPath], { timeout: 15000 }) + if (!r.ok) return res.status(500).json({ error: 'VS Code (code) nicht gefunden' }) + break + } + } + res.json({ ok: true, label: action.label }) +})) + +// git push in a visible console, so SSH/credential prompts and errors are seen. +// body.message: commit all changes with this message first ("Commit & Push"). +app.post('/api/projects/:name/push', handle(async (req, res) => { + const name = req.params.name + const projectPath = resolveProject(name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + const git = await gitInfo(projectPath) + if (!git.remote) return res.status(400).json({ error: 'kein Remote eingerichtet' }) + if (!/^[\w./-]+$/.test(git.branch)) return res.status(400).json({ error: `Branch-Name nicht unterstützt: ${git.branch || '(keiner)'}` }) + const steps = [] + if (typeof req.body?.message === 'string' && req.body.message.trim()) { + // the message sits in "..." in a .cmd file: no quotes, no line breaks + const msg = req.body.message.replace(/["\r\n]+/g, ' ').trim().slice(0, 200) + steps.push('git add -A', `git commit -m "${msg}"`) + } + steps.push(git.upstream ? 'git push' : `git push -u origin ${git.branch}`) + openConsole(`${name} push`, projectPath, steps.join(' && ')) + res.json({ ok: true }) +})) + +// Sets the "origin" remote (SSH or https URL; '' removes it). +app.post('/api/projects/:name/remote', handle(async (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + try { await setRemote(projectPath, req.body?.url) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) } + res.json({ ok: true, git: await gitInfo(projectPath) }) +})) + +// git init for a project without repository. +app.post('/api/projects/:name/git-init', handle(async (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + try { await initRepo(projectPath) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) } + res.json({ ok: true, git: await gitInfo(projectPath) }) +})) + +// Background disk scan: one project ({name}) or all (empty body). +app.post('/api/scan', (req, res) => { + if (!storage.available()) return res.status(400).json({ error: 'cleanup.ps1 nicht gefunden' }) + const name = req.body?.name + const refs = name ? [name].filter((n) => resolveProject(n)).map(projectRef) : projectList().filter((p) => p.folder !== '_Tools') + if (!refs.length) return res.status(404).json({ error: 'unknown project' }) + if (!storage.startScan(refs.map((p) => ({ root: p.root.path, folder: p.folder, key: p.key })))) return res.status(409).json({ error: 'Scan läuft schon' }) + res.json({ ok: true, state: storage.state }) +}) + +app.get('/api/scan', (req, res) => res.json(storage.state)) + +// Deletes selected cleanup candidates of one project (cleanup.ps1 re-checks them). +app.post('/api/projects/:name/clean', handle(async (req, res) => { + const ref = resolveProject(req.params.name) && projectRef(req.params.name) + if (!ref) return res.status(404).json({ error: 'unknown project' }) + if (ref.folder === '_Tools') return res.status(400).json({ error: '_Tools wird nie aufgeräumt' }) + // paths are relative to the projects folder, as cleanup.ps1 listed them ("\...") + const paths = (Array.isArray(req.body?.paths) ? req.body.paths : []) + .filter((p) => typeof p === 'string' && p.startsWith(ref.folder + path.sep)) + if (!paths.length) return res.status(400).json({ error: 'nichts ausgewählt' }) + const result = await storage.clean(ref.root.path, ref.folder, paths) + res.json(result) +})) + +// NAS backup (lib/backup.js): check → copy, never deletes in the backup. +app.get('/api/backup', (req, res) => res.json(backup.getState())) +// body: { target } = check everything · { target, project, autoCopy: true } = "Sichern" of one project +app.post('/api/backup/check', handle(async (req, res) => { + const project = req.body?.project ?? null + const ref = project && resolveProject(project) ? projectRef(project) : null + if (project && (!ref || ref.folder === '_Tools')) return res.status(404).json({ error: 'unknown project' }) + const target = String(req.body?.target ?? '') || null + if (target && !settings.get().backup.targets.some((t) => t.id === target)) return res.status(404).json({ error: 'Backup-Ziel nicht gefunden' }) + if (!ROOTS.length) return res.status(400).json({ error: 'Kein Projektordner gewählt' }) + if (!backup.check(ref ? { root: ref.root.path, folder: ref.folder } : null, !!req.body?.autoCopy, target)) return res.status(409).json({ error: 'Es läuft schon ein Backup' }) + res.json(backup.getState()) +})) +app.post('/api/backup/copy', handle(async (req, res) => { + if (!backup.copy()) return res.status(409).json({ error: 'Erst prüfen (oder läuft schon)' }) + res.json(backup.getState()) +})) +app.post('/api/backup/cancel', (req, res) => { + backup.cancel() + res.json(backup.getState()) +}) + +applySettings() + +app.listen(PORT, HOST, () => { + console.log(`Project dashboard running at http://${HOST}:${PORT}`) + console.log(`Scanning: ${ROOT_DIR}`) +}) diff --git a/start-dashboard.bat b/start-dashboard.bat new file mode 100644 index 0000000..5d13e19 --- /dev/null +++ b/start-dashboard.bat @@ -0,0 +1,9 @@ +@echo off +cd /d "%~dp0" +if not exist "node_modules" ( + echo node_modules fehlt - installiere einmalig ... + call npm install +) +start "Project Dashboard" cmd /k "npm start" +timeout /t 2 /nobreak >nul +start "" http://127.0.0.1:4848