diff --git a/.dashboard.json b/.dashboard.json new file mode 100644 index 0000000..da291ea --- /dev/null +++ b/.dashboard.json @@ -0,0 +1,12 @@ +{ + "status": "idea", + "priority": "medium", + "notes": "", + "tags": [], + "tasks": [], + "thumbnail": "", + "start": "", + "program": "", + "itch": "", + "updatedAt": "2026-11-12T08:32:33.379Z" +} \ No newline at end of file diff --git a/README.md b/README.md index 5763645..af1e609 100644 --- a/README.md +++ b/README.md @@ -1,201 +1,208 @@ -# Project Dashboard +# Projekt-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. +Ein Übersichts-Board für alle deine Projektordner unter Windows – Spiele, Apps, Bastelprojekte. +Jeder Unterordner ist ein Projekt. Du siehst auf einen Blick, woran du arbeitest, was ungesichert ist, +wie viel Platz es belegt, und startest es mit einem Klick. -Liegt als Werkzeug in `_Tools\ProjectDashboard` und verwaltet die Ordner zwei Ebenen höher -(`D:\Oculusquest\Projekt`; anders per Umgebungsvariable `DASHBOARD_ROOT`). +- **Alles bleibt auf deinem PC.** Kein Konto, keine Cloud. Status, Notizen und Aufgaben landen als kleine + Datei `.dashboard.json` im jeweiligen Projektordner. +- **Eine Datei, nichts zu installieren.** `ProjectDashboard.exe` bringt alles mit, was sie braucht. -## 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). +## Installieren und starten -**Im Browser:** `start-dashboard.bat` doppelklicken oder `npm install` + `npm start`, -dann http://127.0.0.1:4848 – der Server ist **nur lokal** erreichbar. +**Voraussetzung:** Windows 10 oder 11. Die „Microsoft Edge WebView2 Runtime“ ist bei Windows 11 immer dabei – +fehlt sie, zeigt das Programm einen Link zum Download. -**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). +1. `ProjectDashboard.exe` in einen beliebigen Ordner legen (z. B. `Dokumente\Programme`) und doppelklicken. +2. Meldet Windows **„Der Computer wurde durch Windows geschützt“**: auf **Weitere Informationen → Trotzdem ausführen** + klicken. Das kommt, weil die Datei nicht signiert ist. +3. Beim ersten Start richtet sich das Programm kurz ein und zeigt dann **Einrichten**: + - **Projektordner** wählen – den Ordner, in dem deine Projekte liegen (Pflicht). + - Optional ein **Backup-Ziel** (externe Platte, NAS, anderes Laufwerk) – geht auch später. -**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. +Fertig. Eine Verknüpfung auf dem Desktop legst du wie bei jedem Programm an (Rechtsklick auf die exe → +„Senden an“ → „Desktop“). -**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. +**Optional, aber praktisch:** [Git](https://git-scm.com) (für Git-Status und Push) und +[VS Code](https://code.visualstudio.com). Fehlt etwas davon, fehlen nur die passenden Anzeigen und Knöpfe. -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. +## Was du damit machen kannst -**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. +### Überblick +- **Board** mit Spalten *Idee · Aktiv · Pausiert · Fertig · Archiviert* – Karten per Drag & Drop verschieben. + Umschalter *Karten | Liste* für eine kompakte Zeilen-Ansicht. +- **Galerie** mit Vorschaubildern (das App-Icon oder ein Bild aus dem Projekt wird automatisch gefunden). +- **Liste** als Tabelle, Spaltenkopf klicken = sortieren. +- **Aufgaben** aller Projekte an einem Ort: abhaken, neue eintragen. +- **Suche** (Taste `/`) über Namen, Notizen und Tags, dazu Schnellfilter wie *Ohne Remote*, *Ungesichert*, *Aufräumbar*. +- **Hell / System / Dunkel** oben rechts. -Zweite Instanz zum Testen: `DASHBOARD_PORT=4849` setzen (gilt für exe und Server). +### Auf jeder Karte +- **📂 Explorer · `` VS Code · ▶ Starten** als Knöpfe. + ▶ startet automatisch das Passende: das eigene Programm (exe), eine HTML-Seite, ein Start-Skript, + Unity, `npm run dev`, Python … Was ▶ genau startet, legst du im Projekt unter **Aktionen** fest (📌). +- **Git-Ampel:** rot = kein Git oder kein Remote (liegt nur auf dieser Platte), gelb = ungesicherte + Änderungen, grün = alles gepusht. +- **Backup-Stand**, **Größe**, erkannte **Technik** (Unity, Node, .NET, Flutter, Android, Python …). -## Ansichten & Bedienung +### Projekt-Panel (Klick auf ein Projekt) +- **Bearbeiten:** Status, Priorität, Tags, Notizen, Aufgaben, eigener Start-Befehl, Vorschaubild. +- **Info:** Git-Details. Remote eintragen (SSH wie `git@github.com:name/projekt.git` oder https), + **Git einrichten** für Projekte ohne Repository, **Push** bzw. **Commit & Push** mit Nachricht. + Push läuft in einem sichtbaren Konsolenfenster (dort erscheinen Passwort-/SSH-Abfragen und Fehler). + Dein öffentlicher SSH-Schlüssel lässt sich mit einem Klick kopieren. +- **Speicher:** Projekt scannen, Größe sehen und Caches/Build-Ordner gezielt löschen. Ordner mit Dateien, + die in Git sind, werden nie angeboten. +- **Aktionen:** alle erkannten Programme und Befehle (npm, dotnet, flutter, Gradle, Unity, Python …), + jeweils in einem eigenen Konsolenfenster. +- **Klonen** und **Umbenennen…** (auch in einen anderen Projektordner verschieben). -- **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`. +### Neues Projekt +Knopf **Neu** oben: leeres Projekt (Ordner mit `README.md`) oder Klon eines vorhandenen. Ein Klon lässt +`node_modules`, Caches und – abwählbar – Build-Ordner weg; den Git-Verlauf nur auf Wunsch. -## Backup auf die MyCloud +### Mehrere Projektordner +Oben links neben dem Logo ist ein Auswahlmenü: +- **Klick auf einen Namen** zeigt nur diesen Ordner, **Häkchen** zeigen mehrere gleichzeitig. +- **Ordner hinzufügen…** bzw. **Mehrere Ordner einlesen…** (übergeordneten Ordner wählen, Unterordner ankreuzen). -Knopf **Backup** oben (zeigt „vor … Tagen“, gelb wenn älter als 7 Tage oder noch nie): +Sind mehrere Ordner sichtbar, steht auf jeder Karte, aus welchem sie stammt. -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. +### Backup +Knopf **Backup** oben: +1. **Prüfen, was neu ist** – zeigt neue und geänderte Dateien pro Projekt. +2. **Jetzt kopieren** – mit Fortschritt, jederzeit 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. +Einzelne Projekte sicherst du im Projekt unter **Aktionen → Jetzt sichern**. -**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** – es kommt nur dazu. +- Nicht gesichert werden Ordner, die sich neu erzeugen lassen (`node_modules`, `.venv`, `__pycache__` …). + Die Liste ist in den Einstellungen änderbar. +- Mehrere Ziele (z. B. NAS **und** USB-Platte) sind möglich, jedes mit eigenem Stand. +- Bei mehreren Projektordnern landet der erste direkt im Ziel, jeder weitere in einem Unterordner mit seinem Namen. -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). +**Automatisch sichern:** Einstellungen → Backup → „Automatisch sichern“: *Aus · Bei jedem Start · Stündlich · +Täglich (Uhrzeit) · Wöchentlich (Tag + Uhrzeit)*, auf ein Ziel oder alle nacheinander. Gesichert werden **alle** +Projektordner, auch die gerade nicht angezeigten. Das läuft nur, solange das Dashboard geöffnet ist. Ein verpasster +Termin (PC aus) wird beim nächsten Öffnen nachgeholt; Termine vor dem Einschalten zählen nicht als verpasst. Ist das +Ziel nicht erreichbar (NAS aus, USB-Platte fehlt), folgt nach 30 Minuten ein neuer Versuch. Die Einstellungen zeigen +den nächsten Termin und das letzte Ergebnis, der Backup-Knopf zeigt „auto …“, solange es läuft. -## Projektverwaltung (Karten, Galerie, Editor) +**Backup-Erinnerung:** Ein Projekt gilt als **„Backup fällig“**, wenn es seit dem letzten Backup geändert wurde +und dieses älter als 7 Tage ist (einstellbar unter Einstellungen → Backup). Dafür gibt es einen eigenen Filter, +der Backup-Knopf zeigt die Anzahl, und einmal am Tag erscheint ein Hinweis. -Jede Karte/Kachel zeigt zusätzlich: +### Speicher (eigene Seite) +Reiter **Speicher** oben: Wer belegt wie viel Platz? +- **Kennzahlen:** belegt gesamt, aufräumbar (Cache · Builds · Rohbilder), wie viele Projekte gemessen sind, **Alle messen**. +- **Treemap:** jedes Projekt als Fläche nach Größe, der farbige Streifen unten zeigt den aufräumbaren Anteil. + Klick auf ein Projekt zeigt seine Ordner, ein weiterer Klick die Unterordner der großen Ordner. + Farben: orange = Cache, blau = fertige Builds, grün = Rohbilder, grau = der Rest. +- **Größte Projekte** als Balkenliste und **Größte Speicherfresser**: die größten Ordner über alle Projekte, die sich + neu erzeugen lassen – ankreuzen und **Ausgewählte löschen**. Cache ist vorausgewählt; Ordner mit Dateien, + die in Git sind, werden nie angeboten. -- **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“. +Größen misst das Dashboard selbst. Was gelöscht werden darf, entscheidet `cleanup.ps1`; fehlt es, gibt es nur die Größen. -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. +### Aktivität +Reiter **Aktivität**: ein Kalender über das letzte Jahr. Je dunkler ein Tag ist, desto mehr Projekte wurden an +diesem Tag bearbeitet. Gezählt werden geänderte Dateien (nach ihrer *letzten* Änderung) und Git-Commits. +Klick auf einen Tag zeigt, woran gearbeitet wurde. Dazu kommen aktive Tage, die aktuelle und die längste Serie +und „Zuletzt aktiv“ (7 / 30 / 90 Tage). Im Projekt unter **Info** steht dieselbe Ansicht für ein halbes Jahr. -Editor-Reiter: +### Release archivieren (ZIP) +Im Projekt unter **Info → Release archivieren**: einen Build-Ordner (`dist`, `builds`, `release`, `publish`, +`bin\Release` …) oder das ganze Projekt als ZIP mit Datum im Namen nach `\releases\` packen. Beim ganzen +Projekt bleiben `node_modules`, Build-Ordner, `.git` und `releases` draußen. Optional wird ein fertiger Build-Ordner +danach gelöscht, um Platz zu sparen – das ZIP bleibt. -- **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`). +### itch.io (optional) +Trägst du in den Einstellungen dein öffentliches itch.io-Profil ein (`https://name.itch.io`), erkennt das +Dashboard, welche Projekte veröffentlicht sind (🚀), und zeigt itch-Spiele, die noch keinem Projekt zugeordnet sind. -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`. +## Einstellungen -## Tabs +Zahnrad oben rechts, mit den Reitern **Projektordner · Backup · itch.io · Allgemein**. +Änderungen gelten erst nach **Speichern** (oder `Strg+S`). -Oben zwischen **Board** (Kanban) und **Galerie** (Thumbnail-Kacheln) umschalten. +## Wo liegen meine Daten? -### Galerie +| Was | Wo | +|---|---| +| Status, Notizen, Aufgaben eines Projekts | `.dashboard.json` im Projektordner | +| Einstellungen, Scan- und Backup-Stand | `%LOCALAPPDATA%\ProjectDashboard\data\` | +| Fenstergröße, Protokoll (`server.log`) | `%LOCALAPPDATA%\ProjectDashboard\` | +| Das entpackte Programm | `%LOCALAPPDATA%\ProjectDashboard\app\` | -- 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. +Im Reiter **Allgemein** der Einstellungen öffnet **Datenordner öffnen** den Ordner direkt. -## Wie es funktioniert +**Neue Version:** einfach die neue `ProjectDashboard.exe` über die alte kopieren. Einstellungen und Daten bleiben. -- 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. +**Entfernen:** die exe löschen und den Ordner `%LOCALAPPDATA%\ProjectDashboard` löschen. +Die `.dashboard.json`-Dateien in den Projektordnern stören nicht, du kannst sie aber ebenfalls löschen. -## Bekannte Einschränkung +## Sicherheit -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. +Das Dashboard läuft als kleiner Server **nur auf deinem PC** (`127.0.0.1:4848`), ist aus dem Netzwerk nicht +erreichbar und lehnt Anfragen anderer Webseiten ab. Es schickt nichts ins Internet – außer, wenn du ein +itch.io-Profil einträgst: dann wird diese öffentliche Seite gelesen. -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. +## Probleme? + +- **Fenster bleibt leer / „Server antwortet nicht“:** Läuft das Dashboard schon in einem zweiten Fenster? Sonst + ist evtl. Port 4848 belegt. Details stehen in `%LOCALAPPDATA%\ProjectDashboard\server.log`. +- **Oben erscheint „Neu starten“:** das Programm wurde aktualisiert – Knopf klicken, das Fenster bleibt offen. +- **Umbenennen klappt nicht („Ordner ist in Benutzung“):** VS Code, Konsolen oder das laufende Programm aus dem + Projekt schließen, dann nochmal. +- **Git-Anzeigen fehlen:** Git ist nicht installiert oder nicht im PATH. + +--- + +## Für Entwickler + +Node.js-Server (`server.js`, Express) + Oberfläche (`public/`) + kleines Windows-Fenster mit WebView2 (`launcher/`, C#/.NET 8). + +**Aus dem Quellcode starten:** `npm install`, dann `npm start` (oder `start-dashboard.bat`) und +http://127.0.0.1:4848 öffnen – oder `build.ps1` (siehe unten) für das Fenster. + +**Bauen** (braucht das .NET SDK 8+ und Node.js): +- `powershell -ExecutionPolicy Bypass -File build.ps1` → kleine `ProjectDashboard.exe` neben `server.js`, + nutzt das installierte Node.js und die .NET 8 Desktop Runtime. +- `powershell -ExecutionPolicy Bypass -File build.ps1 -Release` → `release\ProjectDashboard.exe` (~100 MB) zum + Weitergeben: .NET, `node.exe` und alle Dateien sind drin. `cleanup.ps1` (für Scan/Aufräumen) wird aus + `..\Cleanup\` oder `..\_Tools\Cleanup\` mitgepackt. +- Icon: `launcher\make-icon.ps1`, dann `launcher\app.ico` löschen und neu bauen. + +Änderungen an `server.js`, `lib\` oder `public\` brauchen keinen Neubau: Der Server läuft als Worker unter +`lib\supervisor.js`, das Dashboard meldet geänderten Code und startet per **Neu starten** neu. + +**Umgebungsvariablen:** +`DASHBOARD_PORT` (zweite Instanz, z. B. 4849) · `DASHBOARD_DATA` (Datenordner) · +`DASHBOARD_ROOT` (fester Projektordner, für Tests). +Liegt das Dashboard in `\_Tools\ProjectDashboard`, wird `` automatisch vorgeschlagen und +`_Tools\Backup\backup-config.json` mitgepflegt (für ein eigenes `backup-projekte.bat`). + +**Aufbau:** +| Datei | Aufgabe | +|---|---| +| `server.js` | Routen, Projektliste über mehrere Projektordner | +| `lib\settings.js` | Einstellungen, Projektordner, Backup-Ziele | +| `lib\backup.js` | Backup mit robocopy (prüfen → kopieren, nie löschen) | +| `lib\storage.js` | Größen-Scan mit Ordner-Aufteilung (Treemap) und Aufräumen über `cleanup.ps1` | +| `lib\scheduler.js` | Automatisches Backup nach Zeitplan (Stand in `auto-backup.json` im Datenordner) | +| `lib\archive.js` | Release-ZIP nach `\releases` (über `tar.exe` von Windows) | +| `lib\create.js` | Neu, Klonen, Umbenennen/Verschieben | +| `lib\git.js` · `lib\tech.js` · `lib\icons.js` | Git-Status, Technik-Erkennung + Aktionen, App-Icons | +| `lib\itch.js` · `lib\activity.js` | itch.io-Profil, „zuletzt geändert“ und Aktivität pro Tag | +| `lib\proc.js` · `lib\supervisor.js` | Prozesse/Konsolen, Neustart | + +Direktlinks: `#gallery`, `#list`, `#tasks`, `#activity`, `#storage`, `#board//info`. Darstellung per Link: `?theme=light` / `?theme=dark`. + +Icons: [Lucide](https://lucide.dev) (ISC-Lizenz). Die Release-exe enthält Node.js (MIT) und Express (MIT), +siehe `THIRD-PARTY.txt` im entpackten Programmordner. diff --git a/build.ps1 b/build.ps1 index 9a19037..3caa80e 100644 --- a/build.ps1 +++ b/build.ps1 @@ -47,9 +47,14 @@ 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') +# dashboard inside _Tools (..\Cleanup) or next to it (..\_Tools\Cleanup); without it the +# shipped exe measures sizes but offers nothing to delete +$parent = Split-Path $here -Parent +$cleanup = @((Join-Path $parent 'Cleanup\cleanup.ps1'), (Join-Path $parent '_Tools\Cleanup\cleanup.ps1')) | Where-Object { Test-Path $_ } | Select-Object -First 1 +if ($cleanup) { + New-Item -ItemType Directory (Join-Path $payload 'tools') | Out-Null + Copy-Item $cleanup (Join-Path $payload 'tools\cleanup.ps1') +} else { Write-Warning 'cleanup.ps1 nicht gefunden - die exe misst Groessen, bietet aber nichts zum Aufraeumen an.' } # node.exe of this PC (MIT license, copied alongside) $nodeExe = (Get-Command node -ErrorAction Stop).Source diff --git a/lib/activity.js b/lib/activity.js index 7acf089..0b6bb58 100644 --- a/lib/activity.js +++ b/lib/activity.js @@ -5,17 +5,27 @@ 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 SKIP = /^(node_modules|\.git|\.gradle|\.gradle-local|Library|Temp|Logs|obj|bin|build|builds|dist|out|release|releases|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 } +// local calendar day "YYYY-MM-DD" (the heatmap shows the user's days, not UTC) +const dayOf = (ms) => { + const d = new Date(ms) + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +} +const YEAR_MS = 371 * 86400000 + function scan(projectPath) { let best = 0 let bestFile = '' let seen = 0 + // files changed per day within the last year (each file counts on the day of its last change) + const days = {} + const since = Date.now() - YEAR_MS const stack = [{ dir: projectPath, depth: 0 }] while (stack.length) { const { dir, depth } = stack.pop() @@ -30,15 +40,37 @@ function scan(projectPath) { let m = 0 try { m = fs.statSync(full).mtimeMs } catch { continue } if (m > best) { best = m; bestFile = full } + if (m >= since && m <= Date.now() + 86400000) { const k = dayOf(m); days[k] = (days[k] ?? 0) + 1 } } } } return finish() function finish() { - return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES } : null + return best ? { at: new Date(best).toISOString(), file: path.relative(projectPath, bestFile), partial: seen > MAX_ENTRIES, days } : null } } +// Commits per day of the last year (git log), cached like the scan. +const { run } = require('./proc') +const gitCache = new Map() // projectPath -> { value, at } +async function gitDays(projectPath) { + const c = gitCache.get(projectPath) + if (c && Date.now() - c.at < TTL_MS) return c.value + let value = {} + if (fs.existsSync(path.join(projectPath, '.git'))) { + const r = await run('git', ['-C', projectPath, 'log', '--since=1.year.ago', '--format=%ad', '--date=short-local'], { timeout: 15000 }) + for (const line of r.stdout.split(/\r?\n/)) { const k = line.trim(); if (/^\d{4}-\d{2}-\d{2}$/.test(k)) value[k] = (value[k] ?? 0) + 1 } + } + gitCache.set(projectPath, { value, at: Date.now() }) + return value +} + +// Files changed per day (undefined while the background scan hasn't reached the project). +function filesPerDay(projectPath) { + const v = lastChange(projectPath) + return v === undefined ? undefined : v?.days ?? {} +} + // 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 = [] @@ -71,6 +103,6 @@ function lastChange(projectPath) { 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() } +function clear() { cache.clear(); gitCache.clear(); queue.length = 0; queued.clear() } -module.exports = { lastChange, warm, pending, forget, clear } +module.exports = { lastChange, warm, pending, forget, clear, gitDays, filesPerDay, dayOf } diff --git a/lib/archive.js b/lib/archive.js new file mode 100644 index 0000000..aabe64d --- /dev/null +++ b/lib/archive.js @@ -0,0 +1,120 @@ +// Release archive: packs a build folder (dist, builds, release, publish …) or the +// whole project as a ZIP into \releases\, so a version is kept even +// after the build folder was cleaned up. Uses tar.exe (bsdtar, part of +// Windows 10/11), which writes real ZIP files with -a and an .zip name. +const fs = require('fs') +const path = require('path') +const { run } = require('./proc') +const settings = require('./settings') + +const ARCHIVE_DIR = 'releases' +const RELEASE_NAMES = /^(dist|builds?|release|releases?|publish|out)$/i +const SKIP_WALK = /^(node_modules|\.git|\.gradle|library|temp|logs|obj|__pycache__|\.venv.*|venv)$/i +// left out of a whole-project archive (on top of the backup excludes) +const PROJECT_SKIP = ['.git', ARCHIVE_DIR, 'dist', 'build', 'builds', 'out', 'bin', 'obj', 'Library', 'Temp', 'Logs', '.gradle', '.next', 'coverage', '.cache'] + +function dirInfo(dir, limit = 20000) { + let bytes = 0, files = 0 + const stack = [dir] + while (stack.length && files < limit) { + const cur = stack.pop() + let entries + try { entries = fs.readdirSync(cur, { withFileTypes: true }) } catch { continue } + for (const e of entries) { + const full = path.join(cur, e.name) + if (e.isDirectory()) stack.push(full) + else if (e.isFile()) { files++; try { bytes += fs.statSync(full).size } catch {} } + } + } + return { bytes, files } +} + +// Build folders worth archiving (two levels deep, with files in them). +// -> [{ rel, mb, files }] +function findReleaseDirs(projectPath) { + const out = [] + const walk = (dir, depth) => { + let entries + try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return } + for (const e of entries) { + if (!e.isDirectory() || e.name.startsWith('.')) continue + const full = path.join(dir, e.name) + const rel = path.relative(projectPath, full) + if (e.name.toLowerCase() === ARCHIVE_DIR && depth === 0) continue + // bin\Release of .NET projects + const isBinRelease = /^release$/i.test(e.name) && /^bin$/i.test(path.basename(dir)) + if (RELEASE_NAMES.test(e.name) || isBinRelease) { + const info = dirInfo(full) + if (info.files) out.push({ rel, mb: Math.round((info.bytes / 1048576) * 10) / 10, files: info.files }) + continue + } + if (depth < 2 && !SKIP_WALK.test(e.name)) walk(full, depth + 1) + } + } + walk(projectPath, 0) + return out.sort((a, b) => b.mb - a.mb).slice(0, 12) +} + +// Existing archives in \releases (newest first). +function listArchives(projectPath) { + const dir = path.join(projectPath, ARCHIVE_DIR) + let entries = [] + try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return [] } + return entries.filter((e) => e.isFile() && /\.zip$/i.test(e.name)).map((e) => { + const st = fs.statSync(path.join(dir, e.name)) + return { name: e.name, mb: Math.round((st.size / 1048576) * 10) / 10, at: st.mtime.toISOString() } + }).sort((a, b) => (a.at < b.at ? 1 : -1)) +} + +const stamp = () => { + const d = new Date() + const p = (n) => String(n).padStart(2, '0') + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}` +} +const safe = (s) => s.replace(/[\\/:*?"<>|\s]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') + +let running = false + +// what: a relative folder from findReleaseDirs, or 'project'. -> { name, mb, path } +async function zip(projectPath, what) { + if (running) throw new Error('Es wird gerade schon ein Archiv erstellt.') + const project = path.basename(projectPath) + let base, items, excludes = [] + if (what === 'project') { + base = projectPath + items = ['.'] + const b = settings.get().backup + excludes = [...new Set([...b.excludeDirs, ...PROJECT_SKIP])].map((x) => `--exclude=${x}`) + excludes.push(...b.excludeFiles.map((x) => `--exclude=${x}`)) + } else { + const src = path.resolve(projectPath, String(what ?? '')) + if (!src.startsWith(projectPath + path.sep) || !fs.existsSync(src) || !fs.statSync(src).isDirectory()) throw new Error('Ordner nicht gefunden.') + // the folder itself goes into the zip (unpacks as "dist\...") + base = path.dirname(src) + items = [path.basename(src)] + } + const outDir = path.join(projectPath, ARCHIVE_DIR) + fs.mkdirSync(outDir, { recursive: true }) + const label = what === 'project' ? 'projekt' : safe(String(what)) + let out = path.join(outDir, `${safe(project)}_${label}_${stamp()}.zip`) + for (let i = 2; fs.existsSync(out); i++) out = out.replace(/(_\d+)?\.zip$/i, `_${i}.zip`) + running = true + try { + // tar.exe of Windows (System32) - not a tar from Git or MSYS, which can't write ZIP + const tar = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe') + if (!fs.existsSync(tar)) throw new Error('tar.exe fehlt (gehört zu Windows 10/11).') + const r = await run(tar, ['-a', '-c', '-f', out, ...excludes, '-C', base, ...items], { timeout: 60 * 60 * 1000 }) + if (!r.ok) { + try { fs.unlinkSync(out) } catch {} + throw new Error(`ZIP fehlgeschlagen: ${(r.stderr || r.stdout).trim().split(/\r?\n/).slice(-2).join(' ') || `Code ${r.code}`}`) + } + const st = fs.statSync(out) + return { name: path.basename(out), mb: Math.round((st.size / 1048576) * 10) / 10, path: out } + } finally { + running = false + } +} + +const busy = () => running + +module.exports = { findReleaseDirs, listArchives, zip, busy, ARCHIVE_DIR } diff --git a/lib/backup.js b/lib/backup.js index f1b55a2..e40000c 100644 --- a/lib/backup.js +++ b/lib/backup.js @@ -27,6 +27,7 @@ const state = { 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") + auto: false, // started by the automatic backup schedule error: null, check: null, // summary of the last check progress: null, // { files, filesTotal, bytes, bytesTotal, current } @@ -90,10 +91,11 @@ function baseArgs(cfg) { '/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) { +// robocopy runs of a job: one per projects folder (the shown ones, or `rootList`), +// or one for a single project +function itemsFor(t, scope, rootList = roots) { 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) })) + return rootList.map((root) => ({ root, source: root, target: destOf(t, root) })) } const stamp = () => new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '-') @@ -173,12 +175,14 @@ function failedFromLog(log, source, target) { // 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) { +// opts.roots: other projects folders than the shown ones (automatic backup: all of them); +// opts.auto: started by the schedule (lib/scheduler.js), shown as such in the UI. +function check(scope = null, autoCopy = false, targetId = null, opts = {}) { if (busy()) return false const cfg = config(targetId) - const items = itemsFor(cfg.t, scope) + const items = itemsFor(cfg.t, scope, opts.roots?.length ? opts.roots : roots) 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 }) + Object.assign(state, { phase: 'checking', target: cfg.t.id, scope: scope ? keyOf(scope.root, scope.folder) : null, autoCopy, auto: !!opts.auto, 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?`) diff --git a/lib/create.js b/lib/create.js index 892ede0..b40a586 100644 --- a/lib/create.js +++ b/lib/create.js @@ -68,6 +68,53 @@ async function create(opts) { } } +// Renames a project folder and/or moves it into another projects folder. +// Same drive: a plain rename. Other drive: robocopy everything (no excludes), +// check that nothing is missing, only then delete the original. +// opts: { from (absolute project path), rootPath (target projects folder), name } +async function move(opts) { + if (running) throw new Error(`Es läuft gerade schon „${running}“.`) + const name = checkName(opts.name) + const src = path.resolve(opts.from) + const dest = path.join(path.resolve(opts.rootPath), name) + if (path.basename(src).toLowerCase() === '_tools') throw new Error('_Tools wird nicht umbenannt oder verschoben.') + if (src === dest) throw new Error('Name und Ordner sind unverändert.') + const caseOnly = src.toLowerCase() === dest.toLowerCase() + if (!caseOnly && fs.existsSync(dest)) throw new Error(`Es gibt schon einen Ordner „${name}“ in ${opts.rootPath}.`) + if (dest.toLowerCase().startsWith(src.toLowerCase() + path.sep)) throw new Error('Ein Projekt kann nicht in sich selbst verschoben werden.') + running = path.basename(src) + try { + const copyMove = async () => { + const args = [src, dest, '/E', '/XJ', '/R:1', '/W:1', '/COPY:DAT', '/DCOPY:T', '/MT:8', '/NJH', '/NJS', '/NP', '/NFL', '/NDL'] + const r = await run('robocopy', args, { timeout: 2 * 60 * 60 * 1000 }) + if (r.code < 0 || r.code >= 8) throw new Error(`Kopieren fehlgeschlagen (robocopy ${r.code}). Das Original in ${src} ist unverändert; die angefangene Kopie liegt in ${dest}.`) + // check: a listing run must find nothing left to copy + const chk = await run('robocopy', [src, dest, '/E', '/XJ', '/L', '/NJH', '/NJS', '/NP', '/NDL', '/FP', '/R:0', '/W:0'], { timeout: 30 * 60 * 1000 }) + const missing = chk.stdout.split(/\r?\n/).filter((l) => /\t/.test(l) && !/\*EXTRA/i.test(l)).length + if (chk.code < 0 || chk.code >= 8 || missing) throw new Error(`Kopie unvollständig (${missing} Dateien fehlen). Das Original in ${src} bleibt erhalten; die Kopie liegt in ${dest}.`) + fs.rmSync(src, { recursive: true, force: true, maxRetries: 3 }) + } + if (process.env.DASHBOARD_TEST_FORCE_COPY && !caseOnly) await copyMove() + else { + try { + if (caseOnly) { + // Windows: a case-only rename needs a detour + const tmp = `${src}.__umbenennen__${Date.now()}` + fs.renameSync(src, tmp) + fs.renameSync(tmp, dest) + } else fs.renameSync(src, dest) + } catch (e) { + if (e.code === 'EXDEV') await copyMove() + else if (e.code === 'EPERM' || e.code === 'EBUSY' || e.code === 'EACCES') throw new Error('Der Ordner ist in Benutzung (VS Code, Konsole, laufendes Programm, Explorer-Fenster?) – schließen und nochmal versuchen.') + else throw e + } + } + return { name, path: dest } + } finally { + running = null + } +} + const busy = () => !!running -module.exports = { create, checkName, busy } +module.exports = { create, move, checkName, busy } diff --git a/lib/scheduler.js b/lib/scheduler.js new file mode 100644 index 0000000..4b65158 --- /dev/null +++ b/lib/scheduler.js @@ -0,0 +1,143 @@ +// Automatic backup: runs the normal backup (check → copy, never deletes) of +// all projects folders on a schedule chosen in the settings - at every start, +// hourly, daily at a time, or weekly on a day at a time. Only while the +// dashboard runs; a missed time (PC off, window closed) is made up at the next +// start. An unreachable target (NAS off, USB disk missing) is tried again after +// RETRY_MS. With target 'all' the targets are backed up one after another. +const fs = require('fs') +const path = require('path') +const settings = require('./settings') +const backup = require('./backup') + +const FILE = path.join(settings.DATA_DIR, 'auto-backup.json') +const TICK_MS = 30 * 1000 +const RETRY_MS = 30 * 60 * 1000 +const START_DELAY_MS = 2 * 60 * 1000 // "at every start": give the PC (and the NAS) a moment + +// since: when the current schedule was switched on/changed - times before that +// are not "missed" (switching on "daily 20:00" at 14:00 starts today at 20:00) +let st = { lastRun: null, lastAttempt: null, lastResult: null, since: null, plan: null } +try { st = { ...st, ...JSON.parse(fs.readFileSync(FILE, 'utf-8')) } } catch {} +const bootAt = Date.now() +let startDone = false +let queue = [] // target ids still to do in this run +let current = null // { id } of the running job +let results = [] // per target of this run: { id, name, ok, error } +let timer = null + +function save() { + try { fs.mkdirSync(path.dirname(FILE), { recursive: true }); fs.writeFileSync(FILE, JSON.stringify(st, null, 1)) } catch {} +} +const ms = (iso) => (iso ? new Date(iso).getTime() : 0) +function cfg() { + const c = settings.get().backup.auto ?? { interval: 'off' } + const plan = c.interval === 'off' ? 'off' : `${c.interval}|${c.time}|${c.weekday}` + if (plan !== st.plan) { st.plan = plan; st.since = new Date().toISOString(); save() } + return c +} +// last time that counts as "done": the last run, or when the schedule was set +const base = () => Math.max(ms(st.lastRun), ms(st.since)) + +// the latest scheduled moment at or before `now` (daily/weekly), else null +function lastSlot(c, now) { + const [h, m] = (c.time ?? '20:00').split(':').map(Number) + const d = new Date(now) + d.setHours(h, m, 0, 0) + if (c.interval === 'daily') { if (d > now) d.setDate(d.getDate() - 1); return d } + if (c.interval === 'weekly') { + d.setDate(d.getDate() - ((d.getDay() - c.weekday + 7) % 7)) + if (d > now) d.setDate(d.getDate() - 7) + return d + } + return null +} + +function due(c, now = new Date()) { + if (c.interval === 'off' || !settings.get().backup.targets.length) return false + // failed last time: wait before trying again + if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return false + switch (c.interval) { + case 'start': return !startDone && now - bootAt >= START_DELAY_MS + case 'hourly': return now - base() >= 60 * 60 * 1000 + case 'daily': + case 'weekly': return base() < lastSlot(c, now).getTime() + } + return false +} + +// when the next automatic backup will start (for the settings), or null +function nextRun(c, now = new Date()) { + if (c.interval === 'off' || !settings.get().backup.targets.length) return null + if (current || queue.length) return now.toISOString() + if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return new Date(ms(st.lastAttempt) + RETRY_MS).toISOString() + if (due(c, now)) return now.toISOString() + switch (c.interval) { + case 'start': return startDone ? null : new Date(bootAt + START_DELAY_MS).toISOString() + case 'hourly': return new Date(base() + 60 * 60 * 1000).toISOString() + case 'daily': + case 'weekly': { + const s = lastSlot(c, now) + s.setDate(s.getDate() + (c.interval === 'daily' ? 1 : 7)) + return s.toISOString() + } + } + return null +} + +// all registered projects folders that exist (not only the ones shown right now) +const allRoots = () => settings.get().roots.map((r) => path.resolve(r.path)).filter((p) => fs.existsSync(p)) + +function startNext() { + if (backup.busy() || !queue.length) return + const id = queue[0] + if (!backup.check(null, true, id, { roots: allRoots(), auto: true })) return + queue.shift() + current = { id } +} + +function finishRun() { + const ok = results.length > 0 && results.every((r) => r.ok) + st.lastResult = { at: new Date().toISOString(), ok, targets: results } + if (ok) st.lastRun = st.lastResult.at + save() + results = [] +} + +function tick() { + try { + if (current) { + if (backup.busy()) return + const s = backup.getState() + const t = settings.get().backup.targets.find((x) => x.id === current.id) + results.push({ id: current.id, name: t?.name ?? current.id, ok: s.phase === 'done', error: s.phase === 'done' ? null : s.phase === 'cancelled' ? 'abgebrochen' : s.error }) + current = null + if (!queue.length) finishRun() + } + if (queue.length) return startNext() + const c = cfg() + // someone else's backup is running: the schedule waits for the next tick + if (backup.busy() || !due(c)) return + const targets = settings.get().backup.targets + queue = c.target === 'all' ? targets.map((t) => t.id) : targets.filter((t) => t.id === c.target).map((t) => t.id) + if (!queue.length) queue = targets.slice(0, 1).map((t) => t.id) + if (c.interval === 'start') startDone = true + st.lastAttempt = new Date().toISOString() + save() + startNext() + } catch (e) { + console.error('Auto-Backup:', e.message) + } +} + +function start() { + if (timer) return + timer = setInterval(tick, TICK_MS) + setTimeout(tick, 5000) +} + +function status() { + const c = cfg() + return { ...c, next: nextRun(c), running: !!current || queue.length > 0, lastRun: st.lastRun, lastResult: st.lastResult } +} + +module.exports = { start, status, lastSlot, due } diff --git a/lib/settings.js b/lib/settings.js index fffa963..ef65e41 100644 --- a/lib/settings.js +++ b/lib/settings.js @@ -65,10 +65,26 @@ function defaults() { targets: Array.isArray(legacy?.targets) ? legacy.targets : targetsFrom(legacy?.target ?? ''), excludeDirs: legacy?.excludeDirs ?? DEFAULT_EXCLUDE_DIRS, excludeFiles: legacy?.excludeFiles ?? DEFAULT_EXCLUDE_FILES, + // "Backup fällig": changed since the last backup and that is older than this + remindDays: 7, + auto: { ...AUTO_DEFAULT }, }, } } +// Automatic backup (lib/scheduler.js): interval off | start | hourly | daily | weekly, +// time "HH:MM" (daily/weekly), weekday 0=So … 6=Sa (weekly), target 'all' or a target id. +const AUTO_DEFAULT = { interval: 'off', time: '20:00', weekday: 5, target: 'all' } +function cleanAuto(a, old) { + const o = { ...AUTO_DEFAULT, ...(old ?? {}) } + if (!a || typeof a !== 'object') return o + if (['off', 'start', 'hourly', 'daily', 'weekly'].includes(a.interval)) o.interval = a.interval + if (typeof a.time === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(a.time)) o.time = a.time + if (Number.isInteger(+a.weekday) && +a.weekday >= 0 && +a.weekday <= 6) o.weekday = +a.weekday + if (typeof a.target === 'string' && a.target) o.target = a.target + return o +} + let current = null function load() { @@ -77,6 +93,7 @@ function load() { 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 + backup.auto = cleanAuto(saved?.backup?.auto) // 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 })) @@ -225,8 +242,12 @@ function save(input) { targets, excludeDirs: cleanList(input.excludeDirs, s.backup.excludeDirs), excludeFiles: cleanList(input.excludeFiles, s.backup.excludeFiles), + remindDays: Number.isFinite(+input.remindDays) && +input.remindDays >= 1 ? Math.min(365, Math.round(+input.remindDays)) : (s.backup.remindDays ?? 7), + auto: cleanAuto(input.auto, s.backup.auto), }, }) + // an automatic backup to a target that was removed falls back to all targets + if (next.backup.auto.target !== 'all' && !targets.some((t) => t.id === next.backup.auto.target)) next.backup.auto.target = 'all' 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) diff --git a/lib/storage.js b/lib/storage.js index 8cf9e05..7d41cbb 100644 --- a/lib/storage.js +++ b/lib/storage.js @@ -53,7 +53,9 @@ function scriptFor(root) { return null } -function available() { return !!scriptFor(roots[0]) } +// sizes can always be measured; cleanup candidates need cleanup.ps1 +function available() { return true } +const cleanupAvailable = () => !!scriptFor(roots[0]) function psArgs(root, extra) { return ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptFor(root), '-Root', root, ...extra, '-Json'] @@ -66,25 +68,72 @@ function parseJson(stdout) { return JSON.parse(text.slice(start)) } -async function dirSizeMB(dir) { +async function dirBytes(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 + return m ? +m[1] : null +} + +const MB = (b) => Math.round((b / 1048576) * 10) / 10 + +// Size of a folder split by its direct subfolders (one robocopy run each, so the +// total costs the same as one run over the whole folder). Files directly in the +// folder are added up as "(Dateien)". -> { bytes, children: [{ name, mb, bytes }] } +async function folderSplit(dir) { + let entries = [] + try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return { bytes: 0, children: [] } } + let fileBytes = 0 + const dirs = [] + for (const e of entries) { + const full = path.join(dir, e.name) + if (e.isFile()) { try { fileBytes += fs.statSync(full).size } catch {} } + else if (e.isDirectory() && !e.isSymbolicLink()) { + // junctions look like directories: skip them like robocopy /XJ does + try { if (fs.lstatSync(full).isSymbolicLink()) continue } catch { continue } + dirs.push(e.name) + } + } + const children = [] + await pool(dirs, 4, async (name) => { + const b = await dirBytes(path.join(dir, name)) + if (b) children.push({ name, bytes: b }) + }) + if (fileBytes) children.push({ name: '(Dateien)', bytes: fileBytes, files: true }) + children.sort((a, b) => b.bytes - a.bytes) + return { bytes: children.reduce((s, c) => s + c.bytes, 0), children } +} + +// Tree for the treemap: subfolders of the project, the biggest ones (>= 5 % and +// >= 50 MB, at most 3) split once more. Tiny entries are merged. +async function sizeTree(dir) { + const top = await folderSplit(dir) + const big = top.children.filter((c) => !c.files && c.bytes >= top.bytes * 0.05 && c.bytes >= 50 * 1048576).slice(0, 3) + for (const c of big) c.children = (await folderSplit(path.join(dir, c.name))).children + const tidy = (list, total) => { + const keep = [], small = { name: '(kleinere)', bytes: 0, merged: 0 } + for (const c of list) { + if (c.bytes < total * 0.002 && list.length > 12) { small.bytes += c.bytes; small.merged++ } + else keep.push({ name: c.name, mb: MB(c.bytes), ...(c.files ? { files: true } : {}), ...(c.children ? { children: tidy(c.children, c.bytes) } : {}) }) + } + if (small.merged) keep.push({ name: `(${small.merged} kleinere)`, mb: MB(small.bytes), merged: true }) + return keep.slice(0, 60) + } + return { bytes: top.bytes, tree: tidy(top.children, top.bytes) } } async function scanProject(root, folder) { const dir = path.join(root, folder) - const [sizeMB, cand] = await Promise.all([ - dirSizeMB(dir), + const [split, cand] = await Promise.all([ + sizeTree(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 } + d[folder] = { at: new Date().toISOString(), sizeMB: Math.round(split.bytes / 1048576), candidates, deletable, tree: split.tree } save() return d[folder] } @@ -118,6 +167,18 @@ async function clean(root, folder, paths) { function get(root, folder) { return all[rootKey(root)]?.[folder] ?? null } +// A project was renamed/moved: keep its scan result. Cleanup paths are +// "\..." relative to the projects folder, so they get the new name. +function rename(oldRoot, oldFolder, newRoot, newFolder) { + const d = get(oldRoot, oldFolder) + if (!d) return + delete all[rootKey(oldRoot)][oldFolder] + const prefix = oldFolder + path.sep + d.candidates = (d.candidates ?? []).map((c) => (typeof c.Path === 'string' && c.Path.startsWith(prefix) ? { ...c, Path: newFolder + path.sep + c.Path.slice(prefix.length) } : c)) + ;(all[rootKey(newRoot)] ??= {})[newFolder] = d + save() +} + // items: [{ root, folder }] function totals(items) { let sizeMB = 0, cacheMB = 0, allMB = 0, scanned = 0 @@ -132,4 +193,4 @@ function totals(items) { return { sizeMB, cacheMB, allMB, scanned } } -module.exports = { init, startScan, clean, get, totals, state, available, busy } +module.exports = { init, startScan, clean, get, rename, totals, state, available, cleanupAvailable, busy } diff --git a/lib/supervisor.js b/lib/supervisor.js new file mode 100644 index 0000000..70a6692 --- /dev/null +++ b/lib/supervisor.js @@ -0,0 +1,34 @@ +// Keeps the dashboard server restartable without losing the process the +// launcher (or the console) holds: this process only runs server.js as a +// worker and starts it again when it exits with RESTART_CODE ("Neu starten" +// in the UI after the code was updated). Any other exit ends this process too. +// The worker ends itself when this process goes away (IPC disconnect), so +// closing the window never leaves a server behind. +const { fork } = require('child_process') + +const RESTART_CODE = 75 + +function supervise(script) { + let child = null + const start = () => { + child = fork(script, process.argv.slice(2), { + env: { ...process.env, DASHBOARD_WORKER: '1' }, + stdio: 'inherit', + }) + child.on('exit', (code, signal) => { + if (code === RESTART_CODE) { + console.log('Dashboard wird neu gestartet …') + start() + return + } + process.exit(code ?? (signal ? 1 : 0)) + }) + } + // Ctrl+C / normal end: take the worker along + const stop = () => { try { child?.kill() } catch {} process.exit(0) } + process.on('SIGINT', stop) + process.on('SIGTERM', stop) + start() +} + +module.exports = { supervise, RESTART_CODE } diff --git a/public/app.js b/public/app.js index 4a2b955..2967747 100644 --- a/public/app.js +++ b/public/app.js @@ -115,7 +115,8 @@ function gitHtml(git, short = false) { } // Backup state of one project (p.lastBackup from the server: own or full backup, newer one) -const BACKUP_FRESH_DAYS = 7 +// days after which an un-backed-up change counts as "Backup fällig" (Einstellungen → Backup) +let BACKUP_FRESH_DAYS = 7 function cloudInfo(p) { const l = p.lastBackup if (!l) return { level: 'red', short: 'nie', label: 'Backup: noch nie gesichert' } @@ -123,7 +124,16 @@ function cloudInfo(p) { 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}` } + const due = backupDue(p) ? ' · seitdem geändert: Backup fällig' : '' + return { level, short: timeAgo(l.at), label: `Backup: gesichert ${when} (${l.how})${extra}${due}` } +} +// changed since the last backup (or never backed up) and that backup is older than the reminder time +function backupDue(p) { + const changed = p.lastChange?.at + if (!changed || p.folder === '_Tools') return false + const l = p.lastBackup + if (!l) return true + return changed > l.at && Date.now() - new Date(l.at) > BACKUP_FRESH_DAYS * 86400000 } function cloudBadge(p, cls = 'tbadge') { const c = cloudInfo(p) @@ -198,9 +208,13 @@ async function load() { rootPaths = data.rootPaths ?? (rootDir ? [rootDir] : []) roots = data.roots ?? [] activeRoots = data.activeRoots ?? (data.activeRoot ? [data.activeRoot] : []) + BACKUP_FRESH_DAYS = data.remindDays ?? 7 renderRootPicker() if (editing) editing = projects.find((p) => p.name === editing.name) ?? editing render() + renderBackupButton() + // "last change" dates are all known → the backup reminder can count + if (!data.activityPending && backup) remindBackup() if (scanState?.running) pollScan() // last-change dates are still being collected in the background → refresh once more clearTimeout(load.again) @@ -247,6 +261,61 @@ document.getElementById('nFrom').addEventListener('change', () => { document.getElementById('nCancel').onclick = () => newDlg.close() document.getElementById('btnNew').onclick = () => openNewProject('') document.getElementById('btnClone').onclick = () => { if (editing) openNewProject(editing.name) } + +/* ── rename / move a project ──────────────────────────────────────────── */ + +const moveDlg = document.getElementById('moveDlg') +let moving = null +const driveOf = (p) => (p.match(/^([A-Za-z]:|\\\\[^\\]+\\[^\\]+)/)?.[1] ?? '').toLowerCase() +function openMove(p) { + moving = p + const from = roots.find((r) => r.id === p.root) + document.getElementById('mvFrom').textContent = `Jetzt: ${from ? `${from.path}\\` : ''}${p.folder ?? p.name}` + document.getElementById('mvName').value = p.folder ?? p.name + document.getElementById('mvRoot').innerHTML = roots.map((r) => ``).join('') + document.getElementById('mvRoot').value = p.root ?? activeRoots[0] ?? '' + document.getElementById('mvCopyOk').checked = false + document.getElementById('mvError').style.display = 'none' + syncMove() + moveDlg.showModal() + document.getElementById('mvName').select() +} +function syncMove() { + const from = roots.find((r) => r.id === moving?.root) + const to = roots.find((r) => r.id === document.getElementById('mvRoot').value) + document.getElementById('mvCopy').hidden = !(from && to && driveOf(from.path) !== driveOf(to.path)) +} +document.getElementById('mvRoot').addEventListener('change', syncMove) +document.getElementById('mvCancel').onclick = () => moveDlg.close() +document.getElementById('btnMove').onclick = () => { if (editing) openMove(editing) } +document.getElementById('moveForm').addEventListener('submit', async (e) => { + e.preventDefault() + const err = document.getElementById('mvError') + err.style.display = 'none' + if (!document.getElementById('mvCopy').hidden && !document.getElementById('mvCopyOk').checked) { + err.innerHTML = `${ic('triangle-alert')}
Bitte bestätigen, dass kopiert und das Original danach gelöscht wird.
` + err.style.display = '' + return + } + const ok = document.getElementById('mvOk') + ok.disabled = true + ok.querySelector('span').textContent = document.getElementById('mvCopy').hidden ? 'Wird umbenannt…' : 'Wird kopiert…' + try { + const r = await postJson(api(moving.name, 'move'), { name: document.getElementById('mvName').value, root: document.getElementById('mvRoot').value }) + moveDlg.close() + closeEditor() + toast(r.shown ? `Jetzt: „${r.name}“ in „${r.rootName}“` : `„${r.name}“ nach „${r.rootName}“ verschoben (wird gerade nicht angezeigt)`, 'folder-pen') + await load() + const p = r.shown && projects.find((x) => x.name === r.key) + if (p) openEditor(p) + } catch (ex) { + err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(ex.message)}
` + err.style.display = '' + } finally { + ok.disabled = false + ok.querySelector('span').textContent = 'Übernehmen' + } +}) document.getElementById('newForm').addEventListener('submit', async (e) => { e.preventDefault() const ok = document.getElementById('nOk') @@ -446,18 +515,38 @@ async function openSettings(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() + shownRootIds = s.activeRoots ?? [s.activeRoot] + document.getElementById('fRoots').innerHTML = (s.roots ?? []).map((r) => rootRow(r)).join('') || rootRow() document.getElementById('fImport').hidden = true document.getElementById('fImportBody').innerHTML = '' - document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('') || targetRow() - document.getElementById('fExDirs').value = (s.backup?.excludeDirs ?? []).join(', ') + document.getElementById('fTargets').innerHTML = (s.backup?.targets ?? []).map(targetRow).join('') + setExDirs(s.backup?.excludeDirs ?? []) + document.getElementById('fRemind').value = s.backup?.remindDays ?? 7 + const au = s.backup?.auto ?? { interval: 'off', time: '20:00', weekday: 5, target: 'all' } + document.getElementById('fAutoInt').value = au.interval + document.getElementById('fAutoTime').value = au.time + document.getElementById('fAutoDay').value = String(au.weekday) + document.getElementById('fAutoTarget').innerHTML = `` + + (s.backup?.targets ?? []).map((t) => ``).join('') + document.getElementById('fAutoTarget').value = au.target + if (!document.getElementById('fAutoTarget').value) document.getElementById('fAutoTarget').value = 'all' + syncAuto() + renderAutoStatus() document.getElementById('fItchProfile').value = s.itchProfile ?? '' loadItchStatus() - document.getElementById('spData').innerHTML = s.dataDir ? `${ic('database', 'sm')} Einstellungen gespeichert in ${escapeHtml(s.dataDir)}` : '' + document.getElementById('spData').innerHTML = s.dataDir + ? `
Einstellungen
${escapeHtml(s.dataDir)}
+
Scan- & Backup-Stand
im selben Ordner (scan.json, backup.json)
+
Darstellung
Hell / System / Dunkel – oben rechts in der Leiste
` + : '' document.getElementById('spWelcome').style.display = setup ? '' : 'none' document.getElementById('spTitle').textContent = setup ? 'Einrichten' : 'Einstellungen' document.getElementById('spError').style.display = 'none' + for (const b of document.querySelectorAll('#spTabs button')) b.classList.remove('has-err') + setSettingsTab('folders') + refreshSettingsRows() const panel = document.getElementById('spanel') + panel.classList.remove('dirty') panel.classList.toggle('setup', settingsSetup) panel.classList.add('open') panel.setAttribute('aria-hidden', 'false') @@ -467,16 +556,18 @@ async function openSettings(setup) { // "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…` + el.className = 'spstatus' + el.innerHTML = `${ic('loader')}
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 } + if (!r.profile) { el.innerHTML = ''; return } const un = r.unmatched ?? [] + el.className = `spstatus ${r.error ? 'err' : 'ok'}` 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 } + ? `${ic('triangle-alert')}
${escapeHtml(r.error)}
` + : `${ic('circle-check')}
${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.className = 'spstatus err'; el.textContent = e.message } } document.getElementById('btnItchRefresh').onclick = async () => { await loadItchStatus(true); load() } @@ -500,12 +591,22 @@ async function saveSettings() { 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), + excludeDirs: getExDirs(), + remindDays: Number(document.getElementById('fRemind').value) || 7, + auto: { + interval: document.getElementById('fAutoInt').value, + time: document.getElementById('fAutoTime').value || '20:00', + weekday: Number(document.getElementById('fAutoDay').value), + target: document.getElementById('fAutoTarget').value || 'all', + }, itchProfile: document.getElementById('fItchProfile').value, } + const btn = document.getElementById('spSave') + btn.disabled = true try { settingsCache = await postJson('/api/settings', body) settingsSetup = false + document.getElementById('spanel').classList.remove('dirty') closeSettings() toast('Einstellungen gespeichert', 'save') await loadBackup() @@ -513,9 +614,60 @@ async function saveSettings() { } catch (e) { err.innerHTML = `${ic('triangle-alert')}
${escapeHtml(e.message)}
` err.style.display = '' + // mark (and show) the tab the error belongs to + const tab = /Backup-Ziel/.test(e.message) ? 'backup' : /itch/i.test(e.message) ? 'itch' : 'folders' + for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('has-err', b.dataset.stab === tab) + setSettingsTab(tab) + } finally { + btn.disabled = false } } +/* automatic backup (settings → Backup) */ +function syncAuto() { + const v = document.getElementById('fAutoInt').value + document.getElementById('fAutoTimeWrap').hidden = !['daily', 'weekly'].includes(v) + document.getElementById('fAutoDayWrap').hidden = v !== 'weekly' + document.getElementById('fAutoTargetWrap').hidden = v === 'off' || (settingsCache?.backup?.targets?.length ?? 0) < 2 +} +document.getElementById('fAutoInt').addEventListener('change', syncAuto) +// "heute 20:00", "morgen 20:00", "Fr., 14.11. 20:00" +function fmtWhen(iso) { + const d = new Date(iso), now = new Date() + const time = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) + if (d - now < 60000) return 'gleich' + const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime() + const diff = Math.round((day(d) - day(now)) / 86400000) + return diff === 0 ? `heute ${time}` : diff === 1 ? `morgen ${time}` : `${d.toLocaleDateString('de-DE', { weekday: 'short', day: 'numeric', month: 'numeric' })} ${time}` +} +function renderAutoStatus() { + const el = document.getElementById('spAuto') + const sch = backup?.schedule + if (!sch || sch.interval === 'off') { el.className = 'spstatus'; el.innerHTML = ''; return } + const r = sch.lastResult + const last = r ? (r.ok ? `Zuletzt erfolgreich ${timeAgo(r.at)}.` : `Letzter Versuch ${timeAgo(r.at)} fehlgeschlagen – ${escapeHtml(r.targets.filter((t) => !t.ok).map((t) => `${t.name}: ${t.error ?? 'Fehler'}`).join('; '))}`) : 'Noch nie automatisch gesichert.' + el.className = `spstatus ${r && !r.ok ? 'err' : r ? 'ok' : ''}` + el.innerHTML = `${ic(sch.running ? 'loader' : r && !r.ok ? 'triangle-alert' : 'calendar-clock')}
${sch.running ? 'Läuft gerade. ' : sch.next ? `Nächstes automatisches Backup: ${fmtWhen(sch.next)}. ` : ''}${last}
` +} + +/* settings tabs, dirty marker, Ctrl+S */ +function setSettingsTab(tab) { + for (const b of document.querySelectorAll('#spTabs button')) b.classList.toggle('active', b.dataset.stab === tab) + for (const p of document.querySelectorAll('#spanel [data-spane]')) p.hidden = p.dataset.spane !== tab +} +for (const b of document.querySelectorAll('#spTabs button')) b.onclick = () => setSettingsTab(b.dataset.stab) +const markSettingsDirty = () => document.getElementById('spanel').classList.add('dirty') +document.getElementById('spanel').addEventListener('input', (e) => { if (!e.target.closest('#fImport')) markSettingsDirty() }) +document.addEventListener('keydown', (e) => { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && document.getElementById('spanel').classList.contains('open')) { + e.preventDefault() + saveSettings() + } +}) +document.getElementById('spOpenData').onclick = async () => { + try { await postJson('/api/datadir/open') } catch (e) { toast(e.message, 'triangle-alert') } +} + // "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') @@ -526,21 +678,64 @@ document.getElementById('spanel').addEventListener('click', async (e) => { 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 (name && !name.value) { name.value = row.classList.contains('rrow') ? folderName(chosen) : shortTargetName(chosen); name.size = nameSize(name.value) } + if (row) { markSettingsDirty(); refreshSettingsRows() } if (b.dataset.for === 'fImportPath') listImport() }) -// projects folder rows: [name] [path] [Durchsuchen…] [↑] [x]; the active one is marked +// One list entry (projects folder or backup target): [icon] name + badges / path / info line [actions] const folderName = (p) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || p -function rootRow(r = { id: '', name: '', path: '' }, active = false) { - return `
- - - - - +let shownRootIds = [] // folders shown on the board (badge "angezeigt") +// the name field grows with its text, so the badges sit right after it +const nameSize = (v) => Math.min(40, Math.max(10, (v ?? '').length + 2)) +function settingsItem(kind, x, placeholder) { + const isRoot = kind === 'root' + return `
+
${ic(isRoot ? 'folder' : 'hard-drive')}
+
+
+ +
+
+
+ + + +
` } +const rootRow = (r = { id: '', name: '', path: '' }) => settingsItem('root', r, 'z. B. D:\\Projekte') +const targetRow = (t = { id: '', name: '', path: '' }) => settingsItem('target', t, 'z. B. E:\\Backup\\Projekte oder \\\\NAS\\Freigabe\\Projekte') + +// badges and info lines depend on the order (first = main folder / default target) +function refreshSettingsRows() { + const rows = [...document.querySelectorAll('#fRoots .rrow')] + rows.forEach((row, i) => { + const id = row.dataset.id + const name = row.querySelector('.tname').value.trim() || folderName(row.querySelector('.tpath').value.trim()) + const n = id && shownRootIds.includes(id) ? projects.filter((p) => p.root === id).length : null + row.querySelector('.sbadges').innerHTML = + (i === 0 ? `${ic('star')}Hauptordner ` : '') + + (id && shownRootIds.includes(id) ? `${ic('eye')}angezeigt` : '') + row.querySelector('.sstat').innerHTML = row.querySelector('.tpath').value.trim() + ? `${n != null ? `${n} Projekte` : ''}${i === 0 ? 'Backup direkt ins Ziel' : `Backup in Unterordner „${escapeHtml(name)}“`}` + : 'Pfad eintragen oder Ordner wählen' + row.querySelector('[data-up]').disabled = i === 0 + }) + const trows = [...document.querySelectorAll('#fTargets .trow')] + trows.forEach((row, i) => { + const st = backup?.targets?.find((t) => t.id === row.dataset.id) + const last = st?.last + row.querySelector('.sbadges').innerHTML = + (i === 0 ? `Standard ` : '') + + (!row.dataset.id ? '' : last ? `${last.ok ? 'gesichert' : 'unvollständig'} ${timeAgo(last.at)}` : 'noch nie komplett') + row.querySelector('.sstat').innerHTML = row.dataset.id ? '' : 'Neu – wird beim Speichern geprüft' + row.querySelector('[data-up]').disabled = i === 0 + }) + document.getElementById('spnFolders').textContent = rows.length || '' + document.getElementById('spnTargets').textContent = trows.length || '' +} + const rowRootPaths = () => [...document.querySelectorAll('#fRoots .rrow .tpath')].map((i) => i.value.trim().toLowerCase().replace(/[\\/]+$/, '')).filter(Boolean) function addRootRow(r) { const box = document.getElementById('fRoots') @@ -548,13 +743,63 @@ function addRootRow(r) { const empty = [...box.querySelectorAll('.rrow')].find((x) => !x.querySelector('.tpath').value.trim() && !x.querySelector('.tname').value.trim()) if (empty && r) empty.remove() box.insertAdjacentHTML('beforeend', rootRow(r)) + markSettingsDirty() + refreshSettingsRows() return box.lastElementChild } document.getElementById('fAddRoot').onclick = () => addRootRow().querySelector('.tpath').focus() -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) +// ↑ / ✕ in both lists +for (const id of ['fRoots', 'fTargets']) { + const list = document.getElementById(id) + list.addEventListener('click', (e) => { + const row = e.target.closest('.sitem') + if (!row) return + if (e.target.closest('[data-rm]')) row.remove() + else if (e.target.closest('[data-up]') && row.previousElementSibling) row.parentNode.insertBefore(row, row.previousElementSibling) + else return + markSettingsDirty() + refreshSettingsRows() + }) + list.addEventListener('input', (e) => { + if (e.target.classList.contains('tname')) e.target.size = nameSize(e.target.value) + refreshSettingsRows() + }) +} + +// "Nicht sichern" as chips: Enter or comma adds, ✕ removes, Backspace in the empty field removes the last +const exBox = document.getElementById('fExDirs') +const exInput = document.getElementById('fExInput') +function addExChip(v) { + v = v.trim() + if (!v || getExDirs(false).some((x) => x.toLowerCase() === v.toLowerCase())) return + exInput.insertAdjacentHTML('beforebegin', `${escapeHtml(v)}`) +} +function setExDirs(list) { + for (const c of exBox.querySelectorAll('.xchip')) c.remove() + exInput.value = '' + for (const v of list) addExChip(v) +} +// withPending: also what is still typed in the field +function getExDirs(withPending = true) { + const list = [...exBox.querySelectorAll('.xchip')].map((c) => c.dataset.v) + if (withPending) for (const v of exInput.value.split(',')) if (v.trim() && !list.includes(v.trim())) list.push(v.trim()) + return list +} +exInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter' || e.key === ',') { + e.preventDefault() + for (const v of exInput.value.split(',')) addExChip(v) + exInput.value = '' + markSettingsDirty() + } else if (e.key === 'Backspace' && !exInput.value) { + exBox.querySelector('.xchip:last-of-type')?.remove() + markSettingsDirty() + } +}) +exBox.addEventListener('click', (e) => { + const rm = e.target.closest('.xchip button') + if (rm) { rm.closest('.xchip').remove(); markSettingsDirty(); return } + exInput.focus() }) // "Mehrere einlesen…": list the subfolders of a folder, tick the ones to add @@ -617,21 +862,14 @@ async function importList({ dir, body, have, onAdd }) { } } -// backup target rows in the settings: [name] [path] [Durchsuchen…] [x] +// short display name of a backup target: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup const shortTargetName = (p) => p.match(/^\\\\([^\\]+)/)?.[1] ?? (p.match(/^([A-Za-z]:)/) ? `${p.slice(0, 2)} ${p.split('\\').filter(Boolean).pop() ?? ''}`.trim() : p.split('\\').pop()) -function targetRow(t = { id: '', name: '', path: '' }) { - return `
- - - - -
` -} document.getElementById('fAddTarget').onclick = () => { document.getElementById('fTargets').insertAdjacentHTML('beforeend', targetRow()) + markSettingsDirty() + refreshSettingsRows() 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 @@ -645,10 +883,70 @@ async function postJson(url, body) { }) let data = {} try { data = await res.json() } catch {} - if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`) + if (!res.ok) { + // a route the running server doesn't know yet: it's older than this page + if (res.status === 404 && !data.error) { checkVersion(); throw new Error('Der Server ist veraltet – oben „Neu starten“ klicken.') } + throw new Error(data.error ?? `HTTP ${res.status}`) + } return data } +/* ── update banner: server code or page changed since start ───────────── */ + +let uiStampAtLoad = null +async function checkVersion() { + let v + try { + const res = await fetch('/api/version', { cache: 'no-store' }) + // 404: a server from before this check - certainly older than this page + v = res.status === 404 ? { stale: true } : await res.json() + } catch { return } + if (uiStampAtLoad === null) uiStampAtLoad = v.uiStamp ?? 0 + const banner = document.getElementById('updBanner') + const btn = document.getElementById('updBtn') + if (v.stale) { + document.getElementById('updText').textContent = 'Das Dashboard wurde aktualisiert – der Server muss neu starten, damit alles funktioniert.' + btn.innerHTML = `${ic('refresh-cw')}Neu starten` + btn.onclick = restartServer + banner.hidden = false + } else if (v.uiStamp > uiStampAtLoad) { + document.getElementById('updText').textContent = 'Neue Version der Oberfläche – Seite neu laden.' + btn.innerHTML = `${ic('refresh-cw')}Neu laden` + btn.onclick = () => location.reload() + banner.hidden = false + } else banner.hidden = true +} +async function restartServer() { + const btn = document.getElementById('updBtn') + btn.disabled = true + btn.innerHTML = `${ic('loader')}Startet neu…` + try { + let before = null + try { before = (await (await fetch('/api/version', { cache: 'no-store' })).json()).pid } catch {} + const r = await fetch('/api/restart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }) + if (r.status === 409) throw new Error((await r.json()).error) + // a server from before this feature has no restart: it must be closed by hand + if (!r.ok) throw new Error('Dieser Server kann sich noch nicht selbst neu starten – Dashboard einmal schließen und wieder öffnen.') + const until = Date.now() + 20000 + while (Date.now() < until) { + await new Promise((ok) => setTimeout(ok, 700)) + try { + const v = await (await fetch('/api/version', { cache: 'no-store' })).json() + if (v.pid && v.pid !== before) { location.reload(); return } + } catch {} + } + throw new Error('Server antwortet nicht – Dashboard schließen und wieder öffnen.') + } catch (e) { + toast(e.message, 'triangle-alert') + btn.disabled = false + btn.innerHTML = `${ic('refresh-cw')}Neu starten` + } +} +checkVersion() +setInterval(checkVersion, 60000) +window.addEventListener('focus', checkVersion) +document.addEventListener('visibilitychange', () => { if (!document.hidden) checkVersion() }) + async function patchProject(name, body) { const res = await fetch(`/api/projects/${encodeURIComponent(name)}`, { method: 'PATCH', @@ -680,6 +978,7 @@ 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: 'due', label: 'Backup fällig', icon: 'clock-alert', test: backupDue }, { 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 }, @@ -774,6 +1073,8 @@ function pollScan() { scanTimer = setTimeout(async () => { try { scanState = await (await fetch('/api/scan')).json() } catch { return } renderKpis() + // the storage page shows results as they come in + if (activeView === 'storage') loadStorage() if (scanState.running) pollScan() else { await load() @@ -788,6 +1089,7 @@ async function startScan(name) { const r = await postJson('/api/scan', name ? { name } : {}) scanState = r.state renderKpis() + if (activeView === 'storage') loadStorage() pollScan() } catch (e) { toast(e.message, 'triangle-alert') } } @@ -804,7 +1106,7 @@ function qsButton(p) { return `` } // Card/row corner: [VS Code] [▶]. placeholder keeps rows aligned when a project has no ▶. -// explorer: also an [Explorer] button in front (gallery tiles). +// explorer: also an [Explorer] button in front. function qsGroup(p, placeholder = false, explorer = false) { const ex = explorer ? `` : '' const vs = `` @@ -853,7 +1155,7 @@ function rowHtml(p) { ${p.published ? `${ic('rocket', 'sm')}` : ''}
- ${qsGroup(p, true)} + ${qsGroup(p, true, true)} ` } @@ -864,12 +1166,13 @@ function cardHtml(p) { return `
${avatar(p)}
${escapeHtml(p.name)}
-
${rootTag(p, true)}${prioHtml(p.priority)}
- ${qsGroup(p)} +
${prioHtml(p.priority)}
+ ${qsGroup(p, false, true)} ${p.lastCommit ? `
${ic('git-commit-horizontal', 'sm')}${escapeHtml(p.lastCommit.message)}
` : ''} ${factsHtml(p)}
${gitHtml(p.git)}${cloudChip(p)}${pubChip(p)}
+ ${multiRoot() ? `
${rootTag(p)}
` : ''}
${techChips(p.tech?.types)}${warnChips(p)}${tags}
${p.notes ? `
${escapeHtml(p.notes)}
` : ''} ${total ? `
${ic('list-checks', 'sm')}${done}/${total}
` : ''}` @@ -993,12 +1296,471 @@ function renderList() { } } +// views with their own header (no project KPIs / filter toolbar) +const WIDE_VIEWS = ['storage', 'activity'] 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) + document.body.classList.toggle('view-wide', WIDE_VIEWS.includes(view)) updateToolbarForView() try { localStorage.setItem('dash.view', view) } catch {} + if (view === 'storage') loadStorage() + if (view === 'activity') loadActivity() +} + +/* ── activity page: calendar heatmap of active projects per day ───────── */ + +let actData = null +let actDay = null +let actRange = 7 +const DOW = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] +const MONTHS = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'] +const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +const parseDay = (k) => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d) } +const fmtDay = (k) => parseDay(k).toLocaleDateString('de-DE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }) +const nActive = (k) => actData?.days[k]?.projects.length ?? 0 +// 0 · 1 · 2 · 3–4 · 5+ active projects +const levelOf = (n) => (n <= 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n <= 4 ? 3 : 4) +const LEVEL_LABEL = ['keins', '1 Projekt', '2 Projekte', '3–4 Projekte', '5+ Projekte'] + +async function loadActivity() { + try { actData = await (await fetch('/api/activity')).json() } catch { return } + if (!actDay || !actData.days[actDay]) { + // default: today, else the last day with activity + actDay = actData.days[actData.today] ? actData.today : Object.keys(actData.days).sort().pop() ?? actData.today + } + renderActivity() + clearTimeout(loadActivity.t) + // last-change dates still being collected → refresh until complete + if (actData.pending && activeView === 'activity') loadActivity.t = setTimeout(loadActivity, 3000) +} + +// heatmap grid: weeks as columns (Monday first), `weeks` back from this week +function heatGrid(weeks, cell, title) { + const today = parseDay(actData?.today ?? dayKey(new Date())) + const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7)) + const start = new Date(monday); start.setDate(monday.getDate() - (weeks - 1) * 7) + let html = DOW.map((d, i) => (i % 2 === 0 ? `${d}` : '')).join('') + let lastMonth = -1 + for (let w = 0; w < weeks; w++) { + const first = new Date(start); first.setDate(start.getDate() + w * 7) + if (first.getMonth() !== lastMonth && first.getDate() <= 7) { + html += `${MONTHS[first.getMonth()]}` + lastMonth = first.getMonth() + } else if (w === 0) lastMonth = first.getMonth() + for (let r = 0; r < 7; r++) { + const d = new Date(first); d.setDate(first.getDate() + r) + const k = dayKey(d) + const future = d > today + html += `` + } + } + return html +} + +function renderActivity() { + if (!actData) return + const keys = Object.keys(actData.days).filter((k) => nActive(k) > 0).sort() + // streaks: consecutive active days; the current one may end yesterday + let longest = 0, run = 0, prev = null + for (const k of keys) { + run = prev && (parseDay(k) - parseDay(prev)) === 86400000 ? run + 1 : 1 + longest = Math.max(longest, run); prev = k + } + let current = 0 + const t = parseDay(actData.today) + const d = new Date(t) + if (!nActive(dayKey(d))) d.setDate(d.getDate() - 1) + while (nActive(dayKey(d))) { current++; d.setDate(d.getDate() - 1) } + const best = keys.reduce((b, k) => (nActive(k) > (b ? nActive(b) : 0) ? k : b), null) + document.getElementById('acKpis').innerHTML = ` +
Aktive Tage
${keys.length}
im letzten Jahr
+
Aktuelle Serie
${current} ${current === 1 ? 'Tag' : 'Tage'}
am Stück mit Arbeit
+
Längste Serie
${longest} ${longest === 1 ? 'Tag' : 'Tage'}
im letzten Jahr
+
Vollster Tag
${best ? `${nActive(best)} Projekte` : '–'}
${best ? parseDay(best).toLocaleDateString('de-DE') : ''}
` + document.getElementById('acPending').textContent = actData.pending ? `· ${actData.pending} Projekte werden noch gelesen…` : '' + document.getElementById('acLegend').innerHTML = `weniger${[0, 1, 2, 3, 4].map((l) => ``).join('')}mehr aktive Projekte` + const heat = document.getElementById('acHeat') + heat.innerHTML = heatGrid(53, (k) => levelOf(nActive(k)), (k) => `${fmtDay(k)}: ${nActive(k)} Projekte`) + heat.querySelector(`[data-day="${actDay}"]`)?.classList.add('sel') + // start scrolled to the newest weeks on narrow screens + heat.parentElement.scrollLeft = heat.parentElement.scrollWidth + renderActDay() + renderActTop() +} + +function actRow(p, meta) { + return `` +} +const actMeta = (files, commits) => [files ? `${files} ${files === 1 ? 'Datei' : 'Dateien'}` : '', commits ? `${commits} ${commits === 1 ? 'Commit' : 'Commits'}` : ''].filter(Boolean).join(' · ') + +function renderActDay() { + const e = actData.days[actDay] + document.getElementById('acDayTitle').textContent = fmtDay(actDay) + document.getElementById('acDay').innerHTML = e?.projects.length + ? `
${e.projects.map((p) => actRow(p.name, actMeta(p.files, p.commits))).join('')}
` + : '
An diesem Tag wurde nichts geändert.
' +} + +function renderActTop() { + const since = parseDay(actData.today); since.setDate(since.getDate() - actRange + 1) + const agg = new Map() + for (const [k, e] of Object.entries(actData.days)) { + if (parseDay(k) < since) continue + for (const p of e.projects) { + const a = agg.get(p.name) ?? { days: 0, files: 0, commits: 0, last: k } + a.days++; a.files += p.files; a.commits += p.commits; if (k > a.last) a.last = k + agg.set(p.name, a) + } + } + const list = [...agg].sort((a, b) => b[1].days - a[1].days || b[1].last.localeCompare(a[1].last)).slice(0, 15) + document.getElementById('acTop').innerHTML = list.length + ? `
${list.map(([n, a]) => actRow(n, `${a.days} ${a.days === 1 ? 'Tag' : 'Tage'} · zuletzt ${timeAgo(parseDay(a.last).toISOString())}`)).join('')}
` + : '
In diesem Zeitraum keine Änderungen.
' +} + +const acHeat = document.getElementById('acHeat') +const acTip = document.getElementById('acTip') +acHeat.addEventListener('click', (e) => { + const c = e.target.closest('.hc:not(.future)') + if (!c) return + actDay = c.dataset.day + for (const x of acHeat.querySelectorAll('.hc.sel')) x.classList.remove('sel') + c.classList.add('sel') + renderActDay() +}) +acHeat.addEventListener('mousemove', (e) => { + const c = e.target.closest('.hc:not(.future)') + if (!c) { acTip.hidden = true; return } + const ev = actData.days[c.dataset.day] + acTip.innerHTML = `${escapeHtml(fmtDay(c.dataset.day))}
aktive Projekte${ev?.projects.length ?? 0}
` + + (ev ? `
Dateien / Commits${ev.files} / ${ev.commits}
` + ev.projects.slice(0, 4).map((p) => `
${escapeHtml(p.name)}${actMeta(p.files, p.commits)}
`).join('') : '') + acTip.hidden = false + const card = acHeat.closest('.stcard').getBoundingClientRect() + let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14 + if (x + acTip.offsetWidth > card.width - 8) x = e.clientX - card.left - acTip.offsetWidth - 14 + acTip.style.left = `${x}px`; acTip.style.top = `${y}px` +}) +acHeat.addEventListener('mouseleave', () => { acTip.hidden = true }) +for (const id of ['acDay', 'acTop']) { + document.getElementById(id).addEventListener('click', (e) => { + const b = e.target.closest('[data-proj]') + const p = b && projects.find((x) => x.name === b.dataset.proj) + if (p) openEditor(p) + }) +} +for (const b of document.querySelectorAll('#acRange button')) b.onclick = () => { + actRange = +b.dataset.range + for (const x of document.querySelectorAll('#acRange button')) x.classList.toggle('active', x === b) + renderActTop() +} + +// small heatmap (26 weeks) in a project's Info tab +async function loadProjectActivity(name) { + const box = document.getElementById('actMini') + let a + try { a = await (await fetch(api(name, 'activity'))).json() } catch { return } + if (!box.isConnected || editing?.name !== name) return + const score = (k) => (a.files?.[k] ?? 0) + (a.commits?.[k] ?? 0) * 5 + // 0 · 1–4 · 5–19 · 20–59 · 60+ (files + 5 × commits) + const lv = (k) => { const s = score(k); return s <= 0 ? 0 : s < 5 ? 1 : s < 20 ? 2 : s < 60 ? 3 : 4 } + const saved = actData + actData = { today: a.today, days: {} } // heatGrid reads "today" from here + box.innerHTML = `
${heatGrid(26, lv, (k) => `${fmtDay(k)}: ${actMeta(a.files?.[k] ?? 0, a.commits?.[k] ?? 0) || 'nichts'}`)}
` + actData = saved + for (const c of box.querySelectorAll('.hc:not(.future)')) c.title = c.getAttribute('aria-label') + const days = new Set([...Object.keys(a.files ?? {}), ...Object.keys(a.commits ?? {})]) + const cut = new Date(); cut.setDate(cut.getDate() - 182) + const n = [...days].filter((k) => parseDay(k) >= cut).length + document.getElementById('actMiniInfo').textContent = a.files === null ? 'wird noch gelesen…' : `${n} aktive Tage im letzten halben Jahr` +} + +/* ── storage page: treemap, biggest projects, biggest regenerable folders ─ */ + +let storageData = null +let stPath = [] // [] = all projects · [project] · [project, folder] +let stSelected = new Set() +const TIER_KEYS = ['Cache', 'Release', 'Output'] +const TIER_SHORT = { Cache: 'Cache', Release: 'Builds', Output: 'Rohbilder' } +const tierVar = (t) => `var(--t-${t.toLowerCase()})` +const fmtMB1 = (mb) => (mb >= 1024 ? `${(mb / 1024).toLocaleString('de-DE', { maximumFractionDigits: mb >= 10240 ? 0 : 1 })} GB` : `${Math.round(mb).toLocaleString('de-DE')} MB`) + +async function loadStorage() { + try { storageData = await (await fetch('/api/storage')).json() } catch { return } + // a project that went away (folder switch, rename) leaves the drill-down + if (stPath.length && !storageData.projects.some((p) => p.name === stPath[0])) stPath = [] + renderStorage() +} + +function renderStorage() { + if (!storageData) return + renderStorageKpis() + renderTreemap() + renderStorageTop() + renderHogs() +} + +function renderStorageKpis() { + const ps = storageData.projects + const scanned = ps.filter((p) => p.sizeMB != null) + const total = scanned.reduce((s, p) => s + p.sizeMB, 0) + const del = { Cache: 0, Release: 0, Output: 0 } + for (const p of scanned) for (const t of TIER_KEYS) del[t] += p.deletable?.[t] ?? 0 + const delAll = del.Cache + del.Release + del.Output + const oldest = scanned.reduce((o, p) => (!o || p.at < o ? p.at : o), null) + const scan = storageData.scan + const bar = TIER_KEYS.filter((t) => del[t] > 0).map((t) => ``).join('') + + (total > delAll ? `` : '') + document.getElementById('stKpis').innerHTML = ` +
Belegt
${fmtMB1(total)}
${scanned.length} Projekte gemessen
+
Aufräumbar
${fmtMB1(delAll)}
+ +
${TIER_KEYS.map((t) => `${TIER_SHORT[t]} ${fmtMB1(del[t])}`).join('')}
+
Anteil aufräumbar
${total ? Math.round((delAll / total) * 100) : 0} %
vom belegten Platz
+
Gemessen
${scanned.length} / ${ps.length}
+
${scan?.running ? `${ic('loader', 'sm')} läuft: ${scan.done}/${scan.total}` : oldest ? `ältester Stand ${timeAgo(oldest)}` : 'noch nichts gemessen'}
+
` + document.getElementById('stScanAll').onclick = () => startScan() +} + +// Squarified treemap (Bruls et al.): items sorted by value, laid out in rows +// along the shorter side so tiles stay close to square. -> [{ item, x, y, w, h }] +function squarify(items, x, y, w, h) { + const out = [] + const total = items.reduce((s, it) => s + it.value, 0) + if (!total || w <= 0 || h <= 0) return out + const scale = (w * h) / total + let rest = items.map((it) => ({ it, a: it.value * scale })).filter((r) => r.a > 0) + const worst = (row, side) => { + const s = row.reduce((t, r) => t + r.a, 0) + let max = 0, min = Infinity + for (const r of row) { max = Math.max(max, r.a); min = Math.min(min, r.a) } + return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min)) + } + while (rest.length) { + const side = Math.min(w, h) + const row = [rest[0]] + let i = 1 + while (i < rest.length && worst([...row, rest[i]], side) <= worst(row, side)) row.push(rest[i++]) + rest = rest.slice(i) + const s = row.reduce((t, r) => t + r.a, 0) + if (w >= h) { // column on the left + const cw = s / h + let cy = y + for (const r of row) { const rh = r.a / cw; out.push({ item: r.it, x, y: cy, w: cw, h: rh }); cy += rh } + x += cw; w -= cw + } else { // row on top + const rh = s / w + let cx = x + for (const r of row) { const rw = r.a / rh; out.push({ item: r.it, x: cx, y, w: rw, h: rh }); cx += rw } + y += rh; h -= rh + } + } + return out +} + +// cleanup info for a path inside a project (rel = "Library" or "android\app") +function tierInfo(p, rel) { + const full = rel ? `${p.folder}\\${rel}` : p.folder + const exact = p.candidates.find((c) => !c.skip && c.path.toLowerCase() === full.toLowerCase()) + const inside = { Cache: 0, Release: 0, Output: 0 } + const pre = (full + '\\').toLowerCase() + for (const c of p.candidates) if (!c.skip && c.path.toLowerCase().startsWith(pre)) inside[c.tier] += c.mb + return { tier: exact?.tier ?? null, inside } +} +const dlStrip = (inside, totalMB) => { + const segs = TIER_KEYS.filter((t) => inside[t] > 0) + if (!segs.length || !totalMB) return '' + // strip width = share of the tile that can go + const share = Math.min(1, segs.reduce((s, t) => s + inside[t], 0) / totalMB) + return `
${segs.map((t) => ``).join('')}
` +} + +function renderTreemap() { + const box = document.getElementById('stTree') + const W = box.clientWidth, H = box.clientHeight + const ps = storageData.projects + const proj = stPath.length ? ps.find((p) => p.name === stPath[0]) : null + const crumbs = [``] + if (proj) crumbs.push(`›${stPath.length > 1 ? `` : `${escapeHtml(proj.name)}`}`) + if (stPath.length > 1) crumbs.push(`›${escapeHtml(stPath[1])}`) + if (proj) crumbs.push(``) + document.getElementById('stCrumbs').innerHTML = crumbs.join('') + document.getElementById('stLegend').innerHTML = TIER_KEYS.map((t) => `${TIER_SHORT[t]}`).join('') + 'Rest' + + let html = '' + const tile = (r, cls, label, sub, attrs, extra = '') => { + const big = r.w > 46 && r.h > 30 + return `
+ ${big ? `${escapeHtml(label)}${r.h > 44 ? `${sub}` : ''}` : ''}${extra}
` + } + + if (!proj) { + const items = ps.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).map((p) => ({ value: p.sizeMB, p })) + if (!items.length) { box.innerHTML = `
Noch nichts gemessen – oben „Alle messen“.
`; return } + const draw = (list, x, y, w, h) => squarify(list, x, y, w, h).map((r) => { + const p = r.item.p + const inside = { Cache: p.deletable?.Cache ?? 0, Release: p.deletable?.Release ?? 0, Output: p.deletable?.Output ?? 0 } + return tile(r, '', p.name, fmtMB1(p.sizeMB), `data-proj="${escapeHtml(p.name)}"`, dlStrip(inside, p.sizeMB)) + }).join('') + const groups = multiRoot() ? roots.filter((rt) => activeRoots.includes(rt.id)).map((rt) => ({ rt, list: items.filter((i) => i.p.root === rt.id) })).filter((g) => g.list.length) : [] + if (groups.length > 1) { + // one block per projects folder, with its name on top + for (const g of squarify(groups.map((g) => ({ value: g.list.reduce((s, i) => s + i.value, 0), g })), 0, 0, W, H)) { + html += `
${escapeHtml(g.item.g.rt.name)} · ${fmtMB1(g.item.value)}
` + html += draw(g.item.g.list, g.x + 2, g.y + 18, g.w - 4, g.h - 20) + } + } else html = draw(items, 0, 0, W, H) + } else { + const level = stPath.length > 1 ? proj.tree?.find((c) => c.name === stPath[1])?.children : proj.tree + if (!level?.length) { + box.innerHTML = `
${proj.sizeMB == null ? 'Dieses Projekt wurde noch nicht gemessen.' : 'Für die Aufteilung nach Ordnern das Projekt neu messen.'}

+
` + document.getElementById('stScanOne').onclick = () => startScan(proj.name) + return + } + const items = level.filter((c) => c.mb > 0).map((c) => ({ value: c.mb, c })) + html = squarify(items, 0, 0, W, H).map((r) => { + const c = r.item.c + const rel = stPath.length > 1 ? `${stPath[1]}\\${c.name}` : c.name + const info = c.files || c.merged ? { tier: null, inside: { Cache: 0, Release: 0, Output: 0 } } : tierInfo(proj, rel) + const drill = stPath.length === 1 && c.children?.length > 1 + const cls = `${info.tier ? `t-${info.tier}` : ''} ${drill ? '' : 'flat'}` + return tile(r, cls, c.name, fmtMB1(c.mb), `data-rel="${escapeHtml(rel)}" data-name="${escapeHtml(c.name)}" ${drill ? 'data-drill' : ''}`, info.tier ? '' : dlStrip(info.inside, c.mb)) + }).join('') + } + box.innerHTML = html +} + +// tooltip + clicks on the treemap +const stTree = document.getElementById('stTree') +const stTip = document.getElementById('stTip') +stTree.addEventListener('mousemove', (e) => { + const t = e.target.closest('.tm') + if (!t) { stTip.hidden = true; return } + const ps = storageData?.projects ?? [] + let html = '' + if (t.dataset.proj) { + const p = ps.find((x) => x.name === t.dataset.proj) + const d = p.deletable ?? {} + html = `${escapeHtml(p.name)}
Größe${fmtMB1(p.sizeMB)}
` + + TIER_KEYS.filter((k) => d[k] > 0).map((k) => `
${TIER_SHORT[k]}${fmtMB1(d[k])}
`).join('') + + (multiRoot() ? `
Ordner${escapeHtml(p.rootName)}
` : '') + + `
gemessen${timeAgo(p.at)}
` + } else { + const proj = ps.find((x) => x.name === stPath[0]) + const level = stPath.length > 1 ? proj.tree.find((c) => c.name === stPath[1]).children : proj.tree + const c = level.find((x) => x.name === t.dataset.name) + const info = c.files || c.merged ? null : tierInfo(proj, t.dataset.rel) + html = `${escapeHtml(t.dataset.rel)}
Größe${fmtMB1(c.mb)}
` + + (info?.tier ? `
Löschbar${TIER_SHORT[info.tier]}
` : '') + + (info ? TIER_KEYS.filter((k) => info.inside[k] > 0).map((k) => `
darin ${TIER_SHORT[k]}${fmtMB1(info.inside[k])}
`).join('') : '') + + (t.hasAttribute('data-drill') ? '
Klick: Unterordner
' : '') + } + stTip.innerHTML = html + stTip.hidden = false + const card = stTree.parentElement.getBoundingClientRect() + let x = e.clientX - card.left + 14, y = e.clientY - card.top + 14 + if (x + stTip.offsetWidth > card.width - 8) x = e.clientX - card.left - stTip.offsetWidth - 14 + if (y + stTip.offsetHeight > card.height - 8) y = e.clientY - card.top - stTip.offsetHeight - 14 + stTip.style.left = `${x}px`; stTip.style.top = `${y}px` +}) +stTree.addEventListener('mouseleave', () => { stTip.hidden = true }) +const stDrill = (t) => { + if (!t) return + if (t.dataset.proj) stPath = [t.dataset.proj] + else if (t.hasAttribute('data-drill')) stPath = [stPath[0], t.dataset.name] + else return + stTip.hidden = true + renderTreemap() +} +stTree.addEventListener('click', (e) => stDrill(e.target.closest('.tm'))) +stTree.addEventListener('keydown', (e) => { if (e.key === 'Enter') stDrill(e.target.closest('.tm')) }) +document.getElementById('stCrumbs').addEventListener('click', (e) => { + const b = e.target.closest('button') + if (!b) return + if (b.hasAttribute('data-open')) { const p = projects.find((x) => x.name === stPath[0]); if (p) { openEditor(p); setSection?.('info') } return } + stPath = stPath.slice(0, +b.dataset.crumb) + renderTreemap() +}) +new ResizeObserver(() => { if (activeView === 'storage' && storageData) renderTreemap() }).observe(stTree) + +function renderStorageTop() { + const top = storageData.projects.filter((p) => p.sizeMB > 0).sort((a, b) => b.sizeMB - a.sizeMB).slice(0, 10) + const max = top[0]?.sizeMB ?? 1 + document.getElementById('stTop').innerHTML = top.length ? `
${top.map((p) => { + const d = p.deletable ?? {} + const del = TIER_KEYS.reduce((s, t) => s + (d[t] ?? 0), 0) + const segs = TIER_KEYS.filter((t) => d[t] > 0).map((t) => ``).join('') + + (p.sizeMB > del ? `` : '') + return `` + }).join('')}
` : '
Noch nichts gemessen.
' +} +document.getElementById('stTop').addEventListener('click', (e) => { + const b = e.target.closest('[data-proj]') + if (!b) return + stPath = [b.dataset.proj] + renderTreemap() + document.getElementById('stTree').scrollIntoView({ block: 'nearest', behavior: 'smooth' }) +}) + +// global list of regenerable folders, biggest first +function renderHogs() { + const can = storageData.cleanupAvailable + const rows = storageData.projects.flatMap((p) => p.candidates.filter((c) => !c.skip).map((c) => ({ ...c, p }))) + .sort((a, b) => b.mb - a.mb).slice(0, 30) + const keyOf = (r) => `${r.p.name}|${r.path}` + // first render: Cache preselected (always regenerable) + if (!renderHogs.done) { for (const r of rows) if (r.tier === 'Cache') stSelected.add(keyOf(r)); renderHogs.done = true } + for (const k of [...stSelected]) if (!rows.some((r) => keyOf(r) === k)) stSelected.delete(k) + document.getElementById('stHogs').innerHTML = rows.length + ? `${can ? '' : ''}ProjektOrdnerArtGröße + ${rows.map((r) => ` + ${can ? `` : ''} + ${escapeHtml(r.p.name)} + ${escapeHtml(inProject(r.path))} + ${TIER_SHORT[r.tier]} + ${fmtMB1(r.mb)}`).join('')}` + : 'Nichts zum Aufräumen gefunden (oder noch nicht gemessen).' + updateHogSel(rows) + renderHogs.rows = rows +} +function updateHogSel(rows = renderHogs.rows ?? []) { + const sel = rows.filter((r) => stSelected.has(`${r.p.name}|${r.path}`)) + const mb = sel.reduce((s, r) => s + r.mb, 0) + document.getElementById('stSel').textContent = sel.length ? `${sel.length} ausgewählt · ${fmtMB1(mb)}` : storageData?.cleanupAvailable ? '' : 'Löschen braucht cleanup.ps1' + document.getElementById('stDelete').disabled = !sel.length +} +document.getElementById('stHogs').addEventListener('click', (e) => { + const tr = e.target.closest('tr[data-k]') + if (!tr || !storageData?.cleanupAvailable) return + const cb = tr.querySelector('input') + if (e.target !== cb) cb.checked = !cb.checked + if (cb.checked) stSelected.add(tr.dataset.k); else stSelected.delete(tr.dataset.k) + updateHogSel() +}) +document.getElementById('stDelete').onclick = async () => { + const sel = (renderHogs.rows ?? []).filter((r) => stSelected.has(`${r.p.name}|${r.path}`)) + if (!sel.length) return + const mb = sel.reduce((s, r) => s + r.mb, 0) + if (!confirm(`${sel.length} Ordner (${fmtMB1(mb)}) endgültig löschen?\n\n${sel.map((r) => `${r.p.name}: ${inProject(r.path)}`).join('\n')}\n\nSie lassen sich neu erzeugen (npm install, Build …).`)) return + const btn = document.getElementById('stDelete') + btn.disabled = true + btn.innerHTML = `${ic('loader')}Lösche…` + const byProject = new Map() + for (const r of sel) byProject.set(r.p.name, [...(byProject.get(r.p.name) ?? []), r.path]) + let failed = 0 + for (const [name, paths] of byProject) { + try { await postJson(api(name, 'clean'), { paths }) } catch (e) { failed++; toast(`${name}: ${e.message}`, 'triangle-alert') } + } + stSelected.clear() + btn.innerHTML = `${ic('trash')}Ausgewählte löschen` + if (!failed) toast(`${fmtMB1(mb)} freigegeben`, 'brush-cleaning') + await loadStorage() + load() } /* ── tasks view (all projects) ────────────────────────────────────────── */ @@ -1212,13 +1974,56 @@ function renderInfo(name, d) { } storageBody += `
` + // release archive: ZIP of a build folder (or the whole project) into \releases + const folder = editing?.folder ?? name + const releaseCands = new Set((s?.candidates ?? []).filter((c) => c.Tier === 'Release' && !c.Skip).map((c) => inProject(c.Path).toLowerCase())) + const rd = d.releaseDirs ?? [] + const arcs = d.archives ?? [] + const archiveBody = ` +
+ + +
+ +
Landet in ${escapeHtml(folder)}\\releases\\ mit Datum im Namen${rd.length ? '' : ' – kein Build-Ordner gefunden (dist, builds, release, publish …)'}.
+ ${arcs.length ? `
${arcs.slice(0, 8).map((a) => `
${new Date(a.at).toLocaleDateString('de-DE')}
${escapeHtml(a.name)} · ${fmtMB(a.mb)}
`).join('')}
` : ''} +
` + 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` : ''}
`) + + `

${ic('activity')}Aktivität

wird geladen…
` + section('hard-drive', 'Speicher', storageBody) + + section('file-archive', 'Release archivieren (ZIP)', archiveBody) + section('wand-sparkles', 'Generator', genBody) + section('image', 'App-Icon', iconBody) + loadProjectActivity(name) + const arcSel = document.getElementById('arcWhat') + const syncArc = () => { document.getElementById('arcDelWrap').style.display = arcSel.selectedOptions[0]?.dataset.del ? '' : 'none' } + arcSel.onchange = syncArc + syncArc() + document.getElementById('btnArc').onclick = async (e) => { + const btn = e.currentTarget + const what = arcSel.value + const del = document.getElementById('arcDel').checked && !!arcSel.selectedOptions[0]?.dataset.del + if (del && !confirm(`ZIP von „${what}“ erstellen und den Ordner danach löschen?`)) return + btn.disabled = true + btn.innerHTML = `${ic('loader')}Packe…` + try { + const r = await postJson(api(name, 'archive'), { what, deleteAfter: del }) + toast(`${r.name} (${fmtMB(r.mb)})${r.deleted ? ' – Build-Ordner gelöscht' : ''}`, 'file-archive') + loadDetails(name) + if (r.deleted) load() + } catch (ex) { + toast(ex.message, 'triangle-alert') + btn.disabled = false + btn.innerHTML = `${ic('file-archive')}ZIP erstellen` + } + } + document.getElementById('btnArcOpen').onclick = () => postJson(api(name, 'archive/open')).catch((ex) => toast(ex.message, 'triangle-alert')) + 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) } @@ -1509,9 +2314,14 @@ document.addEventListener('click', (e) => { async function loadBackup() { const wasBusy = backupBusy() + const wasAuto = backup?.auto try { backup = await (await fetch('/api/backup')).json() } catch { return } - if (wasBusy && !backupBusy()) load() // refresh the backup badges on cards/tiles/list + if (wasBusy && !backupBusy()) { + load() // refresh the backup badges on cards/tiles/list + if (wasAuto) toast(backup.phase === 'done' ? 'Automatisches Backup fertig' : `Automatisches Backup: ${backup.error ?? 'abgebrochen'}`, backup.phase === 'done' ? 'circle-check' : 'triangle-alert') + } else if (!wasBusy && backupBusy() && backup.auto) toast('Automatisches Backup läuft …', 'hard-drive-upload') renderBackupButton() + if (document.getElementById('spanel').classList.contains('open')) renderAutoStatus() if (document.getElementById('bpanel').classList.contains('open')) renderBackup() if (editing) { const own = curTarget()?.lastByProject?.[editing.name] @@ -1531,14 +2341,26 @@ function renderBackupButton() { const t = curTarget() const last = t?.last const prefix = backup.targets.length > 1 ? `· ${t.name} ` : '· ' - if (backup.phase === 'checking') sub.textContent = '· prüft…' + if (backup.phase === 'checking') sub.textContent = backup.auto ? '· auto: prüft…' : '· 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)}` + sub.textContent = `· ${backup.auto ? 'auto ' : ''}${pr.bytesTotal ? Math.round((pr.bytes / pr.bytesTotal) * 100) : 0} %` + } else if (dueCount()) sub.textContent = `· ${dueCount()} fällig` + 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) + const old = last && (Date.now() - new Date(last.at)) > BACKUP_FRESH_DAYS * 86400000 + sub.classList.toggle('warn', !last || old || last.ok === false || dueCount() > 0) + if (dueCount()) btn.title += `\n\n${dueCount()} Projekte seit dem letzten Backup geändert (älter als ${BACKUP_FRESH_DAYS} Tage) – Filter „Backup fällig“` +} +const dueCount = () => projects.filter(backupDue).length + +// once a day: a hint when backups are due +function remindBackup() { + const n = dueCount() + if (!n || backup?.notConfigured || backupBusy()) return + const today = new Date().toISOString().slice(0, 10) + try { if (localStorage.getItem('dash.backupReminded') === today) return; localStorage.setItem('dash.backupReminded', today) } catch {} + toast(`Backup fällig: ${n} ${n === 1 ? 'Projekt wurde' : 'Projekte wurden'} seit dem letzten Backup geändert – oben auf „Backup“ klicken`, 'clock-alert') } async function backupAction(what) { @@ -1695,7 +2517,7 @@ document.addEventListener('keydown', (e) => { // 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'] +const VIEWS = ['board', 'gallery', 'list', 'tasks', 'storage', 'activity'] initTheme() if (VIEWS.includes(hashView)) setView(hashView) else try { const v = localStorage.getItem('dash.view'); if (VIEWS.includes(v)) setView(v) } catch {} @@ -1705,6 +2527,8 @@ function openFromHash(project, sec) { } load().then(() => { openFromHash(hashProject, hashSec); if (hashView === 'backup') openBackup() }) loadBackup() +// an automatic backup can start any time: look once a minute (while busy, loadBackup polls every second) +setInterval(() => { if (!backupBusy()) loadBackup() }, 60000) window.addEventListener('hashchange', () => { const [v, project, sec] = decodeURIComponent(location.hash.slice(1)).split('/') if (VIEWS.includes(v)) { setView(v); render() } diff --git a/public/index.html b/public/index.html index ba1f264..de1f64b 100644 --- a/public/index.html +++ b/public/index.html @@ -16,6 +16,10 @@ --shadow: 0 1px 2px rgba(16,24,40,.05), 0 1px 3px rgba(16,24,40,.06); --shadow-lg: 0 12px 32px rgba(16,24,40,.14); --radius: 12px; + /* storage page: what a folder is (validated categorical slots blue/orange/aqua) */ + --t-cache: #eb6834; --t-release: #2a78d6; --t-output: #1baf7a; --t-rest: #e7eaf1; --t-rest-ink: #151823; + /* activity heatmap: one hue, near-zero recedes to the surface */ + --h0: #eef0f4; --h1: #b7d3f6; --h2: #6da7ec; --h3: #2a78d6; --h4: #184f95; color-scheme: light; } :root[data-theme="dark"] { @@ -26,6 +30,8 @@ --red: #f87171; --red-soft: #3b1717; --blue: #60a5fa; --blue-soft: #172a4a; --violet: #a78bfa; --violet-soft: #2a1f47; --cyan: #67e8f9; --cyan-soft: #0f2e35; --shadow: 0 1px 2px rgba(0,0,0,.3); --shadow-lg: 0 16px 40px rgba(0,0,0,.5); + --t-cache: #d95926; --t-release: #3987e5; --t-output: #199e70; --t-rest: #272c39; --t-rest-ink: #e8eaf1; + --h0: #1e222d; --h1: #104281; --h2: #256abf; --h3: #3987e5; --h4: #86b6ef; color-scheme: dark; } * { box-sizing: border-box; } @@ -45,6 +51,10 @@ .brand .logo { width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center; color: #fff; background: linear-gradient(135deg, var(--accent), var(--accent-2)); box-shadow: 0 4px 12px rgba(99,102,241,.35); } .brand h1 { font-size: 17px; margin: 0; letter-spacing: -.01em; } .brand .count { color: var(--muted); font-size: 12px; } + .updbanner { display: flex; align-items: center; gap: 10px; padding: 8px 22px; background: var(--accent-soft); color: var(--accent-text); font-size: 13px; border-top: 1px solid var(--border); } + .updbanner[hidden] { display: none; } + .updbanner span { flex: 1; min-width: 0; } + .updbanner .btn { padding: 5px 12px; } .rootpick { position: relative; } #rootBtn { display: flex; align-items: center; gap: 5px; border: none; background: none; padding: 2px 6px; margin: -2px -6px; border-radius: 7px; cursor: pointer; max-width: 260px; } #rootBtn h1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -63,7 +73,8 @@ .rootmenu .rmbox[aria-checked="true"] { color: var(--accent-text); } .rootmenu .rmbox .i { width: 16px; height: 16px; } .rtag { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--muted); background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 0 5px; margin-left: 6px; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } - .card .sub .rtag { margin-left: 0; } + .card .rootline { margin-top: 6px; } + .card .rootline .rtag { margin-left: 0; max-width: 100%; } .rootmenu .sep { height: 1px; background: var(--border); margin: 5px 2px; } .seg { display: flex; gap: 2px; background: var(--surface-2); padding: 3px; border-radius: 10px; border: 1px solid var(--border); } .seg button { border: none; background: none; padding: 6px 12px; border-radius: 7px; font-size: 13px; font-weight: 600; color: var(--muted); cursor: pointer; display: flex; align-items: center; gap: 6px; } @@ -273,6 +284,94 @@ .toolbar { padding: 10px 22px 0; } main { flex: 1 1 auto; min-height: 0; padding: 10px 22px 14px; overflow: hidden; container-type: inline-size; container-name: main; } .view.active { height: 100%; } + /* activity page */ + #activity.active { overflow-y: auto; overflow-x: hidden; padding-right: 4px; } + .heatscroll { overflow-x: auto; padding-bottom: 4px; } + .heat { display: grid; grid-template-columns: 26px repeat(53, 13px); grid-template-rows: 16px repeat(7, 13px); gap: 3px; width: max-content; font-size: 10px; color: var(--muted); } + .heat .ml { grid-row: 1; white-space: nowrap; } + .heat .dl { grid-column: 1; line-height: 13px; } + .hc { width: 13px; height: 13px; border-radius: 3px; background: var(--h0); cursor: pointer; padding: 0; border: none; } + .hc[data-l="1"] { background: var(--h1); } .hc[data-l="2"] { background: var(--h2); } .hc[data-l="3"] { background: var(--h3); } .hc[data-l="4"] { background: var(--h4); } + .hc.future { visibility: hidden; } + .hc:hover, .hc:focus-visible { outline: 2px solid var(--text); outline-offset: 1px; } + .hc.sel { outline: 2px solid var(--accent); outline-offset: 1px; } + .hleg { display: inline-flex; gap: 3px; align-items: center; } + .hleg .hc { cursor: default; width: 11px; height: 11px; } + .acgrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } + @container main (max-width: 900px) { .acgrid { grid-template-columns: 1fr; } } + .aclist { display: flex; flex-direction: column; gap: 2px; } + .aclist button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; border: none; background: none; padding: 6px 8px; margin: 0 -8px; border-radius: 7px; cursor: pointer; text-align: left; font: inherit; color: inherit; } + .aclist button:hover { background: var(--surface-2); } + .aclist b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .aclist .m { font-size: 12px; color: var(--muted); white-space: nowrap; font-variant-numeric: tabular-nums; } + .hmini { overflow-x: auto; overflow-y: hidden; } + /* the Info card sits on surface-2 - empty days need a step that stays visible there */ + .hmini .hc[data-l="0"] { background: var(--surface-3); } + .hmini .heat { grid-template-columns: 22px repeat(26, 11px); grid-template-rows: 14px repeat(7, 11px); gap: 2px; } + .hmini .hc { width: 11px; height: 11px; border-radius: 2px; cursor: default; } + .hmini .dl { line-height: 11px; } + /* storage page */ + #storage.active { overflow-y: auto; overflow-x: hidden; padding-right: 4px; } + body.view-wide .kpis, body.view-wide .toolbar { display: none; } + .stwrap { display: flex; flex-direction: column; gap: 12px; padding-bottom: 8px; } + .stkpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; } + .stkpi { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; box-shadow: var(--shadow); min-width: 0; display: flex; flex-direction: column; gap: 6px; } + .stkpi .lbl { font-size: 12px; color: var(--muted); } + .stkpi .val { font-size: 22px; font-weight: 700; letter-spacing: -.01em; } + .stkpi .sub { font-size: 12px; color: var(--muted); display: flex; gap: 10px; flex-wrap: wrap; } + .stkpi .btn { align-self: flex-start; } + .stbar { display: flex; height: 8px; border-radius: 4px; overflow: hidden; background: var(--surface-3); gap: 2px; } + .stbar > span { display: block; height: 100%; min-width: 2px; } + .stgrid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 12px; } + @container main (max-width: 1100px) { .stgrid { grid-template-columns: 1fr; } .stkpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + .stcard { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; box-shadow: var(--shadow); min-width: 0; position: relative; } + .sthead { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; } + .sth { margin: 0; font-size: 14px; display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; } + .stside .sth { margin-bottom: 10px; } + .stcrumbs { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 13px; font-weight: 600; min-width: 0; flex: 1; } + .stcrumbs button { border: none; background: none; padding: 3px 6px; border-radius: 6px; color: var(--accent-text); cursor: pointer; font: inherit; } + .stcrumbs button:hover { background: var(--surface-2); } + .stcrumbs .cur { padding: 3px 6px; } + .stcrumbs .sep { color: var(--muted); } + .stlegend { display: flex; gap: 12px; flex-wrap: wrap; font-size: 12px; color: var(--muted); } + .stlegend span { display: inline-flex; align-items: center; gap: 5px; } + .stlegend i, .sttier i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } + .treemap { position: relative; height: clamp(320px, 52vh, 620px); border-radius: 8px; overflow: hidden; background: var(--surface); } + .tm { position: absolute; box-sizing: border-box; border: 1px solid var(--surface); border-radius: 4px; overflow: hidden; background: var(--t-rest); color: var(--t-rest-ink); cursor: pointer; padding: 6px 7px; display: flex; flex-direction: column; gap: 1px; transition: filter .12s; } + .tm:hover, .tm:focus-visible { filter: brightness(1.08); outline: 2px solid var(--accent); outline-offset: -2px; z-index: 2; } + .tm.flat { cursor: default; } + .tm.flat:hover { outline: none; } + .tm.t-Cache { background: var(--t-cache); color: #fff; } + .tm.t-Release { background: var(--t-release); color: #fff; } + .tm.t-Output { background: var(--t-output); color: #fff; } + .tm .n { font-size: 12px; font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .tm .v { font-size: 11px; opacity: .8; white-space: nowrap; font-variant-numeric: tabular-nums; } + .tm .dl { position: absolute; left: 0; right: 0; bottom: 0; display: flex; height: 5px; gap: 2px; } + .tm .dl span { display: block; height: 100%; } + .tmgroup { position: absolute; box-sizing: border-box; border-radius: 6px; } + .tmgroup > .gl { position: absolute; left: 4px; top: 2px; font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; right: 4px; } + .sttip { position: absolute; z-index: 5; pointer-events: none; background: var(--surface); border: 1px solid var(--border-strong); border-radius: 8px; box-shadow: var(--shadow-lg); padding: 8px 10px; font-size: 12px; max-width: 280px; color: var(--text); } + .sttip b { display: block; font-size: 13px; margin-bottom: 2px; overflow-wrap: anywhere; } + .sttip .r { display: flex; justify-content: space-between; gap: 14px; color: var(--muted); } + .sttip .r span:last-child { color: var(--text); font-variant-numeric: tabular-nums; } + .stempty { position: absolute; inset: 0; display: grid; place-items: center; text-align: center; color: var(--muted); font-size: 13px; padding: 20px; } + .sttop { display: flex; flex-direction: column; gap: 8px; } + .sttop button { display: flex; flex-direction: column; gap: 4px; border: none; background: none; padding: 4px 6px; margin: 0 -6px; border-radius: 7px; cursor: pointer; text-align: left; font: inherit; color: inherit; } + .sttop button:hover { background: var(--surface-2); } + .sttop .row { display: flex; justify-content: space-between; gap: 8px; font-size: 13px; } + .sttop .row b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .sttop .row span { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } + .sttop .track { display: flex; height: 8px; gap: 2px; } + .sttop .track span { display: block; height: 100%; border-radius: 0; } + .sttop .track span:first-child { border-radius: 4px 0 0 4px; } + .sttop .track span:last-child { border-radius: 0 4px 4px 0; } + .sttop .track span:only-child { border-radius: 4px; } + .sttop .track .rest { background: var(--border-strong); } + .stdel { display: flex; align-items: center; gap: 10px; margin-left: auto; } + .sttable td.num { font-variant-numeric: tabular-nums; text-align: right; } + .sttable td.path { font-family: "Cascadia Mono", Consolas, ui-monospace, monospace; font-size: 12px; overflow-wrap: anywhere; white-space: normal; } + .sttable input { accent-color: var(--red); } + .sttier { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } #gallery.active { overflow-y: auto; overflow-x: hidden; padding: 2px 4px 8px 2px; } #list.active .tablewrap { max-height: 100%; overflow-y: auto; overflow-x: hidden; } @@ -434,16 +533,13 @@ .hint.warn { color: var(--danger, #c0392b); margin-top: 8px; } /* ── settings panel ─────────────────────────────────────────────────── */ - #spanel { position: fixed; top: 0; right: 0; bottom: 0; width: 560px; max-width: 100vw; background: var(--surface); border-left: 1px solid var(--border); box-shadow: var(--shadow-lg); transform: translateX(100%); transition: transform .22s ease; z-index: 22; display: flex; flex-direction: column; } + #spanel { position: fixed; top: 0; right: 0; bottom: 0; width: 720px; max-width: 100vw; background: var(--surface); border-left: 1px solid var(--border); box-shadow: var(--shadow-lg); transform: translateX(100%); transition: transform .22s ease; z-index: 22; display: flex; flex-direction: column; } #spanel.open { transform: none; } #spanel.setup #btnCloseSettings, #spanel.setup #spCancel { display: none; } .pickrow { display: flex; gap: 6px; } .pickrow input { flex: 1; min-width: 0; } .pickrow .btn { flex: 0 0 auto; } body.no-picker .pickbtn { display: none; } - .trow { display: grid; grid-template-columns: 130px minmax(0, 1fr) auto auto; gap: 6px; margin-bottom: 6px; align-items: center; } - .trow input { min-width: 0; } - body.no-picker .trow { grid-template-columns: 130px minmax(0, 1fr) auto; } .dlg { border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; width: 480px; max-width: calc(100vw - 32px); background: var(--surface); color: var(--text); box-shadow: var(--shadow-lg); } .dlg::backdrop { background: rgba(15, 23, 42, .45); } .dlg select, .dlg > form > input[type=text] { width: 100%; } @@ -451,10 +547,83 @@ .dlg .hint { margin-top: 8px; } body.no-picker #rdPick { display: none; } .dlgfoot { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; } - .rrow { display: grid; grid-template-columns: 130px minmax(0, 1fr) auto auto auto; gap: 6px; margin-bottom: 6px; align-items: center; } - .rrow input { min-width: 0; } - body.no-picker .rrow { grid-template-columns: 130px minmax(0, 1fr) auto auto; } - .rrow.active .tname { border-color: var(--accent); } + /* settings panel: tabs, lists of folders/targets, chips, footer */ + #spanel .phead { padding-bottom: 12px; } + .sptabs { padding: 0 20px 12px; border-bottom: 1px solid var(--border); overflow-x: auto; } + .sptabs .seg { width: max-content; } + .sptabs .tabn { font-size: 10px; background: var(--surface-3); color: var(--muted); padding: 0 6px; border-radius: 9px; line-height: 16px; } + .sptabs .tabn:empty { display: none; } + .sptabs button.active .tabn { background: var(--accent-soft); color: var(--accent-text); } + .sptabs button.has-err { color: var(--red); } + .sptabs button.has-err::after { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--red); } + #spanel .pbody { display: flex; flex-direction: column; gap: 16px; padding-top: 16px; } + .spane { display: flex; flex-direction: column; gap: 12px; } + .spane[hidden] { display: none; } + .sphead h4 { margin: 0; font-size: 14px; } + .sphead p { margin: 2px 0 0; font-size: 12px; color: var(--muted); line-height: 1.45; } + .slist { border: 1px solid var(--border); border-radius: 11px; overflow: hidden; } + .slist:empty { display: none; } + .sitem { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 10px 10px 12px; background: var(--surface); } + .sitem + .sitem { border-top: 1px solid var(--border); } + .sitem:hover { background: var(--surface-2); } + .sitem .fico { width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center; background: var(--surface-2); color: var(--accent-text); border: 1px solid var(--border); } + .sitem:hover .fico { background: var(--surface); } + .sitem .smeta { min-width: 0; display: flex; flex-direction: column; gap: 3px; } + .sitem .snm { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } + .sitem input { border: 1px solid transparent; border-radius: 6px; padding: 1px 5px; margin-left: -6px; background: transparent; min-width: 0; outline: none; } + .sitem .tname { font-weight: 650; font-size: 14px; max-width: 100%; } + .spfield input[type=text], #fImport input[type=text] { width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 13px; background: var(--surface); outline: none; } + .spfield input[type=text]:focus, #fImport input[type=text]:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } + .sitem .tpath { font-family: "Cascadia Mono", Consolas, ui-monospace, monospace; font-size: 12px; color: var(--muted); width: 100%; text-overflow: ellipsis; } + .sitem input:hover { border-color: var(--border); } + .sitem input:focus { border-color: var(--accent); background: var(--surface); box-shadow: 0 0 0 3px var(--accent-soft); color: var(--text); } + .sbadge { font-size: 10.5px; font-weight: 600; padding: 1px 7px; border-radius: 999px; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; } + .sbadge .i { width: 11px; height: 11px; } + .sbadge.main { background: var(--accent-soft); color: var(--accent-text); } + .sbadge.on { background: var(--green-soft); color: var(--green); } + .sbadge.warn { background: var(--yellow-soft); color: var(--yellow); } + .sbadge.ok { background: var(--green-soft); color: var(--green); } + .sstat { font-size: 12px; color: var(--muted); display: flex; gap: 10px; flex-wrap: wrap; } + .sacts { display: flex; gap: 4px; } + .ibtn { width: 30px; height: 30px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface); color: var(--muted); display: grid; place-items: center; cursor: pointer; padding: 0; } + .ibtn:hover { color: var(--accent-text); border-color: var(--accent); } + .ibtn.rm:hover { color: var(--red); border-color: var(--red); } + .ibtn:disabled { opacity: .35; cursor: default; border-color: var(--border); color: var(--muted); } + body.no-picker .ibtn.pickbtn { display: none; } + .spfield { display: flex; flex-direction: column; gap: 6px; } + .spfield > label { font-size: 12px; font-weight: 600; color: var(--muted); } + .remindrow { font-size: 13px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } + .remindrow input { width: 64px; padding: 6px 8px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); font-size: 13px; outline: none; } + .remindrow input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } + .remindrow input[type=time] { width: auto; } + .remindrow > span { display: inline-flex; align-items: center; gap: 6px; } + .remindrow > span[hidden] { display: none; } + .autosel { padding: 6px 8px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); font-size: 13px; outline: none; } + .autosel:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } + .xchips { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: text; } + .xchips:focus-within { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } + .xchip { display: inline-flex; align-items: center; gap: 4px; font-family: "Cascadia Mono", Consolas, ui-monospace, monospace; font-size: 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 7px; padding: 2px 4px 2px 8px; } + .xchip button { border: none; background: none; color: var(--muted); cursor: pointer; display: grid; place-items: center; padding: 2px; border-radius: 4px; } + .xchip button:hover { color: var(--red); background: var(--red-soft); } + .xchips input { border: none; outline: none; background: none; flex: 1; min-width: 14ch; font-size: 12px; font-family: "Cascadia Mono", Consolas, ui-monospace, monospace; padding: 2px; } + details.more { font-size: 12px; color: var(--muted); } + details.more summary { cursor: pointer; display: inline-flex; align-items: center; gap: 5px; color: var(--accent-text); font-weight: 600; list-style: none; } + details.more summary::-webkit-details-marker { display: none; } + details.more > div { margin-top: 6px; padding: 10px 12px; background: var(--surface-2); border-radius: 9px; line-height: 1.55; } + .spstatus { font-size: 13px; padding: 10px 12px; border-radius: 10px; background: var(--surface-2); color: var(--text); display: flex; gap: 8px; align-items: flex-start; line-height: 1.5; } + .spstatus:empty { display: none; } + .spstatus.ok { background: var(--green-soft); color: var(--green); } + .spstatus.err { background: var(--red-soft); color: var(--red); } + .spstatus a { color: inherit; font-weight: 600; } + #spanel .kv { grid-template-columns: 150px minmax(0, 1fr); } + #spError { margin: 0 20px 10px; } + #spanel .pfoot { align-items: center; } + #spanel .pfoot .btn { flex: 0 0 auto; padding: 8px 14px; } + .spdirty { font-size: 12px; color: var(--yellow); display: flex; align-items: center; gap: 6px; visibility: hidden; } + .spdirty::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; } + #spanel.dirty .spdirty { visibility: visible; } + .kbd { font-family: "Cascadia Mono", Consolas, ui-monospace, monospace; font-size: 11px; color: var(--muted); border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 5px; padding: 0 5px; } + @media (max-width: 560px) { .sitem .fico, .kbd { display: none; } .sitem { grid-template-columns: minmax(0, 1fr) auto; } } .rowbtns { display: flex; gap: 6px; flex-wrap: wrap; } .importbox { border: 1px solid var(--border); border-radius: 10px; padding: 10px; margin-top: 8px; background: var(--surface-2); } .importbox[hidden] { display: none; } @@ -523,6 +692,8 @@ + + +
@@ -573,6 +749,54 @@
+
+
+
+
+
+

Aktivität im letzten Jahr

+
+
+
+
Ein Tag zählt, wenn an ihm Dateien zuletzt geändert oder Commits gemacht wurden. Dateien zeigen nur ihre letzte Änderung – Commits ergänzen die Geschichte.
+ +
+
+

Tag

+

Zuletzt aktiv

+
+ +
+
+
+
+
+
+
+
+
+
+
+ +
+
+ + +
+
+

Größte Projekte

+
+
+
+
+
+

Größte Speicherfresser – Ordner, die sich neu erzeugen lassen

+
+
+
+
+
+
@@ -604,6 +828,7 @@ +
@@ -676,51 +901,103 @@

Einstellungen

-
Projektordner und Backup-Ziele
+
Gilt für das ganze Dashboard
-
- + +
+

Umbenennen / verschieben

+
+ + + + + +
Das bisherige Backup bleibt unter dem alten Namen liegen; beim nächsten Backup entsteht der neue Ordner. VS Code, Konsolen und Programme aus dem Projekt vorher schließen.
+ +
+ + +
+
+
+

Neues Projekt

diff --git a/server.js b/server.js index 49b5a41..543646d 100644 --- a/server.js +++ b/server.js @@ -9,6 +9,15 @@ // // 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. +// The process started by the launcher/console only supervises; the real server +// runs as its worker so it can be restarted after an update (lib/supervisor.js). +if (!process.env.DASHBOARD_WORKER) { + require('./lib/supervisor').supervise(__filename) + return +} +// supervisor gone (window closed, killed) → stop too, never left behind +process.on('disconnect', () => process.exit(0)) + const express = require('express') const fs = require('fs') const path = require('path') @@ -23,6 +32,8 @@ const settings = require('./lib/settings') const activity = require('./lib/activity') const itch = require('./lib/itch') const create = require('./lib/create') +const archive = require('./lib/archive') +const scheduler = require('./lib/scheduler') // 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. @@ -323,11 +334,13 @@ app.get('/api/projects', handle(async (req, res) => { roots: s.roots, activeRoot: s.activeRoot, activeRoots: s.activeRoots, + remindDays: s.backup.remindDays ?? 7, 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(), + cleanAvailable: storage.cleanupAvailable(), activityPending: activity.pending(), }) })) @@ -355,6 +368,35 @@ app.post('/api/settings', (req, res) => { res.status(400).json({ error: String(e.message ?? e) }) } }) +// Update detection: newest change of the server code (server.js, lib\*.js) and +// of the page (public\*). The server code is only read at start, so a newer +// file means "restart needed"; the page only needs a reload. +function newestMtime(files) { + let t = 0 + for (const f of files) { try { t = Math.max(t, fs.statSync(f).mtimeMs) } catch {} } + return t +} +const filesIn = (dir, re) => { try { return fs.readdirSync(dir).filter((n) => re.test(n)).map((n) => path.join(dir, n)) } catch { return [] } } +const codeFiles = () => [__filename, ...filesIn(path.join(__dirname, 'lib'), /\.js$/i)] +const uiFiles = () => filesIn(path.join(__dirname, 'public'), /\.(js|html|css)$/i) +const CODE_STAMP = newestMtime(codeFiles()) +const STARTED_AT = new Date().toISOString() +app.get('/api/version', (req, res) => { + res.json({ startedAt: STARTED_AT, pid: process.pid, stale: newestMtime(codeFiles()) > CODE_STAMP, uiStamp: newestMtime(uiFiles()) }) +}) +// Restart the server (lib/supervisor.js starts it again). +app.post('/api/restart', (req, res) => { + if (storage.busy() || backup.busy() || create.busy() || archive.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' }) + res.json({ ok: true }) + setTimeout(() => process.exit(require('./lib/supervisor').RESTART_CODE), 200) +}) + +// Opens the dashboard's data folder (settings, scan.json, backup.json) in Explorer. +app.post('/api/datadir/open', (req, res) => { + fs.mkdirSync(settings.DATA_DIR, { recursive: true }) + openDetached('explorer.exe', [settings.DATA_DIR]) + res.json({ ok: true }) +}) // 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.' }) @@ -388,6 +430,61 @@ app.post('/api/projects/new', handle(async (req, res) => { res.status(400).json({ error: String(e.message ?? e) }) } })) +// ZIP a build folder or the whole project into \releases (lib/archive.js). +// body: { what: relative folder | 'project', deleteAfter } - deleteAfter only for +// folders the cleanup lists as "Release" (finished builds), via cleanup.ps1. +app.post('/api/projects/:name/archive', handle(async (req, res) => { + const key = req.params.name + const ref = resolveProject(key) && projectRef(key) + if (!ref) return res.status(404).json({ error: 'unknown project' }) + const what = String(req.body?.what ?? '') + if (!what) return res.status(400).json({ error: 'Was soll archiviert werden?' }) + let r + try { r = await archive.zip(ref.path, what) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) } + let deleted = false + if (req.body?.deleteAfter && what !== 'project') { + const rel = `${ref.folder}${path.sep}${path.normalize(what)}` + const cand = storage.get(ref.root.path, ref.folder)?.candidates?.find((c) => c.Path.toLowerCase() === rel.toLowerCase() && c.Tier === 'Release' && !c.Skip) + if (cand && !storage.busy()) { + try { await storage.clean(ref.root.path, ref.folder, [cand.Path]); deleted = true } catch {} + } + } + res.json({ ok: true, ...r, deleted, archives: archive.listArchives(ref.path) }) +})) +// Opens \releases in Explorer. +app.post('/api/projects/:name/archive/open', (req, res) => { + const projectPath = resolveProject(req.params.name) + if (!projectPath) return res.status(404).json({ error: 'unknown project' }) + const dir = path.join(projectPath, archive.ARCHIVE_DIR) + fs.mkdirSync(dir, { recursive: true }) + openDetached('explorer.exe', [dir]) + res.json({ ok: true }) +}) +// Rename a project and/or move it into another projects folder (lib/create.js). +// body: { name, root (folder id, default: its own) } +app.post('/api/projects/:name/move', handle(async (req, res) => { + if (storage.busy() || backup.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' }) + const key = req.params.name + const ref = resolveProject(key) && projectRef(key) + if (!ref) return res.status(404).json({ error: 'unknown project' }) + const root = settings.get().roots.find((r) => r.id === (req.body?.root || ref.root.id)) + if (!root || !fs.existsSync(root.path)) return res.status(400).json({ error: 'Projektordner nicht gefunden.' }) + let r + try { + r = await create.move({ from: ref.path, rootPath: root.path, name: req.body?.name }) + } catch (e) { + return res.status(400).json({ error: String(e.message ?? e) }) + } + const newRoot = path.resolve(root.path) + storage.rename(ref.root.path, ref.folder, newRoot, r.name) + thumbCache.delete(key) + quickCache.delete(key) + icons.forget(ref.path) + projectList() + const shown = ROOTS.some((x) => x.id === root.id) + if (shown) activity.warm([r.path]) + res.json({ ok: true, name: r.name, root: root.id, rootName: root.name, shown, key: shown ? keyOf(newRoot, r.name) : r.name }) +})) // 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.' }) @@ -486,6 +583,8 @@ app.get('/api/projects/:name/details', handle(async (req, res) => { program: programInfo(projectPath), path: projectPath, sshKey: sshKey(), + releaseDirs: archive.findReleaseDirs(projectPath), + archives: archive.listArchives(projectPath), }) })) @@ -565,7 +664,6 @@ app.post('/api/projects/:name/git-init', handle(async (req, res) => { // 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' }) @@ -575,6 +673,55 @@ app.post('/api/scan', (req, res) => { app.get('/api/scan', (req, res) => res.json(storage.state)) +// Activity heatmap: per day which projects changed (files by last-change date, +// plus git commits). -> { days: { 'YYYY-MM-DD': { files, commits, projects: [{ name, files, commits }] } }, pending } +async function projectActivity(p) { + const dir = path.join(p.root.path, p.folder) + return { files: activity.filesPerDay(dir), commits: await activity.gitDays(dir) } +} +app.get('/api/activity', handle(async (req, res) => { + const list = projectList() + const acts = await pool(list, 8, projectActivity) + const days = {} + let pending = 0 + list.forEach((p, i) => { + const a = acts[i] + if (a.files === undefined) pending++ + for (const [d, n] of Object.entries(a.files ?? {})) { + const e = (days[d] ??= { files: 0, commits: 0, projects: {} }) + e.files += n + ;(e.projects[p.key] ??= { name: p.key, files: 0, commits: 0 }).files += n + } + for (const [d, n] of Object.entries(a.commits)) { + const e = (days[d] ??= { files: 0, commits: 0, projects: {} }) + e.commits += n + ;(e.projects[p.key] ??= { name: p.key, files: 0, commits: 0 }).commits += n + } + }) + for (const e of Object.values(days)) e.projects = Object.values(e.projects).sort((a, b) => (b.files + b.commits * 5) - (a.files + a.commits * 5)) + res.json({ days, pending, today: activity.dayOf(Date.now()) }) +})) +app.get('/api/projects/:name/activity', handle(async (req, res) => { + const ref = resolveProject(req.params.name) && projectRef(req.params.name) + if (!ref) return res.status(404).json({ error: 'unknown project' }) + const a = await projectActivity(ref) + res.json({ files: a.files ?? null, commits: a.commits, today: activity.dayOf(Date.now()) }) +})) + +// Storage page: every shown project with its scan result (size, split, cleanup candidates). +app.get('/api/storage', (req, res) => { + const list = projectList().map((p) => { + const d = storage.get(p.root.path, p.folder) + return { + name: p.key, folder: p.folder, root: p.root.id, rootName: p.root.name, + sizeMB: d?.sizeMB ?? null, at: d?.at ?? null, deletable: d?.deletable ?? null, + tree: d?.tree ?? null, + candidates: (d?.candidates ?? []).filter((c) => c.MB >= 1).map((c) => ({ path: c.Path, tier: c.Tier, mb: c.MB, skip: !!c.Skip })), + } + }) + res.json({ projects: list, scan: storage.state, cleanupAvailable: storage.cleanupAvailable() }) +}) + // 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) @@ -589,7 +736,7 @@ app.post('/api/projects/:name/clean', handle(async (req, res) => { })) // NAS backup (lib/backup.js): check → copy, never deletes in the backup. -app.get('/api/backup', (req, res) => res.json(backup.getState())) +app.get('/api/backup', (req, res) => res.json({ ...backup.getState(), schedule: scheduler.status() })) // 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 @@ -611,6 +758,7 @@ app.post('/api/backup/cancel', (req, res) => { }) applySettings() +scheduler.start() app.listen(PORT, HOST, () => { console.log(`Project dashboard running at http://${HOST}:${PORT}`)