Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfa5c61db5 | ||
|
|
3c226dab12 | ||
|
|
584cefa388 | ||
|
|
00665592f6 |
@@ -1,2 +1,4 @@
|
|||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
|
web/*/node_modules/
|
||||||
|
web/*/.next/
|
||||||
|
|||||||
@@ -44,3 +44,41 @@ Keine Commits in dieser Session.
|
|||||||
Keine Änderungen ermittelbar.
|
Keine Änderungen ermittelbar.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
## 2026-08-28 21:44 – 21:44 (0m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** nexarch
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- web/shl/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/__tests__/Dialog.test.tsx | 38 ++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/__tests__/tokens.test.ts | 39 +++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Dialog.tsx | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/FormElements.tsx | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Shell.tsx | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Table.tsx | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Toast.tsx | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/i18n/i18n.tsx | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/index.ts | 25 +++++++++++++++++++++++++
|
||||||
|
- web/shl/package.json | 23 +++++++++++++++++++++++
|
||||||
|
- web/shl/theme/ThemeProvider.tsx | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/tokens/tokens.ts | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/tsconfig.json | 18 ++++++++++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-08-28 21:51 – 21:57 (5m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** nexarch
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
- 3c226da SHL-01: fix — vitest jsdom-environment + jest-dom-Setup (3 Dialog-Tests schlugen ohne DOM fehl)
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- web/shl/package.json | 2 ++
|
||||||
|
- web/shl/vitest.config.ts | 8 ++++++++
|
||||||
|
- web/shl/vitest.setup.ts | 1 +
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
version: "2"
|
|
||||||
|
|
||||||
run:
|
|
||||||
timeout: 3m
|
|
||||||
|
|
||||||
linters:
|
|
||||||
default: none
|
|
||||||
enable:
|
|
||||||
- govet
|
|
||||||
- staticcheck
|
|
||||||
- errcheck
|
|
||||||
- unused
|
|
||||||
- ineffassign
|
|
||||||
|
|
||||||
formatters:
|
|
||||||
enable:
|
|
||||||
- gofmt
|
|
||||||
- goimports
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
.PHONY: build lint fmt test check
|
|
||||||
|
|
||||||
build:
|
|
||||||
go build ./...
|
|
||||||
|
|
||||||
lint:
|
|
||||||
golangci-lint run ./...
|
|
||||||
|
|
||||||
fmt:
|
|
||||||
gofmt -l .
|
|
||||||
@test -z "$$(gofmt -l .)" || (echo "gofmt-Verstoesse gefunden, siehe oben" && exit 1)
|
|
||||||
|
|
||||||
test:
|
|
||||||
go test ./... -p 1 -count=1
|
|
||||||
|
|
||||||
check: build
|
|
||||||
go vet ./...
|
|
||||||
golangci-lint run ./...
|
|
||||||
go test ./... -p 1 -count=1
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# NEXARCH Archive
|
|
||||||
|
|
||||||
Zentrales, modulübergreifendes Modul für Aufbewahrung, WORM, Compliance und
|
|
||||||
Backup. Dieses Verzeichnis enthält bisher `internal/backup` (BAK-01,
|
|
||||||
Datenbank-Backup-Strategie) — weitere Bausteine folgen ticketweise.
|
|
||||||
|
|
||||||
## BAK-01: Datenbank-Backup
|
|
||||||
|
|
||||||
`cmd/backup-cli` — Aufrufpunkt für systemd-Timer (siehe
|
|
||||||
`../deploy/systemd/nexarch-archive-backup-*.timer`):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
export NEXARCH_BACKUP_PG_USER=nexarch_backup
|
|
||||||
export NEXARCH_BACKUP_PG_PASSWORD=...
|
|
||||||
export NEXARCH_BACKUP_DIR=/var/backups/nexarch
|
|
||||||
export NEXARCH_BACKUP_KEEP_GENERATIONS=7 # optional, Default 7
|
|
||||||
|
|
||||||
backup-cli full # neue Vollsicherung + Verifikation
|
|
||||||
backup-cli incremental # inkrementelle Sicherung gegen die neueste Generation
|
|
||||||
backup-cli rotate # entfernt alle bis auf die neuesten N Generationen
|
|
||||||
```
|
|
||||||
|
|
||||||
Voraussetzung: die konfigurierte Postgres-Rolle braucht das
|
|
||||||
`REPLICATION`-Attribut (`pg_basebackup` nutzt eine
|
|
||||||
Replikationsverbindung), und `summarize_wal = on` muss serverseitig gesetzt
|
|
||||||
sein (PostgreSQL 17s natives inkrementelles Backup, keine WAL-Archivierung
|
|
||||||
nötig).
|
|
||||||
|
|
||||||
## Prüfungen
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make check # build + vet + lint + test, analog Core/DMS
|
|
||||||
```
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
// backup-cli ist der Aufrufpunkt für BAK-01, gedacht für systemd-Timer
|
|
||||||
// (siehe deploy/systemd/) — "automatisiert nach Zeitplan" (Akzeptanzkriterium
|
|
||||||
// 1) entsteht durch die Zeitplan-Definition im Timer-Unit, nicht durch
|
|
||||||
// einen eigenen In-Prozess-Scheduler (kein zusätzlicher Dauerprozess nötig,
|
|
||||||
// passt zur Produkt-DNA "kein Anwendungsserver mit unnötigem
|
|
||||||
// Ressourcenverbrauch").
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/archive/internal/backup"
|
|
||||||
)
|
|
||||||
|
|
||||||
func loadConfig() backup.Config {
|
|
||||||
cfg := backup.Config{
|
|
||||||
Host: os.Getenv("NEXARCH_BACKUP_PG_HOST"),
|
|
||||||
Port: os.Getenv("NEXARCH_BACKUP_PG_PORT"),
|
|
||||||
User: os.Getenv("NEXARCH_BACKUP_PG_USER"),
|
|
||||||
Password: os.Getenv("NEXARCH_BACKUP_PG_PASSWORD"),
|
|
||||||
BackupDir: os.Getenv("NEXARCH_BACKUP_DIR"),
|
|
||||||
}
|
|
||||||
if cfg.Host == "" {
|
|
||||||
cfg.Host = "localhost"
|
|
||||||
}
|
|
||||||
if cfg.Port == "" {
|
|
||||||
cfg.Port = "5432"
|
|
||||||
}
|
|
||||||
if cfg.User == "" || cfg.Password == "" || cfg.BackupDir == "" {
|
|
||||||
log.Fatal("NEXARCH_BACKUP_PG_USER, NEXARCH_BACKUP_PG_PASSWORD und NEXARCH_BACKUP_DIR muessen gesetzt sein")
|
|
||||||
}
|
|
||||||
return cfg
|
|
||||||
}
|
|
||||||
|
|
||||||
func latestManifest(backupDir string) (string, error) {
|
|
||||||
generations, err := backup.ListGenerations(backupDir)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if len(generations) == 0 {
|
|
||||||
return "", fmt.Errorf("keine vorhandene generation fuer inkrementelle sicherung gefunden - zuerst 'full' ausfuehren")
|
|
||||||
}
|
|
||||||
latest := generations[len(generations)-1]
|
|
||||||
full := backupDir + "/" + latest + "/" + backup.FullBackupDirName + "/" + backup.BackupManifestFile
|
|
||||||
if _, err := os.Stat(full); err == nil {
|
|
||||||
return full, nil
|
|
||||||
}
|
|
||||||
return "", fmt.Errorf("kein backup_manifest in der neuesten generation %q gefunden", latest)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
if len(os.Args) < 2 {
|
|
||||||
log.Fatal("aufruf: backup-cli <full|incremental|verify|rotate> [args]")
|
|
||||||
}
|
|
||||||
cfg := loadConfig()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
switch os.Args[1] {
|
|
||||||
case "full":
|
|
||||||
genID := backup.NewGenerationID(time.Now())
|
|
||||||
manifest, err := backup.FullBackup(ctx, cfg, genID)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("vollsicherung fehlgeschlagen: %v", err)
|
|
||||||
}
|
|
||||||
dir := manifest[:len(manifest)-len("/"+backup.BackupManifestFile)]
|
|
||||||
if err := backup.Verify(dir); err != nil {
|
|
||||||
log.Fatalf("verifikation der vollsicherung fehlgeschlagen: %v", err)
|
|
||||||
}
|
|
||||||
fmt.Printf("vollsicherung %q erstellt und verifiziert: %s\n", genID, manifest)
|
|
||||||
|
|
||||||
case "incremental":
|
|
||||||
manifest, err := latestManifest(cfg.BackupDir)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
generations, _ := backup.ListGenerations(cfg.BackupDir)
|
|
||||||
genID := generations[len(generations)-1]
|
|
||||||
incID := backup.NewGenerationID(time.Now())
|
|
||||||
newManifest, err := backup.IncrementalBackup(ctx, cfg, genID, incID, manifest)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("inkrementelle sicherung fehlgeschlagen: %v", err)
|
|
||||||
}
|
|
||||||
dir := newManifest[:len(newManifest)-len("/"+backup.BackupManifestFile)]
|
|
||||||
if err := backup.Verify(dir); err != nil {
|
|
||||||
log.Fatalf("verifikation der inkrementellen sicherung fehlgeschlagen: %v", err)
|
|
||||||
}
|
|
||||||
fmt.Printf("inkrementelle sicherung %q erstellt und verifiziert: %s\n", incID, newManifest)
|
|
||||||
|
|
||||||
case "rotate":
|
|
||||||
keep := 7
|
|
||||||
if v := os.Getenv("NEXARCH_BACKUP_KEEP_GENERATIONS"); v != "" {
|
|
||||||
_, _ = fmt.Sscanf(v, "%d", &keep)
|
|
||||||
}
|
|
||||||
removed, err := backup.Rotate(cfg.BackupDir, keep)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("rotation fehlgeschlagen: %v", err)
|
|
||||||
}
|
|
||||||
fmt.Printf("rotation abgeschlossen, %d generation(en) entfernt: %v\n", len(removed), removed)
|
|
||||||
|
|
||||||
default:
|
|
||||||
log.Fatalf("unbekannter befehl %q", os.Args[1])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
# BAK-01 – Prüfprotokoll: Datenbank-Backup-Strategie
|
|
||||||
|
|
||||||
Welle 1, keine Vorbedingungen. Neues Modul-Verzeichnis `code/archive/`
|
|
||||||
(gleiches Monorepo-Muster wie `code/dms/`), eigenes Go-Modul
|
|
||||||
`gitea.perlbach24.de/scripte/nexarch/archive`.
|
|
||||||
|
|
||||||
## Grundsatzentscheidung: PostgreSQL-17-natives inkrementelles Backup
|
|
||||||
|
|
||||||
`pg_dump` kennt nur logische Vollsicherungen — "inkrementell" im Sinne des
|
|
||||||
Tickets erfordert das physische Backup-Verfahren. Gewählt: PostgreSQL 17s
|
|
||||||
natives `pg_basebackup --incremental` (WAL-Summarization), NICHT klassisches
|
|
||||||
WAL-Archiving (`archive_mode`), weil letzteres einen Neustart der
|
|
||||||
(geteilten, auch von Core/DMS-Tests genutzten) Postgres-Instanz auf
|
|
||||||
192.168.1.131 erfordert hätte. Stattdessen `summarize_wal = on` gesetzt —
|
|
||||||
nur ein `pg_reload_conf()`, kein Neustart, keine Unterbrechung laufender
|
|
||||||
Verbindungen (per Health-Check nach der Änderung bestätigt).
|
|
||||||
|
|
||||||
Voraussetzung geschaffen: Rolle `nexarch_backup` mit `REPLICATION`-Attribut
|
|
||||||
angelegt (Postgres verlangt eine Replikationsverbindung für
|
|
||||||
`pg_basebackup`), `pg_hba.conf` erlaubte lokale Replikationsverbindungen
|
|
||||||
bereits.
|
|
||||||
|
|
||||||
## Umsetzung
|
|
||||||
|
|
||||||
- `internal/backup.FullBackup`/`IncrementalBackup` — rufen `pg_basebackup`
|
|
||||||
über `os/exec` auf, Ergebnis landet in einer Generationsstruktur
|
|
||||||
(`<BackupDir>/<Generation>/full/` bzw. `.../incremental/<ID>/`).
|
|
||||||
- `internal/backup.Verify` — öffnet `base.tar.gz` vollständig (gzip- UND
|
|
||||||
tar-Stream, jeder Eintrag bis zum Ende gelesen, nicht nur Kopfdaten) —
|
|
||||||
Akzeptanzkriterium 2: Verifikation auf Lesbarkeit, nicht nur Erstellung.
|
|
||||||
- `internal/backup.Rotate`/`ListGenerations` — Generationen sind nach
|
|
||||||
Zeitstempel-ID sortierbar, `Rotate` entfernt die ältesten bis auf `keep`
|
|
||||||
komplett (inklusive aller abhängigen Inkremente).
|
|
||||||
- `cmd/backup-cli` — `full`/`incremental`/`rotate`, aufgerufen von
|
|
||||||
systemd-Timern (`deploy/systemd/nexarch-archive-backup-*.timer`) —
|
|
||||||
"automatisiert nach Zeitplan" (Akzeptanzkriterium 1) entsteht durch die
|
|
||||||
Timer-Definition, kein zusätzlicher Dauerprozess nötig.
|
|
||||||
|
|
||||||
## Prüfungen
|
|
||||||
|
|
||||||
| # | Prüfung | Ergebnis |
|
|
||||||
|---|---|---|
|
|
||||||
| 1 | Sicherung gegen Testdatenbank erfolgreich erstellt und verifiziert | **bestanden** — `TestFullBackup_CreatesVerifiedBackup` gegen die echte Postgres-17-Instanz auf 192.168.1.131 (kein Mock), zusätzlich `TestIncrementalBackup_IsSmallerThanFull`: inkrementelle Sicherung real deutlich kleiner als Vollsicherung (167 KB vs. 16 MB bei der ersten manuellen Probe) — beweist echte inkrementelle Übertragung, nicht nur eine zweite Vollsicherung |
|
|
||||||
| 2 | Verifikation erkennt eine absichtlich beschädigte Sicherungsdatei | **bestanden** — `TestVerify_DetectsCorruptedFile`: 64 Bytes in der Mitte von `base.tar.gz` gekippt, `Verify` schlägt danach fehl (unbeschädigt zuvor erfolgreich) |
|
|
||||||
| 3 | Rotationsregel entfernt nachweislich nur die ältesten Generationen | **bestanden** — `TestRotate_RemovesOnlyOldestGenerations`: 5 Generationen, `keep=2`, exakt die 3 ältesten entfernt, die 2 neuesten nachweislich unangetastet |
|
|
||||||
|
|
||||||
## Echte Verdrahtung auf 192.168.1.131 (nicht nur Testcode)
|
|
||||||
|
|
||||||
Anders als die zuletzt in DMS gefundenen "Baustein existiert, ist aber
|
|
||||||
nirgends verdrahtet"-Fälle (FDN-03/FDN-09 gegen Core) wurde hier die
|
|
||||||
komplette Kette tatsächlich installiert und ausgeführt:
|
|
||||||
|
|
||||||
- `backup-cli` gebaut nach `/opt/nexarch-archive/bin/`
|
|
||||||
- `/etc/nexarch/archive-backup.env` mit den Verbindungsdaten (0600)
|
|
||||||
- 3 systemd-Timer installiert und aktiviert (`enable --now`):
|
|
||||||
Vollsicherung täglich 02:00 UTC, Inkrement stündlich, Rotation täglich
|
|
||||||
03:00 UTC (`systemctl list-timers` bestätigt alle drei scharf)
|
|
||||||
- Jeder der drei Dienste (`full`/`incremental`/`rotate`) einmal manuell über
|
|
||||||
`systemctl start` ausgelöst (nicht nur `go test` direkt) — alle drei mit
|
|
||||||
`status=0/SUCCESS`, Journal bestätigt inhaltlich korrekte Ausgabe
|
|
||||||
(Vollsicherung erstellt+verifiziert, Inkrement erstellt+verifiziert
|
|
||||||
gegen die richtige Vorgänger-Generation, Rotation lief ohne Fehler)
|
|
||||||
|
|
||||||
## Build/Test-Ergebnis (192.168.1.131, `make check`)
|
|
||||||
|
|
||||||
```
|
|
||||||
go build ./... -> clean
|
|
||||||
go vet ./... -> clean
|
|
||||||
golangci-lint run ./... -> 0 issues
|
|
||||||
go test ./... -p 1 -count=1 -> 4/4 Tests ok, 0 Fehlschläge (echter Postgres 17, kein Mock)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Gesamtergebnis
|
|
||||||
|
|
||||||
**Bestanden.** Alle drei Akzeptanzkriterien und alle drei Pflichtprüfungen
|
|
||||||
real erfüllt — inklusive tatsächlicher systemd-Timer-Installation und
|
|
||||||
manuell ausgelöstem End-to-End-Lauf aller drei Dienste auf dem Testhost,
|
|
||||||
nicht nur isolierter Testcode.
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
module gitea.perlbach24.de/scripte/nexarch/archive
|
|
||||||
|
|
||||||
go 1.22
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
// Package backup implementiert BAK-01: automatisierte, inkrementelle
|
|
||||||
// Sicherung der PostgreSQL-Datenbank per pg_basebackup (PostgreSQL 17s
|
|
||||||
// natives inkrementelles Backup über WAL-Summarization, siehe
|
|
||||||
// `summarize_wal`), mit Verifikation jeder Sicherung und
|
|
||||||
// generationsbasierter Rotation. Kein pg_dump-basierter Ansatz, weil
|
|
||||||
// pg_dump ausschließlich logische Vollsicherungen kennt — "inkrementell"
|
|
||||||
// im Sinne des Tickets erfordert das physische, WAL-summary-gestützte
|
|
||||||
// Verfahren aus PostgreSQL 17.
|
|
||||||
package backup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Config enthält die Verbindungsdaten für pg_basebackup — ausschließlich
|
|
||||||
// über Umgebungsvariablen befüllt, nie im Code (siehe Ticket-Abschluss-
|
|
||||||
// Regel).
|
|
||||||
type Config struct {
|
|
||||||
Host string
|
|
||||||
Port string
|
|
||||||
User string
|
|
||||||
Password string
|
|
||||||
BackupDir string
|
|
||||||
PgBaseBackupPath string // Default "pg_basebackup", überschreibbar für Tests
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c Config) binary() string {
|
|
||||||
if c.PgBaseBackupPath != "" {
|
|
||||||
return c.PgBaseBackupPath
|
|
||||||
}
|
|
||||||
return "pg_basebackup"
|
|
||||||
}
|
|
||||||
|
|
||||||
// FullBackupDirName/IncrementalDirName sind die festen Unterverzeichnis-
|
|
||||||
// namen je Generation.
|
|
||||||
const (
|
|
||||||
FullBackupDirName = "full"
|
|
||||||
IncrementalSubdir = "incremental"
|
|
||||||
BackupManifestFile = "backup_manifest"
|
|
||||||
BaseTarGzFile = "base.tar.gz"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewGenerationID liefert eine sortierbare, eindeutige Generation-Kennung
|
|
||||||
// (RFC3339-artig, dateisystemtauglich) — Generationen werden anhand dieser
|
|
||||||
// Kennung chronologisch sortiert (Rotate, ListGenerations).
|
|
||||||
func NewGenerationID(t time.Time) string {
|
|
||||||
return t.UTC().Format("20060102T150405Z")
|
|
||||||
}
|
|
||||||
|
|
||||||
// FullBackup erstellt eine neue Vollsicherung (Akzeptanzkriterium 1) als
|
|
||||||
// eigene Generation. Liefert den Pfad zum backup_manifest, das spätere
|
|
||||||
// IncrementalBackup-Aufrufe als Referenz brauchen.
|
|
||||||
func FullBackup(ctx context.Context, cfg Config, generationID string) (manifestPath string, err error) {
|
|
||||||
dir := filepath.Join(cfg.BackupDir, generationID, FullBackupDirName)
|
|
||||||
if err := os.MkdirAll(filepath.Dir(dir), 0o750); err != nil {
|
|
||||||
return "", fmt.Errorf("backup: generationsverzeichnis anlegen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
args := []string{
|
|
||||||
"-h", cfg.Host, "-p", cfg.Port, "-U", cfg.User,
|
|
||||||
"-D", dir, "-Ft", "-z", "--checkpoint=fast", "--no-password",
|
|
||||||
}
|
|
||||||
if err := runPgBaseBackup(ctx, cfg, args); err != nil {
|
|
||||||
return "", fmt.Errorf("backup: vollsicherung: %w", err)
|
|
||||||
}
|
|
||||||
return filepath.Join(dir, BackupManifestFile), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// IncrementalBackup erstellt eine inkrementelle Sicherung gegen die zuletzt
|
|
||||||
// bekannte Vollsicherung ODER die letzte Inkrement-Sicherung (priorManifestPath
|
|
||||||
// zeigt jeweils auf das backup_manifest der Referenz).
|
|
||||||
func IncrementalBackup(ctx context.Context, cfg Config, generationID, incrementID, priorManifestPath string) (manifestPath string, err error) {
|
|
||||||
dir := filepath.Join(cfg.BackupDir, generationID, IncrementalSubdir, incrementID)
|
|
||||||
if err := os.MkdirAll(filepath.Dir(dir), 0o750); err != nil {
|
|
||||||
return "", fmt.Errorf("backup: inkrement-verzeichnis anlegen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
args := []string{
|
|
||||||
"-h", cfg.Host, "-p", cfg.Port, "-U", cfg.User,
|
|
||||||
"-D", dir, "-Ft", "-z", "--checkpoint=fast", "--no-password",
|
|
||||||
"--incremental=" + priorManifestPath,
|
|
||||||
}
|
|
||||||
if err := runPgBaseBackup(ctx, cfg, args); err != nil {
|
|
||||||
return "", fmt.Errorf("backup: inkrementelle sicherung: %w", err)
|
|
||||||
}
|
|
||||||
return filepath.Join(dir, BackupManifestFile), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func runPgBaseBackup(ctx context.Context, cfg Config, args []string) error {
|
|
||||||
cmd := exec.CommandContext(ctx, cfg.binary(), args...)
|
|
||||||
cmd.Env = append(os.Environ(), "PGPASSWORD="+cfg.Password)
|
|
||||||
output, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("%s fehlgeschlagen: %w (ausgabe: %s)", cfg.binary(), err, string(output))
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
package backup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func requireTestConfig(t *testing.T) Config {
|
|
||||||
t.Helper()
|
|
||||||
user := os.Getenv("TEST_BACKUP_PG_USER")
|
|
||||||
if user == "" {
|
|
||||||
t.Skip("TEST_BACKUP_PG_USER nicht gesetzt, Integrationstest uebersprungen (braucht echten Postgres mit REPLICATION-Rolle)")
|
|
||||||
}
|
|
||||||
return Config{
|
|
||||||
Host: envOr("TEST_BACKUP_PG_HOST", "localhost"),
|
|
||||||
Port: envOr("TEST_BACKUP_PG_PORT", "5432"),
|
|
||||||
User: user,
|
|
||||||
Password: os.Getenv("TEST_BACKUP_PG_PASSWORD"),
|
|
||||||
BackupDir: t.TempDir(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func envOr(key, fallback string) string {
|
|
||||||
if v := os.Getenv(key); v != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFullBackup_CreatesVerifiedBackup ist Pruefung 1: Sicherung gegen
|
|
||||||
// Testdatenbank erfolgreich erstellt und verifiziert.
|
|
||||||
func TestFullBackup_CreatesVerifiedBackup(t *testing.T) {
|
|
||||||
cfg := requireTestConfig(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
genID := NewGenerationID(time.Now())
|
|
||||||
manifest, err := FullBackup(ctx, cfg, genID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fullbackup: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(manifest); err != nil {
|
|
||||||
t.Fatalf("backup_manifest fehlt: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dir := filepath.Dir(manifest)
|
|
||||||
if _, err := os.Stat(filepath.Join(dir, BaseTarGzFile)); err != nil {
|
|
||||||
t.Fatalf("%s fehlt: %v", BaseTarGzFile, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := Verify(dir); err != nil {
|
|
||||||
t.Fatalf("verify: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestIncrementalBackup_IsSmallerThanFull ist der Nachweis fuer
|
|
||||||
// Akzeptanzkriterium 1 (inkrementell): eine echte inkrementelle Sicherung
|
|
||||||
// gegen unveraenderten Bestand ist deutlich kleiner als die Vollsicherung —
|
|
||||||
// beweist, dass tatsaechlich nur Aenderungen uebertragen wurden (PostgreSQL
|
|
||||||
// 17 WAL-Summarization), nicht nochmal alles.
|
|
||||||
func TestIncrementalBackup_IsSmallerThanFull(t *testing.T) {
|
|
||||||
cfg := requireTestConfig(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
genID := NewGenerationID(time.Now())
|
|
||||||
fullManifest, err := FullBackup(ctx, cfg, genID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fullbackup: %v", err)
|
|
||||||
}
|
|
||||||
fullDir := filepath.Dir(fullManifest)
|
|
||||||
fullSize := fileSize(t, filepath.Join(fullDir, BaseTarGzFile))
|
|
||||||
|
|
||||||
incID := NewGenerationID(time.Now().Add(time.Second))
|
|
||||||
incManifest, err := IncrementalBackup(ctx, cfg, genID, incID, fullManifest)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("incrementalbackup: %v", err)
|
|
||||||
}
|
|
||||||
incDir := filepath.Dir(incManifest)
|
|
||||||
if err := Verify(incDir); err != nil {
|
|
||||||
t.Fatalf("verify (inkrementell): %v", err)
|
|
||||||
}
|
|
||||||
incSize := fileSize(t, filepath.Join(incDir, BaseTarGzFile))
|
|
||||||
|
|
||||||
if incSize >= fullSize {
|
|
||||||
t.Fatalf("inkrementelle sicherung (%d bytes) ist nicht kleiner als die vollsicherung (%d bytes) - keine echte inkrementelle Uebertragung", incSize, fullSize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func fileSize(t *testing.T, path string) int64 {
|
|
||||||
t.Helper()
|
|
||||||
info, err := os.Stat(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("dateigroesse von %q ermitteln: %v", path, err)
|
|
||||||
}
|
|
||||||
return info.Size()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestVerify_DetectsCorruptedFile ist Pruefung 2: Verifikation erkennt eine
|
|
||||||
// absichtlich beschaedigte Sicherungsdatei.
|
|
||||||
func TestVerify_DetectsCorruptedFile(t *testing.T) {
|
|
||||||
cfg := requireTestConfig(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
genID := NewGenerationID(time.Now())
|
|
||||||
manifest, err := FullBackup(ctx, cfg, genID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fullbackup: %v", err)
|
|
||||||
}
|
|
||||||
dir := filepath.Dir(manifest)
|
|
||||||
|
|
||||||
if err := Verify(dir); err != nil {
|
|
||||||
t.Fatalf("verify (unbeschaedigt) haette erfolgreich sein muessen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Absichtliche Beschaedigung: mehrere Bytes in der Mitte der Datei kippen.
|
|
||||||
path := filepath.Join(dir, BaseTarGzFile)
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("sicherungsdatei lesen: %v", err)
|
|
||||||
}
|
|
||||||
mid := len(data) / 2
|
|
||||||
for i := mid; i < mid+64 && i < len(data); i++ {
|
|
||||||
data[i] ^= 0xFF
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
|
||||||
t.Fatalf("beschaedigte sicherungsdatei schreiben: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := Verify(dir); err == nil {
|
|
||||||
t.Fatal("verify haette die beschaedigte sicherungsdatei erkennen muessen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRotate_RemovesOnlyOldestGenerations ist Pruefung 3.
|
|
||||||
func TestRotate_RemovesOnlyOldestGenerations(t *testing.T) {
|
|
||||||
backupDir := t.TempDir()
|
|
||||||
generationIDs := []string{
|
|
||||||
"20260101T000000Z",
|
|
||||||
"20260102T000000Z",
|
|
||||||
"20260103T000000Z",
|
|
||||||
"20260104T000000Z",
|
|
||||||
"20260105T000000Z",
|
|
||||||
}
|
|
||||||
for _, id := range generationIDs {
|
|
||||||
if err := os.MkdirAll(filepath.Join(backupDir, id, FullBackupDirName), 0o750); err != nil {
|
|
||||||
t.Fatalf("generation %q anlegen: %v", id, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
removed, err := Rotate(backupDir, 2)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("rotate: %v", err)
|
|
||||||
}
|
|
||||||
wantRemoved := []string{"20260101T000000Z", "20260102T000000Z", "20260103T000000Z"}
|
|
||||||
if len(removed) != len(wantRemoved) {
|
|
||||||
t.Fatalf("entfernte generationen = %v, want %v", removed, wantRemoved)
|
|
||||||
}
|
|
||||||
for i, w := range wantRemoved {
|
|
||||||
if removed[i] != w {
|
|
||||||
t.Fatalf("entfernte generationen = %v, want %v", removed, wantRemoved)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
remaining, err := ListGenerations(backupDir)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("listgenerations: %v", err)
|
|
||||||
}
|
|
||||||
wantRemaining := []string{"20260104T000000Z", "20260105T000000Z"}
|
|
||||||
if len(remaining) != len(wantRemaining) {
|
|
||||||
t.Fatalf("verbleibende generationen = %v, want %v", remaining, wantRemaining)
|
|
||||||
}
|
|
||||||
for i, w := range wantRemaining {
|
|
||||||
if remaining[i] != w {
|
|
||||||
t.Fatalf("verbleibende generationen = %v, want %v", remaining, wantRemaining)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Die NEUESTEN duerfen NICHT entfernt sein (Pruefung 3: nur die
|
|
||||||
// aeltesten Generationen).
|
|
||||||
for _, w := range wantRemaining {
|
|
||||||
if _, err := os.Stat(filepath.Join(backupDir, w)); err != nil {
|
|
||||||
t.Fatalf("neueste generation %q wurde faelschlich entfernt: %v", w, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package backup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sort"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ListGenerations liefert alle Generation-IDs in backupDir, aufsteigend
|
|
||||||
// sortiert (die GenerationID selbst ist chronologisch sortierbar, siehe
|
|
||||||
// NewGenerationID — kein Blick auf Dateisystem-Zeitstempel nötig, die bei
|
|
||||||
// einem Restore/Kopiervorgang verändert werden könnten).
|
|
||||||
func ListGenerations(backupDir string) ([]string, error) {
|
|
||||||
entries, err := os.ReadDir(backupDir)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("backup: sicherungsverzeichnis lesen: %w", err)
|
|
||||||
}
|
|
||||||
var generations []string
|
|
||||||
for _, e := range entries {
|
|
||||||
if e.IsDir() {
|
|
||||||
generations = append(generations, e.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Strings(generations)
|
|
||||||
return generations, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rotate entfernt alle bis auf die `keep` NEUESTEN Generationen
|
|
||||||
// (Akzeptanzkriterium 3) — jede Generation umfasst ihre Vollsicherung UND
|
|
||||||
// alle davon abhängigen Inkremente, ein Löschen der gesamten
|
|
||||||
// Generationsverzeichnisses entfernt beides konsistent zusammen.
|
|
||||||
func Rotate(backupDir string, keep int) (removed []string, err error) {
|
|
||||||
if keep < 0 {
|
|
||||||
keep = 0
|
|
||||||
}
|
|
||||||
generations, err := ListGenerations(backupDir)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(generations) <= keep {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
toRemove := generations[:len(generations)-keep]
|
|
||||||
for _, gen := range toRemove {
|
|
||||||
if err := os.RemoveAll(filepath.Join(backupDir, gen)); err != nil {
|
|
||||||
return removed, fmt.Errorf("backup: generation %q entfernen: %w", gen, err)
|
|
||||||
}
|
|
||||||
removed = append(removed, gen)
|
|
||||||
}
|
|
||||||
return removed, nil
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package backup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"archive/tar"
|
|
||||||
"compress/gzip"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrCorrupted wird geliefert, wenn eine Sicherungsdatei nicht lesbar ist
|
|
||||||
// (Akzeptanzkriterium 2: Verifikation, nicht nur Erstellungs-Prüfung).
|
|
||||||
var ErrCorrupted = fmt.Errorf("backup: sicherungsdatei ist beschaedigt oder unvollstaendig")
|
|
||||||
|
|
||||||
// Verify prüft, dass base.tar.gz im gegebenen Sicherungsverzeichnis
|
|
||||||
// vollständig lesbar ist — öffnet gzip- UND tar-Stream und liest JEDEN
|
|
||||||
// Eintrag bis zum Ende durch (nicht nur die Kopfdaten), damit ein
|
|
||||||
// abgeschnittener oder mit kaputten Bytes überschriebener Inhalt
|
|
||||||
// zuverlässig auffällt, nicht nur ein defekter Tar-Header.
|
|
||||||
func Verify(backupDir string) error {
|
|
||||||
path := filepath.Join(backupDir, BaseTarGzFile)
|
|
||||||
f, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("%w: %s nicht lesbar: %v", ErrCorrupted, path, err)
|
|
||||||
}
|
|
||||||
defer func() { _ = f.Close() }()
|
|
||||||
|
|
||||||
gz, err := gzip.NewReader(f)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("%w: gzip-header ungueltig: %v", ErrCorrupted, err)
|
|
||||||
}
|
|
||||||
defer func() { _ = gz.Close() }()
|
|
||||||
|
|
||||||
tr := tar.NewReader(gz)
|
|
||||||
entries := 0
|
|
||||||
for {
|
|
||||||
hdr, err := tr.Next()
|
|
||||||
if err == io.EOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("%w: tar-eintrag ungueltig: %v", ErrCorrupted, err)
|
|
||||||
}
|
|
||||||
if _, err := io.Copy(io.Discard, tr); err != nil {
|
|
||||||
return fmt.Errorf("%w: inhalt von %q nicht vollstaendig lesbar: %v", ErrCorrupted, hdr.Name, err)
|
|
||||||
}
|
|
||||||
entries++
|
|
||||||
}
|
|
||||||
if entries == 0 {
|
|
||||||
return fmt.Errorf("%w: archiv enthaelt keine eintraege", ErrCorrupted)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=NEXARCH Archive - Datenbank-Vollsicherung (BAK-01)
|
|
||||||
After=network.target postgresql.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
User=nexarch
|
|
||||||
EnvironmentFile=/etc/nexarch/archive-backup.env
|
|
||||||
ExecStart=__INSTALL_DIR__/bin/backup-cli full
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Taeglicher Zeitplan fuer NEXARCH Archive Datenbank-Vollsicherung (BAK-01)
|
|
||||||
|
|
||||||
[Timer]
|
|
||||||
OnCalendar=*-*-* 02:00:00
|
|
||||||
Persistent=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=timers.target
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=NEXARCH Archive - Datenbank-Inkrementalsicherung (BAK-01)
|
|
||||||
After=network.target postgresql.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
User=nexarch
|
|
||||||
EnvironmentFile=/etc/nexarch/archive-backup.env
|
|
||||||
ExecStart=__INSTALL_DIR__/bin/backup-cli incremental
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Stuendlicher Zeitplan fuer NEXARCH Archive Datenbank-Inkrementalsicherung (BAK-01)
|
|
||||||
|
|
||||||
[Timer]
|
|
||||||
OnCalendar=*-*-* *:00:00
|
|
||||||
Persistent=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=timers.target
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=NEXARCH Archive - Sicherungsgenerationen-Rotation (BAK-01)
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
User=nexarch
|
|
||||||
EnvironmentFile=/etc/nexarch/archive-backup.env
|
|
||||||
ExecStart=__INSTALL_DIR__/bin/backup-cli rotate
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Taeglicher Zeitplan fuer NEXARCH Archive Sicherungsgenerationen-Rotation (BAK-01)
|
|
||||||
|
|
||||||
[Timer]
|
|
||||||
OnCalendar=*-*-* 03:00:00
|
|
||||||
Persistent=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=timers.target
|
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# @nexarch/shl — UI-Shell & Design-System (Core SHL-01)
|
||||||
|
|
||||||
|
Gemeinsames Paket für alle NEXARCH-Modul-Frontends (Core, DMS, Mail, Archive, Workflow, AI, Connect).
|
||||||
|
Ein Modul-Frontend importiert ausschließlich über `index.ts`, kopiert keine Komponenten oder Tokens lokal.
|
||||||
|
|
||||||
|
## Enthält
|
||||||
|
|
||||||
|
- **Design-Tokens** (`tokens/tokens.ts`) — Farbe (Hell/Dunkel), Abstand, Typografie. Kontrastwerte gegen WCAG 2.1 AA geprüft (siehe `__tests__/tokens.test.ts`).
|
||||||
|
- **Theming** (`theme/ThemeProvider.tsx`) — zentrale Hell/Dunkel-Umschaltung, respektiert `prefers-color-scheme`, persistiert in `localStorage`.
|
||||||
|
- **i18n-Rahmen** (`i18n/i18n.tsx`) — Umschaltmechanismus Deutsch/Englisch. Modul-Frontends registrieren ihre fachlichen Textbausteine über `registerMessages()`, statt einen eigenen Mechanismus zu bauen.
|
||||||
|
- **Basis-Komponenten** (`components/`) — `Shell` (Layout + Navigation), `Table`, `Dialog`, `TextField`/`SelectField`/`CheckboxField`, `Toast`. Alle mit WCAG-2.1-AA-Grundlage (Tastaturbedienung, ARIA-Attribute, Fokus-Management).
|
||||||
|
|
||||||
|
## Verwendung in einem Modul-Frontend
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ThemeProvider, I18nProvider, ToastProvider, Shell } from "@nexarch/shl";
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ThemeProvider>
|
||||||
|
<I18nProvider initialLocale="de">
|
||||||
|
<ToastProvider>
|
||||||
|
<Shell modules={[]} tenantLabel="Mandant XY">
|
||||||
|
{children}
|
||||||
|
</Shell>
|
||||||
|
</ToastProvider>
|
||||||
|
</I18nProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bekannter offener Punkt
|
||||||
|
|
||||||
|
Die vier bereits gebauten Core-Frontends (`TEN-05`, `LIC-04`, `AUD-04`, `OPS-02`) sind vor diesem Paket entstanden und binden es noch nicht ein — Retrofit ist der nächste Schritt, siehe `nexarch-state.json`.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Ausführung auf dem Test-Host (nicht lokal, siehe Projekt-Testinfrastruktur):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm test
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// Prüfung: Tastaturbedienung der Basis-Komponenten funktioniert (SHL-01 Prüfung 2).
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { Dialog } from "../components/Dialog";
|
||||||
|
import { I18nProvider } from "../i18n/i18n";
|
||||||
|
|
||||||
|
function renderDialog(onClose: () => void) {
|
||||||
|
return render(
|
||||||
|
<I18nProvider>
|
||||||
|
<Dialog open titleId="test-title" title="Test-Dialog" onClose={onClose}>
|
||||||
|
<button type="button">Erste Aktion</button>
|
||||||
|
<button type="button">Zweite Aktion</button>
|
||||||
|
</Dialog>
|
||||||
|
</I18nProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Dialog: Tastaturbedienung", () => {
|
||||||
|
it("schließt sich bei ESC", () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
renderDialog(onClose);
|
||||||
|
fireEvent.keyDown(document, { key: "Escape" });
|
||||||
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("setzt den Fokus beim Öffnen auf das erste fokussierbare Element", () => {
|
||||||
|
renderDialog(vi.fn());
|
||||||
|
const closeButton = screen.getByRole("button", { name: /schließen/i });
|
||||||
|
expect(document.activeElement).toBe(closeButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ist als modaler Dialog mit Titel-Referenz ausgezeichnet", () => {
|
||||||
|
renderDialog(vi.fn());
|
||||||
|
const dialog = screen.getByRole("dialog");
|
||||||
|
expect(dialog).toHaveAttribute("aria-modal", "true");
|
||||||
|
expect(dialog).toHaveAttribute("aria-labelledby", "test-title");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Prüfung: Kontrastwerte erfüllen mindestens AA (SHL-01 Prüfung 3 / Akzeptanzkriterium 4).
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { colorTokens } from "../tokens/tokens";
|
||||||
|
|
||||||
|
// WCAG-2.1-AA-Kontrastberechnung (relative Luminanz, sRGB) — keine externe Abhängigkeit nötig.
|
||||||
|
function relLuminance(hex: string): number {
|
||||||
|
const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
|
||||||
|
const [r, g, b] = rgb.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||||
|
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contrastRatio(a: string, b: string): number {
|
||||||
|
const l1 = relLuminance(a);
|
||||||
|
const l2 = relLuminance(b);
|
||||||
|
const [lighter, darker] = l1 > l2 ? [l1, l2] : [l2, l1];
|
||||||
|
return (lighter + 0.05) / (darker + 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Design-Tokens: WCAG 2.1 AA Kontrast", () => {
|
||||||
|
for (const scheme of ["light", "dark"] as const) {
|
||||||
|
const c = colorTokens[scheme];
|
||||||
|
|
||||||
|
it(`${scheme}: textPrimary auf background erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.textPrimary, c.background)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: textSecondary auf surface erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.textSecondary, c.surface)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: accentContrast auf accent erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.accentContrast, c.accent)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: dangerContrast auf danger erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.dangerContrast, c.danger)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Dialog-Basis-Komponente — SHL-01. WCAG 2.1 AA: Fokus-Falle, ESC schließt, Tastaturbedienung vollständig.
|
||||||
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
const FOCUSABLE_SELECTOR =
|
||||||
|
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||||
|
|
||||||
|
export interface DialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Dialog({ open, onClose, titleId, title, children }: DialogProps) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const dialogRef = useRef<HTMLDivElement>(null);
|
||||||
|
const previouslyFocused = useRef<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
previouslyFocused.current = document.activeElement as HTMLElement | null;
|
||||||
|
|
||||||
|
const node = dialogRef.current;
|
||||||
|
const focusables = node?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
|
||||||
|
focusables?.[0]?.focus();
|
||||||
|
|
||||||
|
function handleKeyDown(event: KeyboardEvent) {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
onClose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key !== "Tab" || !node) return;
|
||||||
|
|
||||||
|
const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
|
||||||
|
if (items.length === 0) return;
|
||||||
|
const first = items[0];
|
||||||
|
const last = items[items.length - 1];
|
||||||
|
|
||||||
|
if (event.shiftKey && document.activeElement === first) {
|
||||||
|
event.preventDefault();
|
||||||
|
last.focus();
|
||||||
|
} else if (!event.shiftKey && document.activeElement === last) {
|
||||||
|
event.preventDefault();
|
||||||
|
first.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
previouslyFocused.current?.focus();
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="shl-dialog-backdrop"
|
||||||
|
role="presentation"
|
||||||
|
onMouseDown={(event) => {
|
||||||
|
if (event.target === event.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
className="shl-dialog"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
>
|
||||||
|
<div className="shl-dialog-header">
|
||||||
|
<h2 id={titleId}>{title}</h2>
|
||||||
|
<button type="button" onClick={onClose} aria-label={t("shl.dialog.close")}>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="shl-dialog-body">{children}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// Formularelemente-Basis-Komponenten — SHL-01. WCAG: jedes Feld hat verknüpftes <label>,
|
||||||
|
// Fehler werden per aria-describedby + aria-invalid angebunden, nicht nur farblich markiert.
|
||||||
|
|
||||||
|
import { useId } from "react";
|
||||||
|
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from "react";
|
||||||
|
|
||||||
|
interface FieldWrapperProps {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
children: (ids: { inputId: string; describedBy: string | undefined }) => ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldWrapper({ label, error, hint, children }: FieldWrapperProps) {
|
||||||
|
const inputId = useId();
|
||||||
|
const hintId = hint ? `${inputId}-hint` : undefined;
|
||||||
|
const errorId = error ? `${inputId}-error` : undefined;
|
||||||
|
const describedBy = [hintId, errorId].filter(Boolean).join(" ") || undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="shl-field">
|
||||||
|
<label htmlFor={inputId}>{label}</label>
|
||||||
|
{children({ inputId, describedBy })}
|
||||||
|
{hint && (
|
||||||
|
<p id={hintId} className="shl-field-hint">
|
||||||
|
{hint}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p id={errorId} className="shl-field-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TextFieldProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "aria-describedby"> {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextField({ label, error, hint, ...inputProps }: TextFieldProps) {
|
||||||
|
return (
|
||||||
|
<FieldWrapper label={label} error={error} hint={hint}>
|
||||||
|
{({ inputId, describedBy }) => (
|
||||||
|
<input
|
||||||
|
id={inputId}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
{...inputProps}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FieldWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SelectFieldProps
|
||||||
|
extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "id" | "aria-describedby"> {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SelectField({ label, error, hint, children, ...selectProps }: SelectFieldProps) {
|
||||||
|
return (
|
||||||
|
<FieldWrapper label={label} error={error} hint={hint}>
|
||||||
|
{({ inputId, describedBy }) => (
|
||||||
|
<select
|
||||||
|
id={inputId}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
{...selectProps}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</FieldWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CheckboxFieldProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "type"> {
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckboxField({ label, ...inputProps }: CheckboxFieldProps) {
|
||||||
|
const inputId = useId();
|
||||||
|
return (
|
||||||
|
<div className="shl-field shl-field-checkbox">
|
||||||
|
<input id={inputId} type="checkbox" {...inputProps} />
|
||||||
|
<label htmlFor={inputId}>{label}</label>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Layout-Shell mit Navigation — SHL-01 Akzeptanzkriterium 1.
|
||||||
|
// Globale Navigation zeigt nur Module, die Core für Tenant/Benutzer freigibt (Backend entscheidet, UI blendet nur aus).
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
import { useTheme } from "../theme/ThemeProvider";
|
||||||
|
|
||||||
|
export interface ModuleLink {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
href: string;
|
||||||
|
active?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShellProps {
|
||||||
|
modules: ModuleLink[];
|
||||||
|
tenantLabel: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Shell({ modules, tenantLabel, children }: ShellProps) {
|
||||||
|
const { scheme, toggle } = useTheme();
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="shl-shell">
|
||||||
|
<a className="shl-skip-link" href="#shl-main-content">
|
||||||
|
{t("shl.shell.skipToContent", "Zum Inhalt springen")}
|
||||||
|
</a>
|
||||||
|
<header className="shl-shell-header">
|
||||||
|
<nav aria-label={t("shl.shell.moduleNav", "Modul-Navigation")}>
|
||||||
|
<ul>
|
||||||
|
{modules.map((mod) => (
|
||||||
|
<li key={mod.key}>
|
||||||
|
<a href={mod.href} aria-current={mod.active ? "page" : undefined}>
|
||||||
|
{mod.label}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
<div className="shl-shell-context">
|
||||||
|
<span className="shl-tenant-context">{tenantLabel}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggle}
|
||||||
|
aria-label={
|
||||||
|
scheme === "light" ? t("shl.theme.toggleToDark") : t("shl.theme.toggleToLight")
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{scheme === "light" ? "🌙" : "☀️"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main id="shl-main-content" className="shl-shell-content" tabIndex={-1}>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// Table-Basis-Komponente — SHL-01. WCAG: semantische <table>, scope auf Kopfzellen, sortierbare Spalten per Tastatur.
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
export interface TableColumn<Row> {
|
||||||
|
key: string;
|
||||||
|
header: string;
|
||||||
|
render: (row: Row) => ReactNode;
|
||||||
|
sortable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TableProps<Row> {
|
||||||
|
columns: TableColumn<Row>[];
|
||||||
|
rows: Row[];
|
||||||
|
rowKey: (row: Row) => string;
|
||||||
|
sortKey?: string;
|
||||||
|
sortDirection?: "asc" | "desc";
|
||||||
|
onSort?: (key: string) => void;
|
||||||
|
caption?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Table<Row>({
|
||||||
|
columns,
|
||||||
|
rows,
|
||||||
|
rowKey,
|
||||||
|
sortKey,
|
||||||
|
sortDirection,
|
||||||
|
onSort,
|
||||||
|
caption,
|
||||||
|
}: TableProps<Row>) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<table className="shl-table">
|
||||||
|
{caption && <caption>{caption}</caption>}
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{columns.map((column) => {
|
||||||
|
const isSorted = column.key === sortKey;
|
||||||
|
const ariaSort = column.sortable
|
||||||
|
? isSorted
|
||||||
|
? sortDirection === "asc"
|
||||||
|
? "ascending"
|
||||||
|
: "descending"
|
||||||
|
: "none"
|
||||||
|
: undefined;
|
||||||
|
return (
|
||||||
|
<th key={column.key} scope="col" aria-sort={ariaSort}>
|
||||||
|
{column.sortable ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSort?.(column.key)}
|
||||||
|
className="shl-table-sort-button"
|
||||||
|
>
|
||||||
|
{column.header}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
column.header
|
||||||
|
)}
|
||||||
|
</th>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={columns.length}>{t("shl.table.noRows")}</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
rows.map((row) => (
|
||||||
|
<tr key={rowKey(row)}>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<td key={column.key}>{column.render(row)}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Toast-Basis-Komponente — SHL-01. WCAG: aria-live sorgt dafür, dass Screenreader Meldungen ansagen.
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
export type ToastVariant = "info" | "success" | "danger" | "warning";
|
||||||
|
|
||||||
|
export interface ToastMessage {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
variant: ToastVariant;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ToastContextValue {
|
||||||
|
toasts: ToastMessage[];
|
||||||
|
push: (text: string, variant?: ToastVariant) => void;
|
||||||
|
dismiss: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||||
|
|
||||||
|
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const dismiss = useCallback((id: string) => {
|
||||||
|
setToasts((current) => current.filter((toast) => toast.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const push = useCallback((text: string, variant: ToastVariant = "info") => {
|
||||||
|
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
setToasts((current) => [...current, { id, text, variant }]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ toasts, push, dismiss }), [toasts, push, dismiss]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToastContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
<div className="shl-toast-region" role="status" aria-live="polite" aria-atomic="false">
|
||||||
|
{toasts.map((toast) => (
|
||||||
|
<div key={toast.id} className={`shl-toast shl-toast-${toast.variant}`}>
|
||||||
|
<span>{toast.text}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => dismiss(toast.id)}
|
||||||
|
aria-label={t("shl.toast.dismiss")}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ToastContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useToast(): ToastContextValue {
|
||||||
|
const ctx = useContext(ToastContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useToast muss innerhalb von <ToastProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// i18n-Rahmen (mind. Deutsch/Englisch) — SHL-01 Akzeptanzkriterium 5.
|
||||||
|
// Liefert nur den Umschaltmechanismus + Basis-Komponenten-Texte.
|
||||||
|
// Modul-Frontends liefern ihre eigenen fachlichen Textbausteine über registerMessages(),
|
||||||
|
// statt einen eigenen i18n-Mechanismus zu bauen (siehe UI-UX-KONZEPT.md Abschnitt 4).
|
||||||
|
|
||||||
|
import { createContext, useContext, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
export type Locale = "de" | "en";
|
||||||
|
|
||||||
|
type MessageDict = Record<string, string>;
|
||||||
|
type MessageBundle = Record<Locale, MessageDict>;
|
||||||
|
|
||||||
|
const baseMessages: MessageBundle = {
|
||||||
|
de: {
|
||||||
|
"shl.dialog.close": "Schließen",
|
||||||
|
"shl.toast.dismiss": "Meldung schließen",
|
||||||
|
"shl.table.noRows": "Keine Einträge vorhanden",
|
||||||
|
"shl.theme.toggleToLight": "Helles Erscheinungsbild",
|
||||||
|
"shl.theme.toggleToDark": "Dunkles Erscheinungsbild",
|
||||||
|
},
|
||||||
|
en: {
|
||||||
|
"shl.dialog.close": "Close",
|
||||||
|
"shl.toast.dismiss": "Dismiss message",
|
||||||
|
"shl.table.noRows": "No entries",
|
||||||
|
"shl.theme.toggleToLight": "Switch to light theme",
|
||||||
|
"shl.theme.toggleToDark": "Switch to dark theme",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Registry, in die Modul-Frontends ihre eigenen Textbausteine einhängen.
|
||||||
|
const registry: MessageBundle = { de: { ...baseMessages.de }, en: { ...baseMessages.en } };
|
||||||
|
|
||||||
|
export function registerMessages(locale: Locale, messages: MessageDict): void {
|
||||||
|
registry[locale] = { ...registry[locale], ...messages };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface I18nContextValue {
|
||||||
|
locale: Locale;
|
||||||
|
setLocale: (locale: Locale) => void;
|
||||||
|
t: (key: string, fallback?: string) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const I18nContext = createContext<I18nContextValue | null>(null);
|
||||||
|
|
||||||
|
export function I18nProvider({
|
||||||
|
initialLocale = "de",
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
initialLocale?: Locale;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const [locale, setLocale] = useState<Locale>(initialLocale);
|
||||||
|
|
||||||
|
const value = useMemo<I18nContextValue>(
|
||||||
|
() => ({
|
||||||
|
locale,
|
||||||
|
setLocale,
|
||||||
|
t: (key: string, fallback?: string) => registry[locale][key] ?? fallback ?? key,
|
||||||
|
}),
|
||||||
|
[locale],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useI18n(): I18nContextValue {
|
||||||
|
const ctx = useContext(I18nContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useI18n muss innerhalb von <I18nProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
// Öffentliche Schnittstelle des Pakets @nexarch/shl — Modul-Frontends importieren ausschließlich hierüber,
|
||||||
|
// nicht aus internen Unterpfaden (SHL-01 Akzeptanzkriterium 2: dokumentiert, versioniert, importierbar statt kopiert).
|
||||||
|
|
||||||
|
export { colorTokens, spacing, breakpoints, typography, cssVariables } from "./tokens/tokens";
|
||||||
|
export type { ColorScheme, ColorTokens } from "./tokens/tokens";
|
||||||
|
|
||||||
|
export { ThemeProvider, useTheme, currentColors } from "./theme/ThemeProvider";
|
||||||
|
|
||||||
|
export { I18nProvider, useI18n, registerMessages } from "./i18n/i18n";
|
||||||
|
export type { Locale } from "./i18n/i18n";
|
||||||
|
|
||||||
|
export { Shell } from "./components/Shell";
|
||||||
|
export type { ShellProps, ModuleLink } from "./components/Shell";
|
||||||
|
|
||||||
|
export { Dialog } from "./components/Dialog";
|
||||||
|
export type { DialogProps } from "./components/Dialog";
|
||||||
|
|
||||||
|
export { Table } from "./components/Table";
|
||||||
|
export type { TableProps, TableColumn } from "./components/Table";
|
||||||
|
|
||||||
|
export { TextField, SelectField, CheckboxField } from "./components/FormElements";
|
||||||
|
export type { TextFieldProps, SelectFieldProps, CheckboxFieldProps } from "./components/FormElements";
|
||||||
|
|
||||||
|
export { ToastProvider, useToast } from "./components/Toast";
|
||||||
|
export type { ToastMessage, ToastVariant } from "./components/Toast";
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "@nexarch/shl",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "NEXARCH UI-Shell & Design-System (Core SHL-01) — gemeinsames Paket für alle Modul-Frontends.",
|
||||||
|
"main": "index.ts",
|
||||||
|
"types": "index.ts",
|
||||||
|
"scripts": {
|
||||||
|
"test": "vitest run",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@testing-library/jest-dom": "^6.4.8",
|
||||||
|
"@testing-library/react": "^16.0.0",
|
||||||
|
"@types/react": "18.3.3",
|
||||||
|
"@types/react-dom": "18.3.0",
|
||||||
|
"jsdom": "^24.1.1",
|
||||||
|
"typescript": "5.5.3",
|
||||||
|
"vitest": "^2.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Zentrales Theming (Hell/Dunkel) — SHL-01 Akzeptanzkriterium 6.
|
||||||
|
// Einzige Quelle für Hell/Dunkel-Werte; Modul-Frontends schalten nur um, bauen kein eigenes Theming.
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { colorTokens, cssVariables, type ColorScheme } from "../tokens/tokens";
|
||||||
|
|
||||||
|
const STORAGE_KEY = "nexarch-shl-theme";
|
||||||
|
|
||||||
|
interface ThemeContextValue {
|
||||||
|
scheme: ColorScheme;
|
||||||
|
setScheme: (scheme: ColorScheme) => void;
|
||||||
|
toggle: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||||
|
|
||||||
|
function readStoredScheme(): ColorScheme | null {
|
||||||
|
if (typeof window === "undefined") return null;
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||||
|
return stored === "light" || stored === "dark" ? stored : null;
|
||||||
|
} catch {
|
||||||
|
// localStorage kann in privaten Fenstern/eingeschränkten Kontexten fehlschlagen — kein Absturz, nur kein persistierter Zustand.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function systemPrefersDark(): boolean {
|
||||||
|
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||||
|
return window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [scheme, setSchemeState] = useState<ColorScheme>("light");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const stored = readStoredScheme();
|
||||||
|
setSchemeState(stored ?? (systemPrefersDark() ? "dark" : "light"));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setScheme = useCallback((next: ColorScheme) => {
|
||||||
|
setSchemeState(next);
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(STORAGE_KEY, next);
|
||||||
|
} catch {
|
||||||
|
// Speichern optional — Umschaltung funktioniert auch ohne Persistenz.
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggle = useCallback(() => {
|
||||||
|
setScheme(scheme === "light" ? "dark" : "light");
|
||||||
|
}, [scheme, setScheme]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const vars = cssVariables(scheme);
|
||||||
|
const root = document.documentElement;
|
||||||
|
for (const [key, value] of Object.entries(vars)) {
|
||||||
|
root.style.setProperty(key, value);
|
||||||
|
}
|
||||||
|
root.dataset.shlTheme = scheme;
|
||||||
|
}, [scheme]);
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ scheme, setScheme, toggle }), [scheme, setScheme, toggle]);
|
||||||
|
|
||||||
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme(): ThemeContextValue {
|
||||||
|
const ctx = useContext(ThemeContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useTheme muss innerhalb von <ThemeProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentColors(scheme: ColorScheme) {
|
||||||
|
return colorTokens[scheme];
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Design-Tokens: einzige Quelle für Farbe, Abstand, Typografie im gesamten Frontend-Verbund.
|
||||||
|
// Modul-Frontends importieren diese Tokens, überschreiben sie nicht lokal (SHL-01 Akzeptanzkriterium 3).
|
||||||
|
// Kontrastwerte sind gegen WCAG 2.1 AA geprüft (Akzeptanzkriterium 1/4): mindestens 4.5:1 für Fließtext.
|
||||||
|
|
||||||
|
export type ColorScheme = "light" | "dark";
|
||||||
|
|
||||||
|
export interface ColorTokens {
|
||||||
|
background: string;
|
||||||
|
surface: string;
|
||||||
|
surfaceRaised: string;
|
||||||
|
border: string;
|
||||||
|
textPrimary: string;
|
||||||
|
textSecondary: string;
|
||||||
|
accent: string;
|
||||||
|
accentContrast: string;
|
||||||
|
danger: string;
|
||||||
|
dangerContrast: string;
|
||||||
|
success: string;
|
||||||
|
warning: string;
|
||||||
|
focusRing: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kontrastwerte geprüft: textPrimary auf background/surface >= 7:1, textSecondary >= 4.5:1,
|
||||||
|
// accentContrast auf accent >= 4.5:1 (WCAG AA, siehe SHL-01 Prüfung 3).
|
||||||
|
export const colorTokens: Record<ColorScheme, ColorTokens> = {
|
||||||
|
light: {
|
||||||
|
background: "#FFFFFF",
|
||||||
|
surface: "#F5F6F8",
|
||||||
|
surfaceRaised: "#FFFFFF",
|
||||||
|
border: "#D7DBE0",
|
||||||
|
textPrimary: "#14181F",
|
||||||
|
textSecondary: "#4B5563",
|
||||||
|
accent: "#1D4ED8",
|
||||||
|
accentContrast: "#FFFFFF",
|
||||||
|
danger: "#B91C1C",
|
||||||
|
dangerContrast: "#FFFFFF",
|
||||||
|
success: "#15803D",
|
||||||
|
warning: "#B45309",
|
||||||
|
focusRing: "#1D4ED8",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
background: "#0F1115",
|
||||||
|
surface: "#181B21",
|
||||||
|
surfaceRaised: "#20242C",
|
||||||
|
border: "#333944",
|
||||||
|
textPrimary: "#F2F4F7",
|
||||||
|
textSecondary: "#B4BAC4",
|
||||||
|
accent: "#5B8DEF",
|
||||||
|
accentContrast: "#0F1115",
|
||||||
|
danger: "#F87171",
|
||||||
|
dangerContrast: "#0F1115",
|
||||||
|
success: "#4ADE80",
|
||||||
|
warning: "#FBBF24",
|
||||||
|
focusRing: "#5B8DEF",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const spacing = {
|
||||||
|
xs: "4px",
|
||||||
|
sm: "8px",
|
||||||
|
md: "16px",
|
||||||
|
lg: "24px",
|
||||||
|
xl: "32px",
|
||||||
|
xxl: "48px",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const breakpoints = {
|
||||||
|
mobile: "0px",
|
||||||
|
tablet: "768px",
|
||||||
|
desktop: "1200px",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const typography = {
|
||||||
|
fontFamily: "'Inter', 'Segoe UI', system-ui, sans-serif",
|
||||||
|
fontFamilyMono: "'JetBrains Mono', ui-monospace, monospace",
|
||||||
|
sizeSm: "13px",
|
||||||
|
sizeMd: "15px",
|
||||||
|
sizeLg: "18px",
|
||||||
|
sizeXl: "24px",
|
||||||
|
lineHeight: 1.5,
|
||||||
|
weightRegular: 400,
|
||||||
|
weightMedium: 500,
|
||||||
|
weightBold: 600,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function cssVariables(scheme: ColorScheme): Record<string, string> {
|
||||||
|
const c = colorTokens[scheme];
|
||||||
|
const vars: Record<string, string> = {};
|
||||||
|
for (const [key, value] of Object.entries(c)) {
|
||||||
|
vars[`--shl-color-${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`] = value;
|
||||||
|
}
|
||||||
|
for (const [key, value] of Object.entries(spacing)) {
|
||||||
|
vars[`--shl-spacing-${key}`] = value;
|
||||||
|
}
|
||||||
|
return vars;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"strict": true,
|
||||||
|
"declaration": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true
|
||||||
|
},
|
||||||
|
"include": ["**/*.ts", "**/*.tsx"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: "jsdom",
|
||||||
|
setupFiles: ["./vitest.setup.ts"],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
|
import { afterEach } from "vitest";
|
||||||
|
import { cleanup } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Ohne explizites Cleanup bleiben zwischen den it()-Blöcken gerenderte Dialoge im DOM stehen
|
||||||
|
// (mehrere <html>/<body>-Bäume stapeln sich), wodurch getByRole() mehrere Treffer statt einen findet.
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user