Garage UI : interface web d'administration pour Garage (API v2 + CLI)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
cedricandClaude Sonnet 5.5 committed 2026-11-20 20:18:24 +01:00
commit fdd5555100
36 files changed
+8486

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Adresse de l'API d'administration de Garage (section [admin] de garage.toml, api_bind_addr).
GARAGE_ADMIN_URL=http://garage:3903
# Jeton d'administration (admin_token de garage.toml, ou `garage admin-token create`).
GARAGE_ADMIN_TOKEN=
# Authentification de l'interface : vide = aucune (à réserver à un reverse proxy qui authentifie).
UI_USER=admin
UI_PASSWORD=
# Affichage des exemples de configuration client (rclone, aws cli).
GARAGE_S3_ENDPOINT=https://s3.example.org
GARAGE_S3_REGION=garage
# Console CLI (facultatif) : chemin du binaire garage et secret RPC du cluster.
GARAGE_BIN=/garage
GARAGE_RPC_HOST=
GARAGE_RPC_SECRET=
+7
View File
@@ -0,0 +1,7 @@
/bin/
web/dist/*
!web/dist/.gitkeep
frontend/node_modules/
.env
.DS_Store
.claude/
+34
View File
@@ -0,0 +1,34 @@
# syntax=docker/dockerfile:1
# --- 1. Frontend : React + Vite -> /src/web/dist
FROM node:22-alpine AS frontend
WORKDIR /src/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund
COPY frontend/ ./
RUN npm run build
# --- 2. Backend : binaire Go statique embarquant le frontend
FROM golang:1.24-alpine AS backend
ARG VERSION=dev
WORKDIR /src
COPY go.mod ./
COPY cmd ./cmd
COPY web/embed.go ./web/
COPY --from=frontend /src/web/dist ./web/dist
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go test ./... && \
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/server ./cmd/server
# --- 3. Binaire garage (CLI) : image officielle, même version que le serveur à piloter
FROM dxflrs/garage:v2.3.0 AS garage
# --- 4. Image finale : distroless, non-root
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=backend /out/server /server
COPY --from=garage /garage /garage
ENV LISTEN_ADDR=:8080 GARAGE_BIN=/garage
EXPOSE 8080
USER nonroot:nonroot
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 CMD ["/server", "healthcheck"]
ENTRYPOINT ["/server"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 vLab-BZH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+26
View File
@@ -0,0 +1,26 @@
# Licence MIT (traduction française)
> Traduction fournie à titre informatif. Seule la version anglaise du fichier [`LICENSE`](LICENSE) fait foi.
```text
Copyright (c) 2026 vLab-BZH
L'autorisation est accordée, gracieusement, à toute personne obtenant une copie
de ce logiciel et des fichiers de documentation associés (le « Logiciel »), de
commercialiser le Logiciel sans restriction, notamment les droits d'utiliser,
de copier, de modifier, de fusionner, de publier, de distribuer, de
sous-licencier et/ou de vendre des copies du Logiciel, ainsi que d'autoriser
les personnes auxquelles le Logiciel est fourni à le faire, sous réserve des
conditions suivantes :
La déclaration de copyright ci-dessus et la présente autorisation doivent être
incluses dans toutes copies ou parties substantielles du Logiciel.
LE LOGICIEL EST FOURNI « TEL QUEL », SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU
IMPLICITE, NOTAMMENT SANS GARANTIE DE QUALITÉ MARCHANDE, D'ADÉQUATION À UN
USAGE PARTICULIER ET D'ABSENCE DE CONTREFAÇON. EN AUCUN CAS LES AUTEURS OU
TITULAIRES DU DROIT D'AUTEUR NE SERONT RESPONSABLES DE TOUT DOMMAGE,
RÉCLAMATION OU AUTRE RESPONSABILITÉ, QUE CE SOIT DANS LE CADRE D'UN CONTRAT,
D'UN DÉLIT OU AUTRE, EN PROVENANCE DE, CONSÉCUTIF À OU EN RELATION AVEC LE
LOGICIEL OU SON UTILISATION, OU AVEC D'AUTRES ÉLÉMENTS DU LOGICIEL.
```
+77
View File
@@ -0,0 +1,77 @@
# Garage UI
Interface web d'administration pour un cluster [Garage](https://garagehq.deuxfleurs.fr/) (stockage S3 auto-hébergé), dans la même charte que [Up And Down](https://github.com/vLab-BZH/upandown) : thème clair et sombre, icônes [Papicons](https://github.com/PapillonApp/papicons), même feuille de style.
- **Vue d'ensemble** : santé du cluster, partitions, nœuds et occupation des disques, plus gros buckets.
- **Buckets** : création, alias globaux, clés autorisées (lecture, écriture, propriétaire), quotas (taille, nombre d'objets), site web statique, nettoyage des envois multipart inachevés, suppression.
- **Clés d'accès** : création, import, secret affiché à la demande, exemples de configuration `rclone` et `aws`, permissions par bucket, suppression.
- **Cluster** : nœuds, rôles (zone, capacité, étiquettes, passerelle), layout en attente avec prévisualisation, application et annulation, connexion d'un nœud.
- **Maintenance** : réparations (`tables`, `blocks`, `scrub`...), tâches de fond, blocs en erreur, snapshot des métadonnées.
- **Console** : exécute la CLI `garage` (liste blanche de sous-commandes), avec des raccourcis et un historique.
Garage 2.0 ou plus récent est requis : l'interface parle à l'**API d'administration v2** (`/v2/...`).
## Fonctionnement
Un seul binaire Go (bibliothèque standard, aucune dépendance) qui embarque le frontend. Il ne contient pas de logique métier :
1. il authentifie l'utilisateur (`UI_USER` / `UI_PASSWORD`, cookie signé `HttpOnly` `SameSite=Strict`) ;
2. il relaie `/api/garage/v2/*` vers l'API d'administration de Garage en ajoutant le jeton : **le jeton n'atteint jamais le navigateur**, et seuls les chemins `/v2/` sont relayés ;
3. il exécute, pour la console, le binaire `garage` avec une liste blanche de sous-commandes (`status`, `stats`, `repair`, `worker`, `block`, `meta`, `layout`, `bucket`, `key`, `node`), sans shell, avec délai maximal et sortie plafonnée.
Cette interface donne les pleins pouvoirs sur le cluster : ne l'exposez que derrière HTTPS et une authentification (la vôtre, ou un reverse proxy avec `UI_PASSWORD` vide).
## Démarrage
Côté Garage, il faut l'API d'administration (`garage.toml`) :
```toml
[admin]
api_bind_addr = "0.0.0.0:3903"
admin_token = "un-jeton-long-et-aleatoire"
```
Puis :
```bash
cp .env.example .env # renseigner GARAGE_ADMIN_URL, GARAGE_ADMIN_TOKEN, UI_PASSWORD
docker compose up -d --build
# http://localhost:8088
```
La console CLI utilise `GARAGE_RPC_HOST` (adresse RPC, port 3901) et `GARAGE_RPC_SECRET` (le `rpc_secret` de `garage.toml`). Sans `GARAGE_BIN`, la page Console est désactivée ; les autres pages n'en ont pas besoin.
## Variables
| Variable | Défaut | Rôle |
|---|---|---|
| `GARAGE_ADMIN_URL` | `http://garage:3903` | API d'administration de Garage |
| `GARAGE_ADMIN_TOKEN` | (obligatoire) | Jeton d'administration |
| `UI_USER` / `UI_PASSWORD` | `admin` / vide | Connexion à l'interface (vide : aucune authentification) |
| `SESSION_SECRET` / `SESSION_TTL` | aléatoire / `24h` | Signature et durée de la session |
| `PUBLIC_URL` | | URL publique (`https://...` : cookie `Secure`) |
| `TITLE` | `Garage UI` | Titre affiché |
| `GARAGE_S3_ENDPOINT` / `GARAGE_S3_REGION` | | Exemples de configuration client |
| `GARAGE_BIN` / `GARAGE_CONFIG` | `/garage` si présent | CLI : binaire et fichier `garage.toml` (`-c`) |
| `GARAGE_RPC_HOST` / `GARAGE_RPC_SECRET` | | CLI : adresse et secret RPC |
| `LISTEN_ADDR` | `:8080` | Écoute |
## Développement
```bash
cd frontend && npm ci && npm run build # sortie dans web/dist (embarquée)
go test ./... && go build -o bin/server ./cmd/server
```
`cmd/mockgarage` est un **faux** Garage v2 en mémoire (jeton `test`, port 3903) pour développer l'interface sans cluster :
```bash
MOCK_ADDR=127.0.0.1:13903 go run ./cmd/mockgarage &
GARAGE_ADMIN_URL=http://127.0.0.1:13903 GARAGE_ADMIN_TOKEN=test UI_PASSWORD=secret LISTEN_ADDR=127.0.0.1:8080 go run ./cmd/server
```
`npm run dev` (dans `frontend/`) sert le frontend avec rechargement à chaud et proxy vers `:8080`.
## Licence
MIT, voir [LICENSE](LICENSE). Composants tiers : [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+8
View File
@@ -0,0 +1,8 @@
# Composants tiers
- **Up And Down** (MIT, vLab-BZH) : feuille de style, jetons de couleur et composants d'interface.
- **Papicons** 0.2.3 (MIT, Association Papillon, icônes de Tom Things, <https://github.com/PapillonApp/papicons>) : tracés copiés sans modification dans `frontend/src/papicons.ts`, utilisés par `icons.tsx` et `gicons.tsx`.
- **Lucide** (ISC, <https://lucide.dev>) : icônes « server » et « terminal » (`frontend/src/gicons.tsx`), absentes de Papicons.
- **React** (MIT, Meta), **Vite** (MIT).
Le serveur n'utilise que la bibliothèque standard de Go.
+339
View File
@@ -0,0 +1,339 @@
// mockgarage : faux serveur d'administration Garage v2 (en mémoire), pour développer et tester
// l'interface sans cluster. Ce n'est PAS Garage : il imite seulement la forme des réponses.
//
// go run ./cmd/mockgarage # écoute sur :3903, jeton « test »
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
)
type perm struct {
Read bool `json:"read"`
Write bool `json:"write"`
Owner bool `json:"owner"`
}
type bucket struct {
ID string
Created string
Aliases []string
Objects int
Bytes int64
Site bool
Index string
ErrDoc *string
MaxSize *int64
MaxObjs *int64
Keys map[string]perm
}
type key struct {
ID, Name, Secret, Created string
Expiration *string
CreateBucket bool
}
var (
mu sync.Mutex
buckets = map[string]*bucket{}
keys = map[string]*key{}
nodeID = "563e1ac825ee3323aa441e72c26d1030d6d4414aeb3697544d1d7e0c3d8da3a2"
staged bool
version = 1
)
func init() {
now := time.Now().UTC().Format(time.RFC3339)
keys["GK31c2f218a2e44f485b94239e"] = &key{ID: "GK31c2f218a2e44f485b94239e", Name: "sauvegardes-proxmox", Secret: strings.Repeat("ab12", 16), Created: now, CreateBucket: true}
keys["GKb5d1c6ef0a9d4a3f9c8e1b22"] = &key{ID: "GKb5d1c6ef0a9d4a3f9c8e1b22", Name: "lecture-seule", Secret: strings.Repeat("cd34", 16), Created: now}
gb := int64(1 << 30)
q := 50 * gb
buckets["b1"] = &bucket{ID: "9a1f0c3e5b7d2f48a6c1e9d0b3a5f7c2e4d6b8a0c2e4f6a8b0d2c4e6f8a0b2c4", Created: now, Aliases: []string{"proxmox-backups"}, Objects: 1284, Bytes: 38 * gb, MaxSize: &q,
Keys: map[string]perm{"GK31c2f218a2e44f485b94239e": {true, true, true}}}
buckets["b2"] = &bucket{ID: "1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d", Created: now, Aliases: []string{"site-vitrine", "www"}, Objects: 42, Bytes: 12 << 20, Site: true, Index: "index.html",
Keys: map[string]perm{"GKb5d1c6ef0a9d4a3f9c8e1b22": {true, false, false}}}
buckets["b3"] = &bucket{ID: "7f6e5d4c3b2a19080f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a6978", Created: now, Aliases: []string{"vide"}, Keys: map[string]perm{}}
}
func j(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func gerr(w http.ResponseWriter, code int, msg string) {
j(w, code, map[string]any{"code": "MockError", "message": msg, "region": "garage", "path": ""})
}
func findBucket(id string) *bucket {
for _, b := range buckets {
if b.ID == id {
return b
}
}
return nil
}
func (b *bucket) info() map[string]any {
ks := []map[string]any{}
for id, p := range b.Keys {
if k := keys[id]; k != nil {
ks = append(ks, map[string]any{"accessKeyId": id, "name": k.Name, "permissions": p, "bucketLocalAliases": []string{}})
}
}
var wc any
if b.Site {
wc = map[string]any{"indexDocument": b.Index, "errorDocument": b.ErrDoc}
}
return map[string]any{
"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "localAliases": []any{}, "websiteAccess": b.Site, "websiteConfig": wc,
"keys": ks, "objects": b.Objects, "bytes": b.Bytes, "unfinishedUploads": 0, "unfinishedMultipartUploads": 2,
"unfinishedMultipartUploadParts": 5, "unfinishedMultipartUploadBytes": 30 << 20,
"quotas": map[string]any{"maxSize": b.MaxSize, "maxObjects": b.MaxObjs},
}
}
func (k *key) info(secret bool) map[string]any {
bs := []map[string]any{}
for _, b := range buckets {
if p, ok := b.Keys[k.ID]; ok {
bs = append(bs, map[string]any{"id": b.ID, "globalAliases": b.Aliases, "localAliases": []string{}, "permissions": p})
}
}
var s any
if secret {
s = k.Secret
}
return map[string]any{"accessKeyId": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false,
"secretAccessKey": s, "permissions": map[string]bool{"createBucket": k.CreateBucket}, "buckets": bs}
}
func handle(token string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
gerr(w, 403, "jeton d'administration invalide")
return
}
mu.Lock()
defer mu.Unlock()
op := strings.TrimPrefix(r.URL.Path, "/v2/")
q := r.URL.Query()
var body map[string]any
var arr []any
raw := json.NewDecoder(r.Body)
var anyBody any
_ = raw.Decode(&anyBody)
switch v := anyBody.(type) {
case map[string]any:
body = v
case []any:
arr = v
}
str := func(k string) string { s, _ := body[k].(string); return s }
log.Printf("%s %s", r.Method, op)
switch op {
case "GetClusterHealth":
j(w, 200, map[string]any{"status": "healthy", "knownNodes": 1, "connectedNodes": 1, "storageNodes": 1, "storageNodesUp": 1, "partitions": 256, "partitionsQuorum": 256, "partitionsAllOk": 256})
case "GetClusterStatus":
var role any = map[string]any{"zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}
j(w, 200, map[string]any{"layoutVersion": version, "nodes": []any{map[string]any{
"id": nodeID, "role": role, "addr": "172.18.0.2:3901", "hostname": "garage", "isUp": true, "lastSeenSecsAgo": nil, "draining": false,
"dataPartition": map[string]any{"available": int64(412e9), "total": int64(500e9)}, "metadataPartition": map[string]any{"available": int64(40e9), "total": int64(50e9)}, "garageVersion": "v2.3.0"}}})
case "GetClusterStatistics":
j(w, 200, map[string]any{"freeform": "Storage nodes:\n ID Hostname Zone Capacity Part. DataAvail MetaAvail\n 563e1ac8 garage dc1 500.0 GB 256 412.0 GB 40.0 GB"})
case "GetClusterLayout":
st := []any{}
if staged {
st = append(st, map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(800e9)})
}
j(w, 200, map[string]any{"version": version, "roles": []any{map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}}, "partitionSize": 67108864, "stagedRoleChanges": st})
case "UpdateClusterLayout":
staged = true
j(w, 200, map[string]any{"version": version})
case "PreviewClusterLayoutChanges":
j(w, 200, map[string]any{"message": []string{"==== NEW CLUSTER LAYOUT ====", "capacité 800 GB sur dc1", "(aperçu simulé)"}})
case "ApplyClusterLayout":
staged, version = false, version+1
j(w, 200, map[string]any{"message": []string{"ok"}})
case "RevertClusterLayout":
staged = false
j(w, 200, map[string]any{"version": version})
case "ConnectClusterNodes":
j(w, 200, []any{map[string]any{"success": len(arr) > 0 && strings.Contains(fmt.Sprint(arr[0]), "@")}})
case "ListBuckets":
out := []any{}
for _, b := range buckets {
out = append(out, map[string]any{"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "localAliases": []any{}})
}
j(w, 200, out)
case "GetBucketInfo":
if b := findBucket(q.Get("id")); b != nil {
j(w, 200, b.info())
return
}
gerr(w, 404, "bucket introuvable")
case "CreateBucket":
id := fmt.Sprintf("%064x", time.Now().UnixNano())
b := &bucket{ID: id, Created: time.Now().UTC().Format(time.RFC3339), Aliases: []string{str("globalAlias")}, Keys: map[string]perm{}}
buckets[id] = b
j(w, 200, b.info())
case "DeleteBucket":
b := findBucket(q.Get("id"))
switch {
case b == nil:
gerr(w, 404, "bucket introuvable")
case b.Objects > 0:
gerr(w, 409, "le bucket n'est pas vide")
default:
for k, x := range buckets {
if x == b {
delete(buckets, k)
}
}
w.WriteHeader(204)
}
case "UpdateBucket":
b := findBucket(q.Get("id"))
if b == nil {
gerr(w, 404, "bucket introuvable")
return
}
if wa, ok := body["websiteAccess"].(map[string]any); ok {
b.Site, _ = wa["enabled"].(bool)
b.Index, _ = wa["indexDocument"].(string)
}
if qu, ok := body["quotas"].(map[string]any); ok {
b.MaxSize, b.MaxObjs = nil, nil
if f, ok := qu["maxSize"].(float64); ok {
n := int64(f)
b.MaxSize = &n
}
if f, ok := qu["maxObjects"].(float64); ok {
n := int64(f)
b.MaxObjs = &n
}
}
j(w, 200, b.info())
case "AddBucketAlias", "RemoveBucketAlias":
b := findBucket(str("bucketId"))
if b == nil {
gerr(w, 404, "bucket introuvable")
return
}
a := str("globalAlias")
if op == "AddBucketAlias" {
b.Aliases = append(b.Aliases, a)
} else {
out := b.Aliases[:0:0]
for _, x := range b.Aliases {
if x != a {
out = append(out, x)
}
}
b.Aliases = out
}
j(w, 200, b.info())
case "AllowBucketKey", "DenyBucketKey":
b := findBucket(str("bucketId"))
if b == nil {
gerr(w, 404, "bucket introuvable")
return
}
p := b.Keys[str("accessKeyId")]
pm, _ := body["permissions"].(map[string]any)
on := op == "AllowBucketKey"
if pm["read"] == true {
p.Read = on
}
if pm["write"] == true {
p.Write = on
}
if pm["owner"] == true {
p.Owner = on
}
b.Keys[str("accessKeyId")] = p
j(w, 200, b.info())
case "CleanupIncompleteUploads":
j(w, 200, map[string]any{"uploadsDeleted": 2})
case "ListKeys":
out := []any{}
for _, k := range keys {
out = append(out, map[string]any{"id": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false})
}
j(w, 200, out)
case "GetKeyInfo":
if k := keys[q.Get("id")]; k != nil {
j(w, 200, k.info(q.Get("showSecretKey") == "true"))
return
}
gerr(w, 404, "clé introuvable")
case "CreateKey", "ImportKey":
id := str("accessKeyId")
sec := str("secretAccessKey")
if id == "" {
id = fmt.Sprintf("GK%024x", time.Now().UnixNano())
sec = fmt.Sprintf("%064x", time.Now().UnixNano())
}
k := &key{ID: id, Name: str("name"), Secret: sec, Created: time.Now().UTC().Format(time.RFC3339)}
keys[id] = k
j(w, 200, k.info(true))
case "UpdateKey":
k := keys[q.Get("id")]
if k == nil {
gerr(w, 404, "clé introuvable")
return
}
if n := str("name"); n != "" {
k.Name = n
}
if a, ok := body["allow"].(map[string]any); ok && a["createBucket"] == true {
k.CreateBucket = true
}
if d, ok := body["deny"].(map[string]any); ok && d["createBucket"] == true {
k.CreateBucket = false
}
j(w, 200, k.info(false))
case "DeleteKey":
delete(keys, q.Get("id"))
for _, b := range buckets {
delete(b.Keys, q.Get("id"))
}
w.WriteHeader(204)
case "ListWorkers":
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{
map[string]any{"id": 1, "name": "Block resync worker #1", "state": "idle", "errors": 0, "consecutiveErrors": 0, "queueLength": 0},
map[string]any{"id": 2, "name": "Block scrub worker", "state": "busy", "errors": 0, "consecutiveErrors": 0, "progress": "42.0%"},
map[string]any{"id": 3, "name": "object sync", "state": map[string]any{"throttled": map[string]any{"durationSecs": 5}}, "errors": 1, "consecutiveErrors": 1, "lastError": map[string]any{"message": "timeout", "secsAgo": 90}},
}}, "error": map[string]any{}})
case "ListBlockErrors":
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{}}, "error": map[string]any{}})
case "LaunchRepairOperation", "CreateMetadataSnapshot", "RetryBlockResync":
j(w, 200, map[string]any{"success": map[string]any{nodeID: nil}, "error": map[string]any{}})
default:
gerr(w, 404, "opération inconnue : "+op)
}
}
}
func main() {
token := "test"
if v := os.Getenv("MOCK_TOKEN"); v != "" {
token = v
}
addr := ":3903"
if v := os.Getenv("MOCK_ADDR"); v != "" {
addr = v
}
log.Printf("mockgarage sur %s (jeton %q)", addr, token)
http.Handle("/v2/", handle(token))
log.Fatal(http.ListenAndServe(addr, nil))
}
+404
View File
@@ -0,0 +1,404 @@
// Garage UI : interface web d'administration d'un cluster Garage (S3).
//
// Le serveur ne contient pas de logique métier : il authentifie l'utilisateur, relaie
// l'API d'administration v2 de Garage en y ajoutant le jeton (qui ne va jamais au
// navigateur) et exécute, si on l'y autorise, quelques sous-commandes de la CLI garage.
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/vLab-BZH/garage-ui/web"
)
var version = "dev"
const (
cookieName = "garage_ui"
csrfHeader = "X-Requested-With"
)
type config struct {
listen string
adminURL *url.URL
adminToken string
user string
password string
secret []byte
title string
s3Endpoint string
s3Region string
cliBin string
cliConfig string
publicURL string
sessionTTL time.Duration
cliTimeout time.Duration
transport http.RoundTripper // nil : transport par défaut (les tests y mettent un faux Garage)
}
func env(k, def string) string {
if v := strings.TrimSpace(os.Getenv(k)); v != "" {
return v
}
return def
}
func loadConfig() (*config, error) {
c := &config{
listen: env("LISTEN_ADDR", ":8080"),
adminToken: env("GARAGE_ADMIN_TOKEN", ""),
user: env("UI_USER", "admin"),
password: os.Getenv("UI_PASSWORD"),
title: env("TITLE", "Garage UI"),
s3Endpoint: env("GARAGE_S3_ENDPOINT", ""),
s3Region: env("GARAGE_S3_REGION", "garage"),
cliBin: env("GARAGE_BIN", ""),
cliConfig: env("GARAGE_CONFIG", ""),
publicURL: env("PUBLIC_URL", ""),
sessionTTL: 24 * time.Hour,
cliTimeout: 120 * time.Second,
}
u, err := url.Parse(env("GARAGE_ADMIN_URL", "http://garage:3903"))
if err != nil || u.Host == "" {
return nil, fmt.Errorf("GARAGE_ADMIN_URL invalide")
}
c.adminURL = u
if d, err := time.ParseDuration(env("SESSION_TTL", "24h")); err == nil && d > 0 {
c.sessionTTL = d
}
if s := env("SESSION_SECRET", ""); s != "" {
c.secret = []byte(s)
} else {
c.secret = make([]byte, 32)
if _, err := rand.Read(c.secret); err != nil {
return nil, err
}
}
if c.cliBin == "" {
if st, err := os.Stat("/garage"); err == nil && !st.IsDir() {
c.cliBin = "/garage"
}
}
return c, nil
}
// --- Session -------------------------------------------------------------------
func (c *config) authEnabled() bool { return c.password != "" }
func (c *config) sign(msg string) string {
m := hmac.New(sha256.New, c.secret)
m.Write([]byte(msg))
return hex.EncodeToString(m.Sum(nil))
}
func (c *config) newSession(user string) string {
exp := strconv.FormatInt(time.Now().Add(c.sessionTTL).Unix(), 10)
msg := base64.RawURLEncoding.EncodeToString([]byte(user)) + "." + exp
return msg + "." + c.sign(msg)
}
// sessionUser renvoie l'utilisateur de la session, ou "" si elle est absente ou invalide.
func (c *config) sessionUser(r *http.Request) string {
if !c.authEnabled() {
return "admin"
}
ck, err := r.Cookie(cookieName)
if err != nil {
return ""
}
parts := strings.Split(ck.Value, ".")
if len(parts) != 3 {
return ""
}
msg := parts[0] + "." + parts[1]
if subtle.ConstantTimeCompare([]byte(parts[2]), []byte(c.sign(msg))) != 1 {
return ""
}
exp, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil || time.Now().Unix() > exp {
return ""
}
u, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return ""
}
return string(u)
}
func (c *config) setCookie(w http.ResponseWriter, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{
Name: cookieName, Value: value, Path: "/", MaxAge: maxAge, HttpOnly: true,
SameSite: http.SameSiteStrictMode, Secure: strings.HasPrefix(c.publicURL, "https://"),
})
}
// --- Utilitaires HTTP ----------------------------------------------------------
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func writeErr(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"message": msg})
}
// guard exige une session et, pour les requêtes qui modifient, l'en-tête anti-CSRF.
func (c *config) guard(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if c.sessionUser(r) == "" {
writeErr(w, http.StatusUnauthorized, "Connexion requise")
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Header.Get(csrfHeader) == "" {
writeErr(w, http.StatusForbidden, "En-tête "+csrfHeader+" manquant")
return
}
next(w, r)
}
}
// --- Routes --------------------------------------------------------------------
func (c *config) handleConfig(w http.ResponseWriter, r *http.Request) {
user := c.sessionUser(r)
writeJSON(w, 200, map[string]any{
"title": c.title, "version": version, "auth": c.authEnabled(), "user": user,
"cli": c.cliBin != "", "s3Endpoint": c.s3Endpoint, "s3Region": c.s3Region,
})
}
func (c *config) handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(csrfHeader) == "" {
writeErr(w, http.StatusForbidden, "En-tête "+csrfHeader+" manquant")
return
}
var in struct{ User, Password string }
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in); err != nil {
writeErr(w, 400, "Requête invalide")
return
}
okU := subtle.ConstantTimeCompare([]byte(in.User), []byte(c.user)) == 1
okP := subtle.ConstantTimeCompare([]byte(in.Password), []byte(c.password)) == 1
if !c.authEnabled() || !okU || !okP {
time.Sleep(700 * time.Millisecond) // ralentit les essais en série
writeErr(w, http.StatusUnauthorized, "Identifiants incorrects")
return
}
c.setCookie(w, c.newSession(in.User), int(c.sessionTTL.Seconds()))
writeJSON(w, 200, map[string]string{"user": in.User})
}
func (c *config) handleLogout(w http.ResponseWriter, _ *http.Request) {
c.setCookie(w, "", -1)
writeJSON(w, 200, map[string]bool{"ok": true})
}
// garageProxy relaie /api/garage/v2/... vers l'API d'administration de Garage.
func (c *config) garageProxy() http.Handler {
rp := &httputil.ReverseProxy{
Transport: c.transport,
Rewrite: func(pr *httputil.ProxyRequest) {
pr.Out.URL.Scheme = c.adminURL.Scheme
pr.Out.URL.Host = c.adminURL.Host
pr.Out.URL.Path = strings.TrimRight(c.adminURL.Path, "/") + strings.TrimPrefix(pr.In.URL.Path, "/api/garage")
pr.Out.URL.RawPath = ""
pr.Out.Host = c.adminURL.Host
pr.Out.Header.Del("Cookie")
pr.Out.Header.Del(csrfHeader)
pr.Out.Header.Set("Authorization", "Bearer "+c.adminToken)
},
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
log.Printf("garage injoignable: %v", err)
writeErr(w, http.StatusBadGateway, "API d'administration de Garage injoignable ("+c.adminURL.Host+")")
},
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := path.Clean(r.URL.Path)
if !strings.HasPrefix(p, "/api/garage/v2/") || (r.Method != http.MethodGet && r.Method != http.MethodPost) {
writeErr(w, http.StatusNotFound, "Route inconnue")
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
rp.ServeHTTP(w, r)
})
}
// Sous-commandes de la CLI garage accessibles depuis la console.
var cliAllowed = map[string]bool{
"status": true, "stats": true, "repair": true, "worker": true, "block": true,
"meta": true, "layout": true, "bucket": true, "key": true, "node": true,
}
type limitedBuf struct {
bytes.Buffer
truncated bool
}
func (b *limitedBuf) Write(p []byte) (int, error) {
const max = 1 << 20
if b.Len()+len(p) > max {
p = p[:max-b.Len()]
b.truncated = true
}
b.Buffer.Write(p)
return len(p), nil
}
func (c *config) handleCLI(w http.ResponseWriter, r *http.Request) {
if c.cliBin == "" {
writeErr(w, http.StatusNotImplemented, "Console CLI non configurée (GARAGE_BIN)")
return
}
var in struct {
Args []string `json:"args"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 16384)).Decode(&in); err != nil || len(in.Args) == 0 || len(in.Args) > 24 {
writeErr(w, 400, "Arguments invalides")
return
}
for _, a := range in.Args {
if len(a) > 300 || strings.ContainsRune(a, 0) {
writeErr(w, 400, "Argument invalide")
return
}
}
if !cliAllowed[in.Args[0]] {
writeErr(w, http.StatusForbidden, "Sous-commande non autorisée : "+in.Args[0])
return
}
args := in.Args
if c.cliConfig != "" {
args = append([]string{"-c", c.cliConfig}, args...)
}
ctx, cancel := context.WithTimeout(r.Context(), c.cliTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, c.cliBin, args...)
var env []string
for _, e := range os.Environ() {
if !strings.HasPrefix(e, "UI_") && !strings.HasPrefix(e, "SESSION_") {
env = append(env, e)
}
}
cmd.Env = env
out := &limitedBuf{}
cmd.Stdout, cmd.Stderr = out, out
start := time.Now()
err := cmd.Run()
code := 0
var ee *exec.ExitError
switch {
case errors.As(err, &ee):
code = ee.ExitCode()
case ctx.Err() != nil:
code = -1
out.WriteString("\n[délai dépassé]")
case err != nil:
code = -1
out.WriteString(err.Error())
}
log.Printf("cli: garage %s -> %d", strings.Join(in.Args, " "), code)
text := out.String()
if out.truncated {
text += "\n[sortie tronquée]"
}
writeJSON(w, 200, map[string]any{"exitCode": code, "output": text, "ms": time.Since(start).Milliseconds()})
}
// spa sert le frontend embarqué, avec repli sur index.html.
func spa() http.Handler {
dist, err := fs.Sub(web.Dist, "dist")
if err != nil {
log.Fatal(err)
}
files := http.FileServer(http.FS(dist))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if p == "" {
p = "index.html"
}
if _, err := fs.Stat(dist, p); err != nil {
if _, err := fs.Stat(dist, "index.html"); err != nil {
http.Error(w, "Frontend non compilé : cd frontend && npm ci && npm run build", http.StatusServiceUnavailable)
return
}
r.URL.Path = "/"
}
if p == "index.html" || r.URL.Path == "/" {
w.Header().Set("Cache-Control", "no-cache")
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
files.ServeHTTP(w, r)
})
}
func (c *config) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]bool{"ok": true}) })
mux.HandleFunc("GET /api/config", c.handleConfig)
mux.HandleFunc("POST /api/login", c.handleLogin)
mux.HandleFunc("POST /api/logout", c.handleLogout)
mux.HandleFunc("POST /api/cli", c.guard(c.handleCLI))
mux.Handle("/api/garage/", c.guard(c.garageProxy().ServeHTTP))
mux.Handle("/", spa())
return mux
}
func healthcheck() int {
addr := env("LISTEN_ADDR", ":8080")
if strings.HasPrefix(addr, ":") {
addr = "127.0.0.1" + addr
}
cl := http.Client{Timeout: 4 * time.Second}
resp, err := cl.Get("http://" + addr + "/api/health")
if err != nil || resp.StatusCode != 200 {
return 1
}
return 0
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(healthcheck())
}
c, err := loadConfig()
if err != nil {
log.Fatal(err)
}
if c.adminToken == "" {
log.Fatal("GARAGE_ADMIN_TOKEN est obligatoire")
}
if !c.authEnabled() {
log.Print("ATTENTION : UI_PASSWORD vide, aucune authentification (réservé à un reverse proxy qui authentifie)")
}
log.Printf("garage-ui %s sur %s, Garage : %s, CLI : %q", version, c.listen, c.adminURL.Host, c.cliBin)
srv := &http.Server{Addr: c.listen, Handler: c.routes(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute}
log.Fatal(srv.ListenAndServe())
}
+144
View File
@@ -0,0 +1,144 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
// fakeGarage enregistre la dernière requête reçue et répond {"ok":true}, sans ouvrir de port.
func fakeGarage(t *testing.T) (roundTripFunc, *http.Request) {
t.Helper()
last := &http.Request{}
return func(r *http.Request) (*http.Response, error) {
*last = *r
rec := httptest.NewRecorder()
rec.Header().Set("Content-Type", "application/json")
_, _ = rec.WriteString(`{"ok":true}`)
return rec.Result(), nil
}, last
}
func newTestConfig(t *testing.T, rt http.RoundTripper) *config {
t.Helper()
t.Setenv("GARAGE_ADMIN_URL", "http://garage.test:3903")
t.Setenv("GARAGE_ADMIN_TOKEN", "tok")
t.Setenv("UI_PASSWORD", "pw")
t.Setenv("GARAGE_BIN", "")
c, err := loadConfig()
if err != nil {
t.Fatal(err)
}
c.cliBin = "/bin/echo"
c.transport = rt
return c
}
func login(t *testing.T, h http.Handler) *http.Cookie {
t.Helper()
req := httptest.NewRequest("POST", "/api/login", strings.NewReader(`{"user":"admin","password":"pw"}`))
req.Header.Set(csrfHeader, "x")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("login: %d %s", rec.Code, rec.Body)
}
for _, ck := range rec.Result().Cookies() {
if ck.Name == cookieName {
return ck
}
}
t.Fatal("pas de cookie de session")
return nil
}
func TestAuthRequiredAndBadLogin(t *testing.T) {
g, _ := fakeGarage(t)
h := newTestConfig(t, g).routes()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/garage/v2/ListBuckets", nil))
if rec.Code != 401 {
t.Fatalf("sans session : %d, attendu 401", rec.Code)
}
req := httptest.NewRequest("POST", "/api/login", strings.NewReader(`{"user":"admin","password":"nope"}`))
req.Header.Set(csrfHeader, "x")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 401 {
t.Fatalf("mauvais mot de passe : %d, attendu 401", rec.Code)
}
}
func TestProxyInjectsTokenAndRestrictsPaths(t *testing.T) {
g, last := fakeGarage(t)
h := newTestConfig(t, g).routes()
ck := login(t, h)
req := httptest.NewRequest("GET", "/api/garage/v2/ListBuckets?x=1", nil)
req.AddCookie(ck)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 || last.URL.Path != "/v2/ListBuckets" || last.URL.RawQuery != "x=1" {
t.Fatalf("proxy : %d, chemin %q", rec.Code, last.URL.String())
}
if last.Header.Get("Authorization") != "Bearer tok" {
t.Fatalf("jeton non injecté : %q", last.Header.Get("Authorization"))
}
if last.Header.Get("Cookie") != "" {
t.Fatal("le cookie de session ne doit pas partir vers Garage")
}
// Hors /v2/ (ex. /metrics) et traversée de chemin : refusés.
for _, p := range []string{"/api/garage/metrics", "/api/garage/v2/../metrics", "/api/garage/v1/status"} {
req = httptest.NewRequest("GET", p, nil)
req.AddCookie(ck)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
// 404, ou 307 vers le chemin nettoyé (le mux Go) : dans les deux cas rien n'est relayé.
if rec.Code != 404 && rec.Code != 307 {
t.Errorf("%s : %d, attendu 404 ou 307", p, rec.Code)
}
}
}
func TestMutationNeedsCSRFHeader(t *testing.T) {
g, _ := fakeGarage(t)
h := newTestConfig(t, g).routes()
ck := login(t, h)
req := httptest.NewRequest("POST", "/api/garage/v2/DeleteBucket?id=x", strings.NewReader("{}"))
req.AddCookie(ck)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 403 {
t.Fatalf("sans en-tête anti-CSRF : %d, attendu 403", rec.Code)
}
}
func TestCLIWhitelist(t *testing.T) {
g, _ := fakeGarage(t)
h := newTestConfig(t, g).routes()
ck := login(t, h)
call := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/cli", strings.NewReader(body))
req.Header.Set(csrfHeader, "x")
req.AddCookie(ck)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
if rec := call(`{"args":["status"]}`); rec.Code != 200 || !strings.Contains(rec.Body.String(), `"exitCode":0`) {
t.Fatalf("status : %d %s", rec.Code, rec.Body)
}
for _, b := range []string{`{"args":["server"]}`, `{"args":["offline-repair"]}`, `{"args":[]}`, `{"args":["status","a\u0000b"]}`} {
if rec := call(b); rec.Code == 200 {
t.Errorf("%s devrait être refusé", b)
}
}
}
+27
View File
@@ -0,0 +1,27 @@
# Garage UI : à lancer à côté de Garage (même hôte ou même réseau Docker).
services:
garage-ui:
build: .
image: garage-ui:local
restart: unless-stopped
ports:
- "${GARAGE_UI_PORT:-8088}:8080"
environment:
# API d'administration de Garage (port 3903). Sur le même réseau Docker : http://garage:3903
GARAGE_ADMIN_URL: ${GARAGE_ADMIN_URL:-http://garage:3903}
GARAGE_ADMIN_TOKEN: ${GARAGE_ADMIN_TOKEN:?définir GARAGE_ADMIN_TOKEN dans .env}
# Authentification de l'interface (vide : aucune, à réserver à un reverse proxy qui authentifie).
UI_USER: ${UI_USER:-admin}
UI_PASSWORD: ${UI_PASSWORD:-}
PUBLIC_URL: ${PUBLIC_URL:-}
TITLE: ${TITLE:-Garage UI}
# Exemples de configuration client affichés sur la page d'une clé.
GARAGE_S3_ENDPOINT: ${GARAGE_S3_ENDPOINT:-}
GARAGE_S3_REGION: ${GARAGE_S3_REGION:-garage}
# Console CLI : le binaire garage est dans l'image ; il lui faut l'adresse RPC et le secret.
GARAGE_RPC_HOST: ${GARAGE_RPC_HOST:-garage:3901}
GARAGE_RPC_SECRET: ${GARAGE_RPC_SECRET:-}
read_only: true
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#6965db" />
<meta name="robots" content="noindex" />
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236965db' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 8h16v11a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z'/%3E%3Cpath d='M3 4h18v4H3zM10 12h4'/%3E%3C/svg%3E" />
<title>Garage UI</title>
<script src="/theme.js"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3402
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "garage-ui-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "^5.8.0",
"vite": "^7.0.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
// Thème appliqué avant le premier rendu (évite un flash clair). Fichier externe : la CSP interdit les scripts inline.
try {
var t = localStorage.getItem("udTheme");
if (t === "dark" || t === "light") document.documentElement.dataset.theme = t;
else if (matchMedia("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
} catch (e) {}
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { createPortal } from "react-dom";
interface Props {
/** Bouton « … » qui a ouvert le menu : le menu s'aligne sur lui. */
anchor: HTMLElement;
onClose: () => void;
children: ReactNode;
}
const MARGIN = 8; // écart minimal avec les bords de la fenêtre
/**
* Menu déroulant des actions d'un élément, ouvert sous le bouton « … » et aligné
* sur son bord droit (au-dessus s'il manque de place en bas). Rendu dans <body>
* pour ne pas être rogné par le défilement de la liste ; refermé par un clic
* ailleurs, Échap, un défilement, un redimensionnement ou le choix d'une action.
*/
export function ActionMenu({ anchor, onClose, children }: Props) {
const ref = useRef<HTMLDivElement>(null);
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
useLayoutEffect(() => {
const menu = ref.current;
if (!menu) return;
const a = anchor.getBoundingClientRect();
const { offsetWidth: w, offsetHeight: h } = menu;
let top = a.bottom + 4;
if (top + h > innerHeight - MARGIN) top = Math.max(MARGIN, a.top - 4 - h);
const left = Math.min(Math.max(MARGIN, a.right - w), innerWidth - w - MARGIN);
setPos({ top, left });
}, [anchor]);
// Focus sur la première action une fois le menu placé (masqué, il ne le prend pas).
useEffect(() => {
if (pos) ref.current?.querySelector<HTMLElement>("button, a")?.focus({ preventScroll: true });
}, [pos]);
useEffect(() => {
const inside = (t: EventTarget | null) => t instanceof Node && (ref.current?.contains(t) || anchor.contains(t));
const onDown = (ev: PointerEvent) => {
if (!inside(ev.target)) onClose();
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === "Escape") {
// Ni désélection, ni fermeture du panneau flottant : seulement le menu.
ev.preventDefault();
ev.stopPropagation();
onClose();
anchor.focus();
} else if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
const items = [...(ref.current?.querySelectorAll<HTMLElement>("button, a") ?? [])];
if (!items.length) return;
ev.preventDefault();
const i = items.indexOf(document.activeElement as HTMLElement);
const next = ev.key === "ArrowDown" ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
items[next].focus();
}
};
const onScroll = (ev: Event) => {
if (!(ev.target instanceof Node && ref.current?.contains(ev.target))) onClose();
};
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("keydown", onKey, true);
document.addEventListener("scroll", onScroll, true);
window.addEventListener("resize", onClose);
return () => {
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", onClose);
};
}, [anchor, onClose]);
return createPortal(
<div
ref={ref}
className="actions menu-popup"
role="menu"
style={pos ?? { top: 0, left: 0, visibility: "hidden" }}
// Une action choisie referme le menu (après coup, pour laisser un lien de
// téléchargement aboutir).
onClick={(ev) => {
if ((ev.target as HTMLElement).closest("button, a")) setTimeout(onClose);
}}
>
{children}
</div>,
document.body,
);
}
+170
View File
@@ -0,0 +1,170 @@
import { Component, useCallback, useEffect, useState, type ReactNode } from "react";
import { appApi, errMsg, type Config } from "./api";
import { BucketPage, Buckets } from "./Buckets";
import { Cluster } from "./Cluster";
import { Console } from "./Console";
import { ClusterIcon, BucketIcon, ConsoleIcon, MaintenanceIcon, OverviewIcon } from "./gicons";
import { KeyIcon, LogoutIcon, MenuIcon, MoonIcon, SunIcon } from "./icons";
import { KeyPage, Keys } from "./Keys";
import { Login } from "./Login";
import { Maintenance } from "./Maintenance";
import { Overview } from "./Overview";
import { ToastProvider } from "./ui";
/** Une erreur d'affichage dans une page ne doit pas blanchir toute l'application. */
class Boundary extends Component<{ children: ReactNode }, { error: Error | null }> {
state = { error: null as Error | null };
static getDerivedStateFromError(error: Error) {
return { error };
}
render() {
return this.state.error ? (
<div className="page">
<p className="error" style={{ cursor: "default" }}>
Erreur d'affichage : {this.state.error.message}
</p>
</div>
) : (
this.props.children
);
}
}
type Theme = "light" | "dark";
const initialTheme = (): Theme => (document.documentElement.dataset.theme === "dark" ? "dark" : "light");
/** Route issue de l'adresse (#/buckets/<id>) : liens directs et bouton « précédent ». */
const useRoute = () => {
const get = () => location.hash.replace(/^#\/?/, "").split("/").map(decodeURIComponent);
const [route, setRoute] = useState(get);
useEffect(() => {
const on = () => setRoute(get());
window.addEventListener("hashchange", on);
return () => window.removeEventListener("hashchange", on);
}, []);
return route;
};
export default function App() {
const [cfg, setCfg] = useState<Config | null>(null);
const [error, setError] = useState("");
const load = useCallback(() => appApi.config().then((c) => (setCfg(c), setError("")), (e) => setError(errMsg(e))), []);
useEffect(() => {
load();
}, [load]);
if (error)
return (
<main className="login">
<div className="login-card center">
<p className="error">{error}</p>
<button className="primary" onClick={load}>
Réessayer
</button>
</div>
</main>
);
if (!cfg) return <div className="splash muted">Chargement…</div>;
if (cfg.auth && !cfg.user) return <Login cfg={cfg} onLoggedIn={load} />;
return (
<ToastProvider>
<Shell cfg={cfg} reload={load} />
</ToastProvider>
);
}
const NAV = [
["", "Vue d'ensemble", OverviewIcon],
["buckets", "Buckets", BucketIcon],
["keys", "Clés d'accès", KeyIcon],
["cluster", "Cluster", ClusterIcon],
["maintenance", "Maintenance", MaintenanceIcon],
["console", "Console", ConsoleIcon],
] as const;
function Shell({ cfg, reload }: { cfg: Config; reload: () => void }) {
const [theme, setTheme] = useState<Theme>(initialTheme);
const [drawer, setDrawer] = useState(false);
const [section, id] = useRoute();
useEffect(() => {
document.documentElement.dataset.theme = theme;
document.title = cfg.title;
try {
localStorage.setItem("udTheme", theme);
} catch {
/* stockage indisponible */
}
}, [theme, cfg.title]);
useEffect(() => {
setDrawer(false);
}, [section, id]);
const page = (() => {
switch (section) {
case "buckets":
return id ? <BucketPage id={id} key={id} /> : <Buckets />;
case "keys":
return id ? <KeyPage id={id} key={id} cfg={cfg} /> : <Keys cfg={cfg} />;
case "cluster":
return <Cluster />;
case "maintenance":
return <Maintenance />;
case "console":
return <Console cfg={cfg} />;
default:
return <Overview />;
}
})();
return (
<div className="app">
<header className="topbar">
<button className="icon-btn menu-btn-inline" onClick={() => setDrawer(!drawer)} aria-label="Menu" title="Menu">
<MenuIcon />
</button>
<a className="brand" href="#/" title={cfg.title}>
<BucketIcon size={26} />
<span>{cfg.title}</span>
</a>
<div className="topbar-tools">
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
</button>
{cfg.auth && (
<button
className="icon-btn"
onClick={async () => {
await appApi.logout();
reload();
}}
aria-label={`Se déconnecter (${cfg.user})`}
title={`Se déconnecter (${cfg.user})`}
>
<LogoutIcon />
</button>
)}
</div>
</header>
<div className="layout">
{drawer && <div className="scrim" onClick={() => setDrawer(false)} />}
<aside className={`sidebar ${drawer ? "open" : ""}`}>
<nav>
{NAV.map(([key, label, Icon]) => (
<a key={key} className={`nav-item ${section === key || (!section && key === "") ? "on" : ""}`} href={`#/${key}`} aria-current={(section || "") === key ? "page" : undefined}>
<Icon />
<span>{label}</span>
</a>
))}
</nav>
<div className="sidebar-foot">
<small className="muted">Garage UI {cfg.version !== "dev" ? `v${cfg.version}` : ""}</small>
</div>
</aside>
<main className="main">
<Boundary key={`${section}/${id}`}>{page}</Boundary>
</main>
</div>
</div>
);
}
+385
View File
@@ -0,0 +1,385 @@
import { useState } from "react";
import { garage, bucketName, type BucketInfo, type BucketListItem, type KeyListItem, type Perm } from "./api";
import { GIB, fmtDate, fmtNum, fmtSize } from "./format";
import { BucketIcon, GlobeIcon } from "./gicons";
import { CloseIcon, PlusIcon, RefreshIcon, TrashIcon } from "./icons";
import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad } from "./ui";
// --- Liste -------------------------------------------------------------------------
export function Buckets() {
const act = useAct();
const [filter, setFilter] = useState("");
const [creating, setCreating] = useState(false);
const { data, error, loading, reload } = useLoad(async () => {
const list = await garage.get<BucketListItem[]>("ListBuckets");
const infos = await Promise.all(list.map((b) => garage.get<BucketInfo>("GetBucketInfo", { id: b.id }).catch(() => null)));
return list.map((b, i) => ({ b, info: infos[i] }));
});
const rows = (data ?? []).filter(({ b }) => bucketName(b).toLowerCase().includes(filter.toLowerCase()));
return (
<div className="page">
<PageHead title="Buckets">
<input type="search" placeholder="Filtrer…" value={filter} onChange={(e) => setFilter(e.target.value)} aria-label="Filtrer les buckets" />
<button onClick={reload} disabled={loading} aria-label="Actualiser" title="Actualiser">
<RefreshIcon />
</button>
<button className="primary" onClick={() => setCreating(true)}>
<PlusIcon /> Nouveau bucket
</button>
</PageHead>
<Loading loading={loading && !data} error={error} onRetry={reload} />
{data && (
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Nom</th>
<th className="num">Objets</th>
<th className="num">Taille</th>
<th>Quota</th>
<th>Clés</th>
<th>Créé</th>
</tr>
</thead>
<tbody>
{rows.map(({ b, info }) => (
<tr key={b.id} className="click" onClick={() => (location.hash = `#/buckets/${b.id}`)}>
<td>
<a href={`#/buckets/${b.id}`} className="name" onClick={(e) => e.stopPropagation()}>
<BucketIcon /> {bucketName(b)}
</a>
{info?.websiteAccess && (
<span className="pill" title="Site web statique activé">
<GlobeIcon size={12} /> web
</span>
)}
{b.globalAliases.length > 1 && <span className="pill">+{b.globalAliases.length - 1} alias</span>}
</td>
<td className="num">{fmtNum(info?.objects)}</td>
<td className="num">{fmtSize(info?.bytes)}</td>
<td className="quota">
{info?.quotas?.maxSize ? (
<>
<UsageBar used={info.bytes} total={info.quotas.maxSize} />
<small className="muted">{fmtSize(info.quotas.maxSize)}</small>
</>
) : (
<span className="muted">-</span>
)}
</td>
<td>{info?.keys.length ?? "-"}</td>
<td className="muted">{fmtDate(b.created)}</td>
</tr>
))}
{rows.length === 0 && (
<tr>
<td colSpan={6} className="muted center">
Aucun bucket.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
{creating && (
<CreateBucket
onClose={() => setCreating(false)}
onCreate={async (alias) => {
const created = await act(() => garage.post<BucketInfo>("CreateBucket", undefined, { globalAlias: alias }), `Bucket « ${alias} » créé`);
if (created) {
setCreating(false);
reload();
}
}}
/>
)}
</div>
);
}
function CreateBucket({ onClose, onCreate }: { onClose: () => void; onCreate: (alias: string) => Promise<void> }) {
const [alias, setAlias] = useState("");
const valid = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(alias);
return (
<Modal title="Nouveau bucket" onClose={onClose} small>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
if (valid) onCreate(alias);
}}
>
<label className="field">
<span>Nom (alias global)</span>
<input type="text" value={alias} onChange={(e) => setAlias(e.target.value.trim())} autoFocus placeholder="mon-bucket" />
</label>
<p className="muted small-text">3 à 63 caractères : minuscules, chiffres, points et tirets.</p>
<div className="modal-actions">
<span className="spacer" />
<button type="button" onClick={onClose}>
Annuler
</button>
<button className="primary" disabled={!valid}>
Créer
</button>
</div>
</form>
</Modal>
);
}
// --- Détail ------------------------------------------------------------------------
export function BucketPage({ id }: { id: string }) {
const act = useAct();
const { data: b, error, loading, reload } = useLoad(() => garage.get<BucketInfo>("GetBucketInfo", { id }), [id]);
const keys = useLoad(() => garage.get<KeyListItem[]>("ListKeys"), []);
const [confirmDelete, setConfirmDelete] = useState(false);
const [alias, setAlias] = useState("");
const [addKey, setAddKey] = useState("");
if (!b) return <div className="page"><PageHead title="Bucket" back={{ href: "#/buckets", label: "Buckets" }} /><Loading loading={loading} error={error} onRetry={reload} /></div>;
const name = bucketName(b);
const run = (fn: () => Promise<unknown>, ok?: string) => act(fn, ok).then((r) => r && reload());
const setPerm = (accessKeyId: string, key: keyof Perm, value: boolean) =>
run(() => garage.post(value ? "AllowBucketKey" : "DenyBucketKey", undefined, { bucketId: b.id, accessKeyId, permissions: { [key]: true } }));
const available = (keys.data ?? []).filter((k) => !b.keys.some((bk) => bk.accessKeyId === k.id));
return (
<div className="page">
<PageHead title={name} back={{ href: "#/buckets", label: "Buckets" }}>
<button className="danger-outline" onClick={() => setConfirmDelete(true)}>
<TrashIcon /> Supprimer
</button>
</PageHead>
<div className="cards">
<div className="card">
<span className="k">Objets</span>
<strong className="v">{fmtNum(b.objects)}</strong>
</div>
<div className="card">
<span className="k">Taille</span>
<strong className="v">{fmtSize(b.bytes)}</strong>
</div>
<div className="card">
<span className="k">Envois inachevés</span>
<strong className="v">{fmtNum(b.unfinishedMultipartUploads)}</strong>
<small className="muted">{fmtSize(b.unfinishedMultipartUploadBytes)}</small>
</div>
<div className="card">
<span className="k">Identifiant</span>
<strong className="v row">
<Mono value={b.id} short={10} />
<CopyButton text={b.id} />
</strong>
<small className="muted">créé le {fmtDate(b.created)}</small>
</div>
</div>
<section className="panel">
<h3>Alias</h3>
<div className="chips">
{b.globalAliases.map((a) => (
<span className="chip on" key={a}>
{a}
<button
className="icon-btn"
aria-label={`Retirer l'alias ${a}`}
disabled={b.globalAliases.length + b.localAliases.length < 2}
title={b.globalAliases.length + b.localAliases.length < 2 ? "Dernier alias : impossible à retirer" : "Retirer"}
onClick={() => run(() => garage.post("RemoveBucketAlias", undefined, { bucketId: b.id, globalAlias: a }), "Alias retiré")}
>
<CloseIcon size={12} />
</button>
</span>
))}
{b.localAliases.map((a) => (
<span className="chip" key={a.accessKeyId + a.alias} title={`Alias local de la clé ${a.accessKeyId}`}>
{a.alias} <small>({a.accessKeyId.slice(0, 8)}…)</small>
</span>
))}
</div>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
if (alias) run(() => garage.post("AddBucketAlias", undefined, { bucketId: b.id, globalAlias: alias }), "Alias ajouté").then(() => setAlias(""));
}}
>
<input type="text" value={alias} onChange={(e) => setAlias(e.target.value.trim())} placeholder="Nouvel alias global" aria-label="Nouvel alias global" />
<button disabled={!alias}>
<PlusIcon /> Ajouter
</button>
</form>
</section>
<section className="panel">
<h3>Clés autorisées</h3>
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Clé</th>
<th className="c">Lecture</th>
<th className="c">Écriture</th>
<th className="c">Propriétaire</th>
</tr>
</thead>
<tbody>
{b.keys.map((k) => (
<tr key={k.accessKeyId}>
<td>
<a href={`#/keys/${k.accessKeyId}`}>{k.name || "(sans nom)"}</a> <Mono value={k.accessKeyId} short={10} />
</td>
{(["read", "write", "owner"] as const).map((p) => (
<td className="c" key={p}>
<input type="checkbox" checked={!!k.permissions[p]} onChange={(e) => setPerm(k.accessKeyId, p, e.target.checked)} aria-label={`${p} pour ${k.name}`} />
</td>
))}
</tr>
))}
{b.keys.length === 0 && (
<tr>
<td colSpan={4} className="muted center">
Aucune clé n'a accès à ce bucket.
</td>
</tr>
)}
</tbody>
</table>
</div>
{available.length > 0 && (
<div className="inline-form">
<select value={addKey} onChange={(e) => setAddKey(e.target.value)} aria-label="Clé à autoriser">
<option value="">Autoriser une clé…</option>
{available.map((k) => (
<option key={k.id} value={k.id}>
{k.name || k.id}
</option>
))}
</select>
<button
disabled={!addKey}
onClick={() => run(() => garage.post("AllowBucketKey", undefined, { bucketId: b.id, accessKeyId: addKey, permissions: { read: true, write: true, owner: false } }), "Clé autorisée").then(() => setAddKey(""))}
>
<PlusIcon /> Lecture + écriture
</button>
</div>
)}
</section>
<div className="cols">
<QuotaForm b={b} onSave={(q) => run(() => garage.post("UpdateBucket", { id: b.id }, { quotas: q }), "Quotas enregistrés")} />
<WebsiteForm
b={b}
onSave={(w) => run(() => garage.post("UpdateBucket", { id: b.id }, { websiteAccess: w }), "Site web enregistré")}
/>
</div>
<section className="panel">
<h3>Maintenance</h3>
<p className="muted small-text">
Les envois multipart abandonnés occupent de la place sans apparaître comme objets. Supprime ceux de plus de 24 heures.
</p>
<button onClick={() => run(() => garage.post("CleanupIncompleteUploads", undefined, { bucketId: b.id, olderThanSecs: 86400 }), "Envois inachevés nettoyés")}>
Nettoyer les envois inachevés
</button>
</section>
{confirmDelete && (
<Confirm
title="Supprimer le bucket"
message={
<p>
Le bucket <strong>{name}</strong> sera supprimé définitivement. Garage refuse de supprimer un bucket qui contient encore des objets.
</p>
}
confirmLabel="Supprimer"
requireText={name}
onClose={() => setConfirmDelete(false)}
onConfirm={async () => {
if (await act(() => garage.post("DeleteBucket", { id: b.id }), "Bucket supprimé")) location.hash = "#/buckets";
else setConfirmDelete(false);
}}
/>
)}
</div>
);
}
function QuotaForm({ b, onSave }: { b: BucketInfo; onSave: (q: { maxSize: number | null; maxObjects: number | null }) => void }) {
const [size, setSize] = useState(b.quotas?.maxSize ? String(+(b.quotas.maxSize / GIB).toFixed(2)) : "");
const [objs, setObjs] = useState(b.quotas?.maxObjects ? String(b.quotas.maxObjects) : "");
return (
<section className="panel">
<h3>Quotas</h3>
{b.quotas?.maxSize ? <UsageBar used={b.bytes} total={b.quotas.maxSize} /> : null}
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
onSave({ maxSize: size ? Math.round(parseFloat(size) * GIB) : null, maxObjects: objs ? parseInt(objs, 10) : null });
}}
>
<div className="grid2">
<label className="field">
<span>Taille maximale (Go)</span>
<input type="number" min="0" step="any" value={size} onChange={(e) => setSize(e.target.value)} placeholder="illimitée" />
</label>
<label className="field">
<span>Nombre d'objets maximal</span>
<input type="number" min="0" step="1" value={objs} onChange={(e) => setObjs(e.target.value)} placeholder="illimité" />
</label>
</div>
<div>
<button className="primary">Enregistrer</button>
</div>
</form>
</section>
);
}
function WebsiteForm({ b, onSave }: { b: BucketInfo; onSave: (w: { enabled: boolean; indexDocument?: string; errorDocument?: string | null }) => void }) {
const [on, setOn] = useState(b.websiteAccess);
const [index, setIndex] = useState(b.websiteConfig?.indexDocument ?? "index.html");
const [err, setErr] = useState(b.websiteConfig?.errorDocument ?? "");
return (
<section className="panel">
<h3>
Site web statique <Status kind={b.websiteAccess ? "ok" : "off"}>{b.websiteAccess ? "activé" : "désactivé"}</Status>
</h3>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
onSave(on ? { enabled: true, indexDocument: index || "index.html", errorDocument: err || null } : { enabled: false });
}}
>
<label className="check-row">
<input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} />
<span>Servir ce bucket comme un site web (port 3902)</span>
</label>
{on && (
<div className="grid2">
<label className="field">
<span>Document d'index</span>
<input type="text" value={index} onChange={(e) => setIndex(e.target.value)} />
</label>
<label className="field">
<span>Document d'erreur</span>
<input type="text" value={err} onChange={(e) => setErr(e.target.value)} placeholder="facultatif" />
</label>
</div>
)}
<div>
<button className="primary">Enregistrer</button>
</div>
</form>
</section>
);
}
+284
View File
@@ -0,0 +1,284 @@
import { useState } from "react";
import { garage, type ClusterLayout, type ClusterStatus, type NodeInfo } from "./api";
import { fmtAgo, fmtSize } from "./format";
import { EditIcon, PlusIcon, RefreshIcon, TrashIcon } from "./icons";
import { Confirm, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad } from "./ui";
const GB = 1e9; // Garage raisonne en octets ; on saisit des Go décimaux, comme dans la doc
export function Cluster() {
const act = useAct();
const { data, error, loading, reload } = useLoad(async () => {
const [status, layout] = await Promise.all([garage.get<ClusterStatus>("GetClusterStatus"), garage.get<ClusterLayout>("GetClusterLayout")]);
return { status, layout };
});
const [edit, setEdit] = useState<NodeInfo | null>(null);
const [connect, setConnect] = useState(false);
const [preview, setPreview] = useState<string[] | null>(null);
const [confirmRevert, setConfirmRevert] = useState(false);
const [removing, setRemoving] = useState<NodeInfo | null>(null);
const run = (fn: () => Promise<unknown>, ok?: string) => act(fn, ok).then((r) => r && reload());
const staged = data?.layout.stagedRoleChanges ?? [];
const stagedOf = (id: string) => staged.find((s) => s.id === id);
const showPreview = async () => {
const r = await garage.post<{ error?: string; message?: string[] }>("PreviewClusterLayoutChanges");
if (r.error) throw new Error(r.error);
setPreview(r.message ?? ["Aucun détail."]);
};
return (
<div className="page">
<PageHead title="Cluster">
<button onClick={reload} disabled={loading} aria-label="Actualiser" title="Actualiser">
<RefreshIcon />
</button>
<button onClick={() => setConnect(true)}>Connecter un nœud</button>
</PageHead>
<Loading loading={loading && !data} error={error} onRetry={reload} />
{data && (
<>
{staged.length > 0 && (
<div className="notice staged">
<strong>{staged.length} changement(s) de layout en attente.</strong> Ils ne sont appliqués qu'après validation : Garage redistribue alors les données entre les nœuds.
<div className="row" style={{ marginTop: "0.5rem" }}>
<button onClick={() => act(showPreview)}>Prévisualiser</button>
<button className="primary" onClick={() => run(() => garage.post("ApplyClusterLayout", undefined, { version: data.layout.version + 1 }), "Layout appliqué")}>
Appliquer
</button>
<button onClick={() => setConfirmRevert(true)}>Annuler les changements</button>
</div>
</div>
)}
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Nœud</th>
<th>État</th>
<th>Zone</th>
<th className="num">Capacité</th>
<th>Données</th>
<th>Version</th>
<th />
</tr>
</thead>
<tbody>
{data.status.nodes.map((n) => {
const s = stagedOf(n.id);
const used = n.dataPartition ? n.dataPartition.total - n.dataPartition.available : 0;
return (
<tr key={n.id}>
<td>
<strong>{n.hostname || "(sans nom)"}</strong>
<div>
<Mono value={n.id} short={16} /> <small className="muted">{n.addr}</small>
</div>
</td>
<td>
<Status kind={n.isUp ? "ok" : "bad"}>{n.isUp ? "en ligne" : "hors ligne"}</Status>
{!n.isUp && <small className="muted"> {fmtAgo(n.lastSeenSecsAgo)}</small>}
{n.draining && <Status kind="warn">vidange</Status>}
</td>
<td>
{n.role ? n.role.zone : <span className="muted">sans rôle</span>}
{n.role?.tags?.length ? <small className="muted"> [{n.role.tags.join(", ")}]</small> : null}
{s && <Status kind="warn">{s.remove ? "retrait prévu" : "modifié"}</Status>}
</td>
<td className="num">{n.role ? (n.role.capacity != null ? fmtSize(n.role.capacity) : "passerelle") : "-"}</td>
<td className="quota">
{n.dataPartition ? (
<>
<UsageBar used={used} total={n.dataPartition.total} />
<small className="muted">
{fmtSize(used)} / {fmtSize(n.dataPartition.total)}
</small>
</>
) : (
<span className="muted">-</span>
)}
</td>
<td className="muted">{n.garageVersion ?? "-"}</td>
<td className="actions-cell">
<button className="icon-btn" onClick={() => setEdit(n)} aria-label="Modifier le rôle" title={n.role ? "Modifier le rôle" : "Assigner un rôle"}>
{n.role ? <EditIcon /> : <PlusIcon />}
</button>
{n.role && (
<button className="icon-btn danger" onClick={() => setRemoving(n)} aria-label="Retirer du layout" title="Retirer du layout">
<TrashIcon />
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p className="muted small-text">
Version du layout : {data.layout.version}
{data.layout.partitionSize ? ` · partitions de ${fmtSize(data.layout.partitionSize)}` : ""}
</p>
</>
)}
{edit && (
<RoleForm
node={edit}
staged={stagedOf(edit.id)}
onClose={() => setEdit(null)}
onSave={async (role) => {
if (await act(() => garage.post("UpdateClusterLayout", undefined, { roles: [{ id: edit.id, ...role }] }), "Changement mis en attente")) {
setEdit(null);
reload();
}
}}
/>
)}
{connect && <ConnectForm onClose={() => setConnect(false)} onDone={() => (setConnect(false), reload())} />}
{preview && (
<Modal title="Effet du layout" onClose={() => setPreview(null)}>
<pre className="out">{preview.join("\n")}</pre>
<div className="modal-actions">
<span className="spacer" />
<button className="primary" onClick={() => setPreview(null)}>
Fermer
</button>
</div>
</Modal>
)}
{confirmRevert && (
<Confirm
title="Annuler les changements"
message={<p>Les changements de layout en attente seront abandonnés.</p>}
confirmLabel="Annuler les changements"
onClose={() => setConfirmRevert(false)}
onConfirm={async () => {
setConfirmRevert(false);
await run(() => garage.post("RevertClusterLayout"), "Changements abandonnés");
}}
/>
)}
{removing && (
<Confirm
title="Retirer le nœud du layout"
message={
<p>
<strong>{removing.hostname || removing.id.slice(0, 12)}</strong> n'aura plus de rôle de stockage. Le changement est mis en attente : il faudra l'appliquer, et Garage redistribuera alors ses données sur les autres nœuds.
</p>
}
confirmLabel="Mettre en attente"
onClose={() => setRemoving(null)}
onConfirm={async () => {
const id = removing.id;
setRemoving(null);
await run(() => garage.post("UpdateClusterLayout", undefined, { roles: [{ id, remove: true }] }), "Retrait mis en attente");
}}
/>
)}
</div>
);
}
function RoleForm({
node,
staged,
onClose,
onSave,
}: {
node: NodeInfo;
staged?: { zone?: string; capacity?: number | null; tags?: string[]; remove?: boolean };
onClose: () => void;
onSave: (r: { zone: string; capacity: number | null; tags: string[] }) => Promise<void>;
}) {
const cur = staged && !staged.remove ? staged : node.role;
const [zone, setZone] = useState(cur?.zone ?? "dc1");
const [gateway, setGateway] = useState(cur ? cur.capacity == null : false);
const [cap, setCap] = useState(cur?.capacity ? String(cur.capacity / GB) : "");
const [tags, setTags] = useState((cur?.tags ?? []).join(", "));
const valid = zone.trim() !== "" && (gateway || parseFloat(cap) > 0);
return (
<Modal title={`Rôle de ${node.hostname || node.id.slice(0, 12)}`} onClose={onClose}>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
onSave({
zone: zone.trim(),
capacity: gateway ? null : Math.round(parseFloat(cap) * GB),
tags: tags.split(",").map((t) => t.trim()).filter(Boolean),
});
}}
>
<label className="field">
<span>Zone</span>
<input type="text" value={zone} onChange={(e) => setZone(e.target.value)} autoFocus />
</label>
<label className="check-row">
<input type="checkbox" checked={gateway} onChange={(e) => setGateway(e.target.checked)} />
<span>Nœud passerelle (aucun stockage de données)</span>
</label>
{!gateway && (
<label className="field">
<span>Capacité (Go)</span>
<input type="number" min="0" step="any" value={cap} onChange={(e) => setCap(e.target.value)} placeholder="ex. 500" />
</label>
)}
<label className="field">
<span>Étiquettes (séparées par des virgules)</span>
<input type="text" value={tags} onChange={(e) => setTags(e.target.value)} />
</label>
<div className="modal-actions">
<span className="spacer" />
<button type="button" onClick={onClose}>
Annuler
</button>
<button className="primary" disabled={!valid}>
Mettre en attente
</button>
</div>
</form>
</Modal>
);
}
function ConnectForm({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
const act = useAct();
const [addr, setAddr] = useState("");
return (
<Modal title="Connecter un nœud" onClose={onClose} small>
<form
className="form"
onSubmit={async (e) => {
e.preventDefault();
const r = await garage.post<{ success: boolean; error?: string }[]>("ConnectClusterNodes", undefined, [addr]).catch((er) => {
act(async () => {
throw er;
});
return null;
});
if (!r) return;
if (r[0]?.success) onDone();
else act(async () => { throw new Error(r[0]?.error || "Connexion refusée"); });
}}
>
<label className="field">
<span>Identifiant@adresse:port RPC</span>
<input type="text" value={addr} onChange={(e) => setAddr(e.target.value.trim())} placeholder="563e1ac8…@10.0.0.2:3901" autoFocus />
</label>
<div className="modal-actions">
<span className="spacer" />
<button type="button" onClick={onClose}>
Annuler
</button>
<button className="primary" disabled={!addr.includes("@")}>
Connecter
</button>
</div>
</form>
</Modal>
);
}
+131
View File
@@ -0,0 +1,131 @@
import { useEffect, useRef, useState } from "react";
import { appApi, errMsg, type Config } from "./api";
import { splitArgs } from "./format";
import { PageHead } from "./ui";
interface Entry {
cmd: string;
out: string;
code: number;
ms: number;
}
const PRESETS: [string, string][] = [
["Statut", "status"],
["Statistiques", "stats -a"],
["Layout", "layout show"],
["Tâches", "worker list"],
["Blocs en erreur", "block list-errors"],
["Buckets", "bucket list"],
["Clés", "key list"],
["Snapshot métadonnées", "meta snapshot --all"],
];
export function Console({ cfg }: { cfg: Config }) {
const [line, setLine] = useState("");
const [log, setLog] = useState<Entry[]>([]);
const [busy, setBusy] = useState(false);
const [hist, setHist] = useState<string[]>([]);
const [hi, setHi] = useState(-1);
const end = useRef<HTMLDivElement>(null);
useEffect(() => {
end.current?.scrollIntoView({ block: "end" });
}, [log]);
const run = async (text: string) => {
const args = splitArgs(text.replace(/^garage\s+/, ""));
if (!args.length || busy) return;
setBusy(true);
setHist((h) => [text, ...h.filter((x) => x !== text)].slice(0, 30));
setHi(-1);
try {
const r = await appApi.cli(args);
setLog((l) => [...l, { cmd: text, out: r.output, code: r.exitCode, ms: r.ms }]);
} catch (e) {
setLog((l) => [...l, { cmd: text, out: errMsg(e), code: -1, ms: 0 }]);
}
setBusy(false);
setLine("");
};
if (!cfg.cli)
return (
<div className="page">
<PageHead title="Console" />
<div className="notice">
<p>
La console CLI n'est pas configurée. Elle exécute le binaire <code>garage</code> depuis le serveur de l'interface : renseignez <code>GARAGE_BIN</code> (l'image fournie l'embarque déjà),{" "}
<code>GARAGE_RPC_HOST</code> et <code>GARAGE_RPC_SECRET</code> (valeur de <code>rpc_secret</code> dans <code>garage.toml</code>).
</p>
<p>Les autres pages passent par l'API d'administration et n'en ont pas besoin.</p>
</div>
</div>
);
return (
<div className="page console-page">
<PageHead title="Console" />
<div className="chips">
{PRESETS.map(([l, c]) => (
<button className="chip" key={c} disabled={busy} onClick={() => run(c)} title={`garage ${c}`}>
{l}
</button>
))}
</div>
<div className="console" role="log" aria-live="polite">
{log.length === 0 && <span className="muted">Choisissez une commande ci-dessus ou tapez-en une (sans le préfixe « garage »).</span>}
{log.map((e, i) => (
<div key={i} className="entry">
<div className="cmd">
<span className="prompt">$ garage</span> {e.cmd}
<small className={e.code === 0 ? "muted" : "error-text"}>
{" "}
{e.code === 0 ? `${e.ms} ms` : `code ${e.code}`}
</small>
</div>
<pre>{e.out}</pre>
</div>
))}
<div ref={end} />
</div>
<form
className="inline-form console-input"
onSubmit={(e) => {
e.preventDefault();
run(line);
}}
>
<span className="prompt">$ garage</span>
<input
type="text"
value={line}
onChange={(e) => setLine(e.target.value)}
onKeyDown={(e) => {
if (e.key === "ArrowUp" && hist.length) {
e.preventDefault();
const n = Math.min(hi + 1, hist.length - 1);
setHi(n);
setLine(hist[n]);
} else if (e.key === "ArrowDown") {
e.preventDefault();
const n = hi - 1;
setHi(n);
setLine(n >= 0 ? hist[n] : "");
}
}}
placeholder="status"
autoFocus
spellCheck={false}
autoCapitalize="off"
aria-label="Commande garage"
/>
<button className="primary" disabled={busy || !line.trim()}>
Exécuter
</button>
<button type="button" onClick={() => setLog([])} disabled={!log.length}>
Effacer
</button>
</form>
</div>
);
}
+351
View File
@@ -0,0 +1,351 @@
import { useState } from "react";
import { garage, type Config, type KeyInfo, type KeyListItem } from "./api";
import { fmtDate } from "./format";
import { EyeIcon, KeyIcon, PlusIcon, RefreshIcon, TrashIcon } from "./icons";
import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, useAct, useLoad } from "./ui";
// --- Liste -------------------------------------------------------------------------
export function Keys({ cfg }: { cfg: Config }) {
const [creating, setCreating] = useState<"new" | "import" | null>(null);
const [created, setCreated] = useState<KeyInfo | null>(null);
const { data, error, loading, reload } = useLoad(() => garage.get<KeyListItem[]>("ListKeys"));
return (
<div className="page">
<PageHead title="Clés d'accès">
<button onClick={reload} disabled={loading} aria-label="Actualiser" title="Actualiser">
<RefreshIcon />
</button>
<button onClick={() => setCreating("import")}>Importer</button>
<button className="primary" onClick={() => setCreating("new")}>
<PlusIcon /> Nouvelle clé
</button>
</PageHead>
<Loading loading={loading && !data} error={error} onRetry={reload} />
{data && (
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Nom</th>
<th>Identifiant</th>
<th>Créée</th>
<th>Expiration</th>
</tr>
</thead>
<tbody>
{data.map((k) => (
<tr key={k.id} className="click" onClick={() => (location.hash = `#/keys/${k.id}`)}>
<td>
<a href={`#/keys/${k.id}`} className="name" onClick={(e) => e.stopPropagation()}>
<KeyIcon /> {k.name || "(sans nom)"}
</a>
</td>
<td>
<Mono value={k.id} short={16} />
</td>
<td className="muted">{fmtDate(k.created)}</td>
<td>{k.expired ? <Status kind="bad">expirée</Status> : k.expiration ? fmtDate(k.expiration) : <span className="muted">jamais</span>}</td>
</tr>
))}
{data.length === 0 && (
<tr>
<td colSpan={4} className="muted center">
Aucune clé.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
{creating && (
<KeyForm
mode={creating}
onClose={() => setCreating(null)}
onDone={(k) => {
setCreating(null);
setCreated(k);
reload();
}}
/>
)}
{created && (
<Modal title="Clé créée" onClose={() => setCreated(null)}>
<p className="notice">Le secret reste consultable plus tard depuis la page de la clé.</p>
<Secrets k={created} cfg={cfg} reveal />
<div className="modal-actions">
<span className="spacer" />
<button className="primary" onClick={() => setCreated(null)}>
Fermer
</button>
</div>
</Modal>
)}
</div>
);
}
function KeyForm({ mode, onClose, onDone }: { mode: "new" | "import"; onClose: () => void; onDone: (k: KeyInfo) => void }) {
const act = useAct();
const [name, setName] = useState("");
const [id, setId] = useState("");
const [secret, setSecret] = useState("");
const [exp, setExp] = useState("");
const [createBucket, setCreateBucket] = useState(false);
const [busy, setBusy] = useState(false);
const valid = mode === "new" || (/^GK[0-9a-f]{24}$/.test(id) && /^[0-9a-f]{64}$/.test(secret));
return (
<Modal title={mode === "new" ? "Nouvelle clé" : "Importer une clé"} onClose={onClose}>
<form
className="form"
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
let k: KeyInfo | undefined;
if (await act(async () => {
if (mode === "new") {
k = await garage.post<KeyInfo>("CreateKey", undefined, {
name: name || null,
allow: { createBucket },
...(exp ? { expiration: new Date(exp).toISOString() } : { neverExpires: true }),
});
} else {
k = await garage.post<KeyInfo>("ImportKey", undefined, { name: name || null, accessKeyId: id, secretAccessKey: secret });
}
})) onDone(k!);
setBusy(false);
}}
>
<label className="field">
<span>Nom</span>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} autoFocus placeholder="ex. sauvegardes-proxmox" />
</label>
{mode === "import" && (
<>
<label className="field">
<span>Identifiant (GK + 24 caractères hexadécimaux)</span>
<input type="text" value={id} onChange={(e) => setId(e.target.value.trim())} />
</label>
<label className="field">
<span>Secret (64 caractères hexadécimaux)</span>
<input type="password" value={secret} onChange={(e) => setSecret(e.target.value.trim())} autoComplete="off" />
</label>
</>
)}
{mode === "new" && (
<>
<label className="field">
<span>Expiration (facultative)</span>
<input type="datetime-local" value={exp} onChange={(e) => setExp(e.target.value)} />
</label>
<label className="check-row">
<input type="checkbox" checked={createBucket} onChange={(e) => setCreateBucket(e.target.checked)} />
<span>Autoriser cette clé à créer des buckets</span>
</label>
</>
)}
<div className="modal-actions">
<span className="spacer" />
<button type="button" onClick={onClose}>
Annuler
</button>
<button className="primary" disabled={!valid || busy}>
{mode === "new" ? "Créer" : "Importer"}
</button>
</div>
</form>
</Modal>
);
}
/** Identifiant, secret et exemples de configuration client. */
function Secrets({ k, cfg, reveal }: { k: KeyInfo; cfg: Config; reveal?: boolean }) {
const [show, setShow] = useState(!!reveal);
const secret = k.secretAccessKey || "";
const shown = show ? secret : "•".repeat(32);
const endpoint = cfg.s3Endpoint || "https://s3.example.org";
const rclone = `[garage]\ntype = s3\nprovider = Other\naccess_key_id = ${k.accessKeyId}\nsecret_access_key = ${secret}\nendpoint = ${endpoint}\nregion = ${cfg.s3Region}`;
const aws = `aws configure set aws_access_key_id ${k.accessKeyId}\naws configure set aws_secret_access_key ${secret}\naws configure set region ${cfg.s3Region}\naws --endpoint-url ${endpoint} s3 ls`;
return (
<div className="form">
<label className="field">
<span>Identifiant</span>
<div className="row">
<input readOnly value={k.accessKeyId} className="grow mono" />
<CopyButton text={k.accessKeyId} />
</div>
</label>
<label className="field">
<span>Secret</span>
<div className="row">
<input readOnly value={shown} className="grow mono" />
{secret && (
<button className="icon-btn" onClick={() => setShow(!show)} aria-label={show ? "Masquer" : "Afficher"} title={show ? "Masquer" : "Afficher"}>
<EyeIcon />
</button>
)}
{secret && <CopyButton text={secret} />}
</div>
</label>
{show && secret && (
<>
<div>
<div className="row">
<strong className="small-text grow">rclone</strong>
<CopyButton text={rclone} />
</div>
<pre className="out">{rclone}</pre>
</div>
<div>
<div className="row">
<strong className="small-text grow">AWS CLI</strong>
<CopyButton text={aws} />
</div>
<pre className="out">{aws}</pre>
</div>
</>
)}
</div>
);
}
// --- Détail ------------------------------------------------------------------------
export function KeyPage({ id, cfg }: { id: string; cfg: Config }) {
const act = useAct();
const [reveal, setReveal] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const { data: k, error, loading, reload } = useLoad(() => garage.get<KeyInfo>("GetKeyInfo", { id, showSecretKey: reveal }), [id, reveal]);
const [name, setName] = useState<string | null>(null);
if (!k)
return (
<div className="page">
<PageHead title="Clé" back={{ href: "#/keys", label: "Clés d'accès" }} />
<Loading loading={loading} error={error} onRetry={reload} />
</div>
);
const run = (fn: () => Promise<unknown>, ok?: string) => act(fn, ok).then((r) => r && reload());
return (
<div className="page">
<PageHead title={k.name || k.accessKeyId} back={{ href: "#/keys", label: "Clés d'accès" }}>
<button className="danger-outline" onClick={() => setConfirmDelete(true)}>
<TrashIcon /> Supprimer
</button>
</PageHead>
<section className="panel">
<h3>
Identifiants {k.expired && <Status kind="bad">expirée</Status>}
</h3>
{reveal || k.secretAccessKey ? (
<Secrets k={k} cfg={cfg} reveal />
) : (
<>
<Secrets k={k} cfg={cfg} />
<p className="muted small-text">Le secret n'est récupéré auprès de Garage que sur demande.</p>
<button onClick={() => setReveal(true)}>
<EyeIcon /> Afficher le secret
</button>
</>
)}
</section>
<section className="panel">
<h3>Réglages</h3>
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
if (name !== null) run(() => garage.post("UpdateKey", { id: k.accessKeyId }, { name }), "Nom enregistré").then(() => setName(null));
}}
>
<div className="inline-form">
<label className="field grow">
<span>Nom</span>
<input type="text" value={name ?? k.name} onChange={(e) => setName(e.target.value)} />
</label>
<button disabled={name === null || name === k.name}>Renommer</button>
</div>
</form>
<label className="check-row">
<input
type="checkbox"
checked={k.permissions.createBucket}
onChange={(e) =>
run(() => garage.post("UpdateKey", { id: k.accessKeyId }, e.target.checked ? { allow: { createBucket: true } } : { deny: { createBucket: true } }))
}
/>
<span>Peut créer des buckets</span>
</label>
<p className="muted small-text">
Créée le {fmtDate(k.created)} · expiration : {k.expiration ? fmtDate(k.expiration) : "jamais"}
</p>
</section>
<section className="panel">
<h3>Buckets accessibles</h3>
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Bucket</th>
<th className="c">Lecture</th>
<th className="c">Écriture</th>
<th className="c">Propriétaire</th>
</tr>
</thead>
<tbody>
{k.buckets.map((b) => (
<tr key={b.id}>
<td>
<a href={`#/buckets/${b.id}`}>{b.globalAliases[0] ?? b.localAliases[0] ?? b.id.slice(0, 12)}</a>
</td>
{(["read", "write", "owner"] as const).map((p) => (
<td className="c" key={p}>
<input
type="checkbox"
checked={!!b.permissions[p]}
onChange={(e) =>
run(() => garage.post(e.target.checked ? "AllowBucketKey" : "DenyBucketKey", undefined, { bucketId: b.id, accessKeyId: k.accessKeyId, permissions: { [p]: true } }))
}
aria-label={p}
/>
</td>
))}
</tr>
))}
{k.buckets.length === 0 && (
<tr>
<td colSpan={4} className="muted center">
Cette clé n'a accès à aucun bucket.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
{confirmDelete && (
<Confirm
title="Supprimer la clé"
message={
<p>
La clé <strong>{k.name || k.accessKeyId}</strong> sera supprimée et ses accès aux buckets révoqués. Les applications qui l'utilisent cesseront de fonctionner.
</p>
}
confirmLabel="Supprimer"
onClose={() => setConfirmDelete(false)}
onConfirm={async () => {
if (await act(() => garage.post("DeleteKey", { id: k.accessKeyId }), "Clé supprimée")) location.hash = "#/keys";
else setConfirmDelete(false);
}}
/>
)}
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
import { useState } from "react";
import { appApi, errMsg, type Config } from "./api";
import { BucketIcon } from "./gicons";
export function Login({ cfg, onLoggedIn }: { cfg: Config; onLoggedIn: () => void }) {
const [user, setUser] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<main className="login">
<form
className="login-card form"
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
setError("");
try {
await appApi.login(user, password);
onLoggedIn();
} catch (er) {
setError(errMsg(er));
setBusy(false);
}
}}
>
<div className="login-brand">
<BucketIcon size={44} />
<h1>{cfg.title}</h1>
<p className="muted">Administration de Garage</p>
</div>
<label className="field">
<span>Utilisateur</span>
<input type="text" value={user} onChange={(e) => setUser(e.target.value)} autoComplete="username" autoFocus />
</label>
<label className="field">
<span>Mot de passe</span>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
</label>
{error && <p className="error">{error}</p>}
<button className="primary big" disabled={busy || !user || !password}>
Se connecter
</button>
</form>
</main>
);
}
+207
View File
@@ -0,0 +1,207 @@
import { useState } from "react";
import { garage, type MultiResponse } from "./api";
import { fmtAgo, fmtNum } from "./format";
import { RefreshIcon } from "./icons";
import { Loading, Mono, PageHead, Status, useAct, useLoad } from "./ui";
interface Worker {
id: number;
name: string;
state: string | { throttled?: { durationSecs?: number } };
errors: number;
consecutiveErrors: number;
lastError?: { message: string; secsAgo: number } | null;
tranquility?: number | null;
progress?: string | null;
queueLength?: number | null;
persistentErrors?: number | null;
freeform?: string[];
}
interface BlockError {
blockHash: string;
refcount: number;
errorCount: number;
lastTrySecsAgo: number;
nextTryInSecs: number;
}
/** Aplatit une réponse diffusée : les nœuds en erreur sont signalés à part. */
function flat<T>(r: MultiResponse<T> | undefined): { items: T[]; errors: string[] } {
return { items: Object.values(r?.success ?? {}), errors: Object.entries(r?.error ?? {}).map(([id, e]) => `${id.slice(0, 8)} : ${e}`) };
}
const REPAIRS: [string, string][] = [
["tables", "Tables (métadonnées)"],
["blocks", "Blocs de données"],
["versions", "Versions d'objets"],
["multipartUploads", "Envois multipart"],
["blockRefs", "Références de blocs"],
["blockRc", "Compteurs de références"],
["rebalance", "Rééquilibrage des blocs"],
["aliases", "Alias"],
["clearResyncQueue", "Vider la file de resynchronisation"],
["scrub:start", "Vérification d'intégrité (scrub) : démarrer"],
["scrub:pause", "Scrub : pause"],
["scrub:resume", "Scrub : reprendre"],
["scrub:cancel", "Scrub : annuler"],
];
const stateLabel = (s: Worker["state"]): [string, "ok" | "warn" | "off"] => {
if (typeof s === "string") return s === "busy" ? ["actif", "ok"] : s === "done" ? ["terminé", "off"] : ["en attente", "off"];
return ["ralenti", "warn"];
};
export function Maintenance() {
const act = useAct();
const [busyOnly, setBusyOnly] = useState(false);
const [repair, setRepair] = useState("tables");
const [result, setResult] = useState("");
const workers = useLoad(() => garage.post<MultiResponse<Worker[]>>("ListWorkers", { node: "*" }, { busyOnly, errorOnly: false }), [busyOnly]);
const blocks = useLoad(() => garage.post<MultiResponse<BlockError[]>>("ListBlockErrors", { node: "*" }));
const w = flat(workers.data);
const wlist = w.items.flat();
const b = flat(blocks.data);
const blist = b.items.flat();
return (
<div className="page">
<PageHead title="Maintenance">
<button onClick={() => (workers.reload(), blocks.reload())} aria-label="Actualiser" title="Actualiser">
<RefreshIcon />
</button>
</PageHead>
<section className="panel">
<h3>Réparations</h3>
<p className="muted small-text">Les opérations sont lancées sur tous les nœuds. Elles tournent en tâche de fond : suivez-les dans la liste des tâches ci-dessous.</p>
<div className="inline-form">
<select value={repair} onChange={(e) => setRepair(e.target.value)} aria-label="Type de réparation">
{REPAIRS.map(([k, l]) => (
<option key={k} value={k}>
{l}
</option>
))}
</select>
<button
className="primary"
onClick={async () => {
const body = repair.startsWith("scrub:") ? { repairType: { scrub: repair.slice(6) } } : { repairType: repair };
if (await act(() => garage.post("LaunchRepairOperation", { node: "*" }, body), "Opération lancée")) workers.reload();
}}
>
Lancer
</button>
<button
onClick={async () => {
const r = await garage.post<MultiResponse<unknown>>("CreateMetadataSnapshot", { node: "*" }).catch((e) => {
act(async () => {
throw e;
});
return null;
});
if (r) setResult(Object.keys(r.error ?? {}).length ? "Échec du snapshot : " + JSON.stringify(r.error) : "Snapshot des métadonnées demandé.");
}}
>
Snapshot des métadonnées
</button>
</div>
{result && <p className="notice">{result}</p>}
</section>
<section className="panel">
<div className="row">
<h3 className="grow">Tâches de fond</h3>
<label className="check-row" style={{ margin: 0 }}>
<input type="checkbox" checked={busyOnly} onChange={(e) => setBusyOnly(e.target.checked)} />
<span>Actives seulement</span>
</label>
</div>
<Loading loading={workers.loading && !workers.data} error={workers.error} onRetry={workers.reload} />
{w.errors.map((e) => (
<p className="error" key={e}>{e}</p>
))}
{workers.data && (
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Tâche</th>
<th>État</th>
<th>Progression</th>
<th className="num">File</th>
<th className="num">Erreurs</th>
</tr>
</thead>
<tbody>
{wlist.map((t, i) => {
const [l, k] = stateLabel(t.state);
return (
<tr key={`${t.id}-${i}`}>
<td>{t.name}</td>
<td>
<Status kind={k}>{l}</Status>
</td>
<td className="muted">{t.progress || t.freeform?.join(" · ") || "-"}</td>
<td className="num">{fmtNum(t.queueLength)}</td>
<td className="num" title={t.lastError ? `${t.lastError.message} (${fmtAgo(t.lastError.secsAgo)})` : undefined}>
{t.errors > 0 ? <span className="error-text">{t.errors}</span> : 0}
</td>
</tr>
);
})}
{wlist.length === 0 && (
<tr>
<td colSpan={5} className="muted center">
Aucune tâche.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
</section>
<section className="panel">
<div className="row">
<h3 className="grow">Blocs en erreur</h3>
<button disabled={blist.length === 0} onClick={() => act(() => garage.post("RetryBlockResync", { node: "*" }, { all: true }), "Nouvel essai demandé").then(() => blocks.reload())}>
Relancer la resynchronisation
</button>
</div>
<Loading loading={blocks.loading && !blocks.data} error={blocks.error} onRetry={blocks.reload} />
{b.errors.map((e) => (
<p className="error" key={e}>{e}</p>
))}
{blocks.data && blist.length === 0 && <p className="muted">Aucun bloc en erreur.</p>}
{blist.length > 0 && (
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Bloc</th>
<th className="num">Références</th>
<th className="num">Échecs</th>
<th>Dernier essai</th>
</tr>
</thead>
<tbody>
{blist.map((e) => (
<tr key={e.blockHash}>
<td>
<Mono value={e.blockHash} short={20} />
</td>
<td className="num">{e.refcount}</td>
<td className="num">{e.errorCount}</td>
<td className="muted">{fmtAgo(e.lastTrySecsAgo)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</div>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { garage, bucketName, type BucketInfo, type BucketListItem, type ClusterHealth, type ClusterStatus, type KeyListItem } from "./api";
import { fmtNum, fmtSize } from "./format";
import { Loading, PageHead, Status, UsageBar, useLoad } from "./ui";
import { RefreshIcon } from "./icons";
const healthLabel: Record<string, [string, "ok" | "warn" | "bad"]> = {
healthy: ["Sain", "ok"],
degraded: ["Dégradé", "warn"],
unavailable: ["Indisponible", "bad"],
};
export function Overview() {
const { data, error, loading, reload } = useLoad(async () => {
const [health, status, buckets, keys, stats] = await Promise.all([
garage.get<ClusterHealth>("GetClusterHealth"),
garage.get<ClusterStatus>("GetClusterStatus"),
garage.get<BucketListItem[]>("ListBuckets"),
garage.get<KeyListItem[]>("ListKeys"),
garage.get<{ freeform?: string }>("GetClusterStatistics").catch(() => ({ freeform: "" })),
]);
const infos = await Promise.all(buckets.map((b) => garage.get<BucketInfo>("GetBucketInfo", { id: b.id }).catch(() => null)));
return { health, status, buckets, keys, stats, infos: infos.filter((x): x is BucketInfo => !!x) };
});
const bytes = data?.infos.reduce((s, b) => s + (b.bytes || 0), 0) ?? 0;
const objects = data?.infos.reduce((s, b) => s + (b.objects || 0), 0) ?? 0;
const [hl, hk] = healthLabel[data?.health.status ?? ""] ?? [data?.health.status ?? "-", "off" as const];
const top = [...(data?.infos ?? [])].sort((a, b) => b.bytes - a.bytes).slice(0, 6);
return (
<div className="page">
<PageHead title="Vue d'ensemble">
<button onClick={reload} disabled={loading}>
<RefreshIcon /> Actualiser
</button>
</PageHead>
<Loading loading={loading && !data} error={error} onRetry={reload} />
{data && (
<>
<div className="cards">
<div className="card">
<span className="k">État du cluster</span>
<strong className="v">
<Status kind={hk}>{hl}</Status>
</strong>
<small className="muted">
{data.health.connectedNodes}/{data.health.knownNodes} nœuds connectés
</small>
</div>
<div className="card">
<span className="k">Partitions</span>
<strong className="v">
{data.health.partitionsAllOk}/{data.health.partitions}
</strong>
<small className="muted">toutes saines (quorum : {data.health.partitionsQuorum})</small>
</div>
<div className="card">
<span className="k">Buckets</span>
<strong className="v">{data.buckets.length}</strong>
<small className="muted">{fmtNum(objects)} objets</small>
</div>
<div className="card">
<span className="k">Données stockées</span>
<strong className="v">{fmtSize(bytes)}</strong>
<small className="muted">hors réplication</small>
</div>
<div className="card">
<span className="k">Clés d'accès</span>
<strong className="v">{data.keys.length}</strong>
<small className="muted">{data.keys.filter((k) => k.expired).length} expirée(s)</small>
</div>
</div>
<div className="cols">
<section className="panel">
<h3>Nœuds</h3>
<ul className="plain">
{data.status.nodes.map((n) => (
<li key={n.id}>
<div className="row">
<Status kind={n.isUp ? "ok" : "bad"}>{n.isUp ? "En ligne" : "Hors ligne"}</Status>
<strong>{n.hostname || n.id.slice(0, 12)}</strong>
<span className="muted">{n.role?.zone ?? "sans rôle"}</span>
<span className="spacer" />
{n.dataPartition && (
<small className="muted">
{fmtSize(n.dataPartition.total - n.dataPartition.available)} / {fmtSize(n.dataPartition.total)}
</small>
)}
</div>
{n.dataPartition && <UsageBar used={n.dataPartition.total - n.dataPartition.available} total={n.dataPartition.total} />}
</li>
))}
</ul>
</section>
<section className="panel">
<h3>Plus gros buckets</h3>
{top.length === 0 && <p className="muted">Aucun bucket.</p>}
<ul className="plain">
{top.map((b) => (
<li key={b.id}>
<div className="row">
<a href={`#/buckets/${b.id}`}>{bucketName(b)}</a>
<span className="spacer" />
<small className="muted">
{fmtNum(b.objects)} objets · {fmtSize(b.bytes)}
</small>
</div>
<UsageBar used={b.bytes} total={bytes} />
</li>
))}
</ul>
</section>
</div>
{data.stats.freeform && (
<section className="panel">
<h3>Statistiques du cluster</h3>
<pre className="out">{data.stats.freeform}</pre>
</section>
)}
</>
)}
</div>
);
}
+179
View File
@@ -0,0 +1,179 @@
// Client de l'API : le serveur Go relaie /api/garage/v2/... vers l'API d'administration de Garage.
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
async function req<T>(url: string, init: RequestInit = {}): Promise<T> {
const r = await fetch(url, {
...init,
credentials: "same-origin",
headers: { "X-Requested-With": "garage-ui", ...(init.body ? { "Content-Type": "application/json" } : {}) },
});
const text = await r.text();
let data: unknown = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = text;
}
if (!r.ok) {
const d = data as { message?: string; error?: string } | string | null;
const msg = (d && typeof d === "object" ? d.message || d.error : d) || r.statusText;
throw new ApiError(r.status, String(msg));
}
return data as T;
}
const qs = (p?: Record<string, string | number | boolean | undefined>) => {
const u = new URLSearchParams();
for (const [k, v] of Object.entries(p ?? {})) if (v !== undefined && v !== "") u.set(k, String(v));
const s = u.toString();
return s ? `?${s}` : "";
};
type Params = Record<string, string | number | boolean | undefined>;
export const garage = {
get: <T>(op: string, params?: Params) => req<T>(`/api/garage/v2/${op}${qs(params)}`),
post: <T = unknown>(op: string, params?: Params, body?: unknown) =>
req<T>(`/api/garage/v2/${op}${qs(params)}`, { method: "POST", body: JSON.stringify(body ?? {}) }),
};
// --- Types (partiels : seuls les champs utilisés) ---------------------------------
export interface Perm {
read: boolean;
write: boolean;
owner: boolean;
}
export interface BucketListItem {
id: string;
created: string;
globalAliases: string[];
localAliases: { accessKeyId: string; alias: string }[];
}
export interface BucketKey {
accessKeyId: string;
name: string;
permissions: Perm;
bucketLocalAliases?: string[];
}
export interface BucketInfo extends BucketListItem {
websiteAccess: boolean;
websiteConfig?: { indexDocument?: string; errorDocument?: string } | null;
keys: BucketKey[];
objects: number;
bytes: number;
unfinishedUploads: number;
unfinishedMultipartUploads: number;
unfinishedMultipartUploadParts: number;
unfinishedMultipartUploadBytes: number;
quotas: { maxSize?: number | null; maxObjects?: number | null };
}
export interface KeyListItem {
id: string;
name: string;
created?: string;
expiration?: string | null;
expired?: boolean;
}
export interface KeyInfo {
accessKeyId: string;
name: string;
created?: string;
expiration?: string | null;
expired?: boolean;
secretAccessKey?: string | null;
permissions: { createBucket: boolean };
buckets: { id: string; globalAliases: string[]; localAliases: string[]; permissions: Perm }[];
}
export interface NodeInfo {
id: string;
role?: { zone: string; tags: string[]; capacity: number | null } | null;
addr?: string | null;
hostname?: string | null;
isUp: boolean;
lastSeenSecsAgo?: number | null;
draining?: boolean;
dataPartition?: { available: number; total: number } | null;
metadataPartition?: { available: number; total: number } | null;
garageVersion?: string | null;
}
export interface ClusterStatus {
layoutVersion: number;
nodes: NodeInfo[];
}
export interface ClusterHealth {
status: string;
knownNodes: number;
connectedNodes: number;
storageNodes: number;
storageNodesUp: number;
partitions: number;
partitionsQuorum: number;
partitionsAllOk: number;
}
export interface LayoutRole {
id: string;
zone: string;
tags: string[];
capacity: number | null;
}
export interface StagedRole {
id: string;
remove?: boolean;
zone?: string;
tags?: string[];
capacity?: number | null;
}
export interface ClusterLayout {
version: number;
roles: LayoutRole[];
parameters?: { zoneRedundancy?: unknown };
partitionSize?: number;
stagedRoleChanges: StagedRole[];
}
/** Réponse d'une opération diffusée aux nœuds (?node=*). */
export interface MultiResponse<T> {
success: Record<string, T>;
error: Record<string, string>;
}
export interface Config {
title: string;
version: string;
auth: boolean;
user: string;
cli: boolean;
s3Endpoint: string;
s3Region: string;
}
export const appApi = {
config: () => req<Config>("/api/config"),
login: (user: string, password: string) => req<{ user: string }>("/api/login", { method: "POST", body: JSON.stringify({ user, password }) }),
logout: () => req("/api/logout", { method: "POST", body: "{}" }),
cli: (args: string[]) => req<{ exitCode: number; output: string; ms: number }>("/api/cli", { method: "POST", body: JSON.stringify({ args }) }),
};
export const bucketName = (b: { id: string; globalAliases: string[]; localAliases: { alias: string }[] }) =>
b.globalAliases[0] ?? b.localAliases[0]?.alias ?? b.id.slice(0, 12);
export const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));
+39
View File
@@ -0,0 +1,39 @@
const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"];
export function fmtSize(n: number | null | undefined): string {
if (n == null || !isFinite(n)) return "-";
let i = 0;
let v = n;
while (v >= 1024 && i < UNITS.length - 1) {
v /= 1024;
i++;
}
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1).replace(".", ",")} ${UNITS[i]}`;
}
export const fmtNum = (n: number | null | undefined) => (n == null ? "-" : n.toLocaleString("fr-FR"));
export function fmtDate(s?: string | null): string {
if (!s) return "-";
const d = new Date(s);
return isNaN(d.getTime()) ? s : d.toLocaleString("fr-FR", { dateStyle: "medium", timeStyle: "short" });
}
export function fmtAgo(secs?: number | null): string {
if (secs == null) return "-";
if (secs < 60) return `il y a ${secs} s`;
if (secs < 3600) return `il y a ${Math.round(secs / 60)} min`;
if (secs < 86400) return `il y a ${Math.round(secs / 3600)} h`;
return `il y a ${Math.round(secs / 86400)} j`;
}
export const GIB = 1024 ** 3;
/** Découpe une ligne de commande en arguments (guillemets simples et doubles pris en charge). */
export function splitArgs(line: string): string[] {
const out: string[] = [];
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
let m: RegExpExecArray | null;
while ((m = re.exec(line))) out.push(m[1] ?? m[2] ?? m[3]);
return out;
}
+25
View File
@@ -0,0 +1,25 @@
// Icônes propres à Garage UI : Papicons d'abord, Lucide en dernier recours (serveur, terminal).
import * as P from "./papicons";
import { icon, pap } from "./icons";
export const OverviewIcon = pap(P.Pie);
export const BucketIcon = pap(P.Archive);
export const MaintenanceIcon = pap(P.Gears);
export const GlobeIcon = pap(P.Globe);
/** Lucide « server » */
export const ClusterIcon = icon(
<>
<rect width="20" height="8" x="2" y="2" rx="2" />
<rect width="20" height="8" x="2" y="14" rx="2" />
<path d="M6 6h.01M6 18h.01" />
</>,
);
/** Lucide « terminal » */
export const ConsoleIcon = icon(
<>
<path d="m4 17 6-6-6-6" />
<path d="M12 19h8" />
</>,
);
+390
View File
@@ -0,0 +1,390 @@
// Icônes de l'interface : jeu Papicons (formes pleines, couleur héritée via currentColor),
// identique à celui d'Excalicloud (frontend/src/icons.tsx) pour que les deux outils se ressemblent.
// Les tracés Papicons sont dans papicons.ts ; les quelques icônes absentes du jeu sont
// dessinées ici dans le même esprit (formes pleines arrondies, ou trait épais à bouts ronds).
import { useId, type ReactNode } from "react";
import * as P from "./papicons";
import type { PapPath } from "./papicons";
type IconProps = { size?: number; className?: string };
/** Identifiant de masque SVG unique et sûr dans url(#…). */
function useMaskId() {
return "m" + useId().replace(/[^a-zA-Z0-9_-]/g, "");
}
function Svg({ size = 16, className, children }: IconProps & { children: ReactNode }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden>
{children}
</svg>
);
}
const paths = (p: PapPath[]) =>
p.map((x, i) => <path key={i} d={x.d} fillRule={x.evenodd ? "evenodd" : undefined} clipRule={x.evenodd ? "evenodd" : undefined} />);
/** Icône Papicons telle quelle. */
export const pap = (p: PapPath[], transform?: string) =>
function Icon({ size, className }: IconProps) {
return (
<Svg size={size} className={className}>
<g transform={transform}>{paths(p)}</g>
</Svg>
);
};
/** Icône au trait, pour les icônes de dossiers sans équivalent Papicons (trait 2, plus appuyé que Tabler). */
export const icon = (children: ReactNode) =>
function Icon({ size = 16, className }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
{children}
</svg>
);
};
/** Icône pleine dessinée ici. */
const solid = (children: ReactNode) =>
function Icon({ size, className }: IconProps) {
return <Svg size={size} className={className}>{children}</Svg>;
};
/** Icône au trait épais (graisse des flèches Papicons), pour les symboles absents du jeu. */
const line = (children: ReactNode) =>
function Icon({ size = 16, className }: IconProps) {
return (
<svg
className={className}
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
>
{children}
</svg>
);
};
/** Icône Papicons avec une pastille en bas à droite (le fond est évidé autour de la pastille). */
const badged = (base: PapPath[], badge: PapPath[]) =>
function Icon({ size }: IconProps) {
const id = useMaskId();
return (
<Svg size={size}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<circle cx="18" cy="18" r="7" fill="#000" />
</mask>
<g mask={`url(#${id})`}>{paths(base)}</g>
<g transform="translate(18 18) scale(0.5) translate(-12 -12)">{paths(badge)}</g>
</Svg>
);
};
// Thème, barre du haut, panneaux.
/** Soleil dessiné ici : celui de Papicons ressemble trop à la roue dentée des Paramètres. */
export const SunIcon = solid(
<>
<circle cx="12" cy="12" r="4.5" />
<path
d="M12 2.5v1.5M12 20v1.5M2.5 12H4M20 12h1.5M5.3 5.3l1.05 1.05M17.65 17.65l1.05 1.05M5.3 18.7l1.05-1.05M17.65 6.35l1.05-1.05"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
/>
</>,
);
export const MoonIcon = pap(P.Moon);
export const SettingsIcon = pap(P.Gears);
export const MenuIcon = pap(P.Menu);
export const CloseIcon = pap(P.Cross);
export const UpdateIcon = pap(P.Sparkles);
export const UserIcon = pap(P.User);
export const LogoutIcon = pap(P.Logout);
export const InfoIcon = pap(P.Info);
export const LinkIcon = pap(P.Link);
export const SearchIcon = pap(P.Search);
// Fichiers et dossiers.
export const FolderIcon = pap(P.Folder);
export const FileIcon = pap(P.Paper);
export const FilePlusIcon = badged(P.Paper, P.Add);
export const FolderPlusIcon = badged(P.Folder, P.Add);
export const FolderUploadIcon = badged(P.Folder, P.ArrowUpBox);
export const MoveIcon = badged(P.Folder, P.ArrowRightBox);
export const UploadIcon = pap(P.ArrowUpBox);
export const DownloadIcon = pap(P.ArrowDownBox);
/** Dossier parent (« .. »). */
export const UpIcon = pap(P.ArrowLeftUp);
export const EditIcon = pap(P.PenAlt);
export const SelectAllIcon = pap(P.Tasks);
export const DeselectIcon = pap(P.Placeholder);
/** Menu d'actions « … » : points à l'horizontale. */
export const DotsIcon = pap(P.Dots, "rotate(90 12 12)");
// Vues de l'explorateur.
export const ListIcon = pap(P.List);
export const GridIcon = pap(P.Grid);
export const GalleryIcon = pap(P.Gallery);
// Poubelle.
export const TrashIcon = pap(P.Trash);
/** Poubelle qui contient des éléments : pastille pleine sur le couvercle. */
export function TrashFullIcon({ size }: IconProps) {
const id = useMaskId();
return (
<Svg size={size}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<circle cx="19.5" cy="4.5" r="4.5" fill="#000" />
</mask>
<g mask={`url(#${id})`}>{paths(P.Trash)}</g>
<circle cx="19.5" cy="4.5" r="3" />
</Svg>
);
}
// Favoris : étoile pleine (favori) ou évidée (pas favori), même silhouette.
export const StarFilledIcon = pap(P.Star);
export function StarIcon({ size }: IconProps) {
const id = useMaskId();
return (
<Svg size={size}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<g fill="#000" transform="translate(12 13) scale(0.45) translate(-12 -13)">
{paths(P.Star)}
</g>
</mask>
<g mask={`url(#${id})`}>{paths(P.Star)}</g>
</Svg>
);
}
// Actions sans équivalent dans Papicons.
export const RefreshIcon = line(
<>
<path d="M19.5 10.5A7.8 7.8 0 0 0 5 8.5M4.5 4.5v4h4" />
<path d="M4.5 13.5A7.8 7.8 0 0 0 19 15.5m.5 4v-4h-4" />
</>,
);
export const RestoreIcon = line(<path d="M9 14.5 4.5 10 9 5.5M4.5 10h11a4.5 4.5 0 1 1 0 9H14" />);
export const HistoryIcon = line(
<>
<path d="M12 8v4l2.5 2" />
<path d="M3.5 11a8.6 8.6 0 1 1 .6 4M3.5 20v-5h5" />
</>,
);
export const SortIcon = line(<path d="M4 6h9M4 12h7M4 18h5M17.5 4.5v15M14.5 16.5l3 3 3-3" />);
export const CopyIcon = function CopyIcon({ size }: IconProps) {
const id = useMaskId();
return (
<Svg size={size}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<rect x="7" y="7" width="16" height="16" rx="5" fill="#000" />
</mask>
<rect x="3" y="3" width="12.5" height="12.5" rx="3.5" mask={`url(#${id})`} />
<rect x="9" y="9" width="12" height="12" rx="3.5" />
</Svg>
);
};
export const SaveIcon = function SaveIcon({ size }: IconProps) {
const id = useMaskId();
return (
<Svg size={size}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<rect x="7.5" y="1" width="7.5" height="6.5" rx="1.5" fill="#000" />
<circle cx="12" cy="15" r="2.75" fill="#000" />
</mask>
<path mask={`url(#${id})`} d="M7 3h8.2c.8 0 1.56.32 2.12.88l2.8 2.8c.56.56.88 1.32.88 2.12V17a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4z" />
</Svg>
);
};
export const TagIcon = solid(
<path
fillRule="evenodd"
clipRule="evenodd"
d="M3 6a3 3 0 0 1 3-3h4.76a3 3 0 0 1 2.12.88l7.9 7.9a3 3 0 0 1 0 4.24l-4.76 4.76a3 3 0 0 1-4.24 0l-7.9-7.9A3 3 0 0 1 3 10.76zm5 .25a1.75 1.75 0 1 0 0 3.5 1.75 1.75 0 0 0 0-3.5z"
/>,
);
export const ShareIcon = solid(
<>
<path d="M6 12 17.5 5.5M6 12l11.5 6.5" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" />
<circle cx="6" cy="12" r="3.25" />
<circle cx="17.5" cy="5.5" r="3.25" />
<circle cx="17.5" cy="18.5" r="3.25" />
</>,
);
export const EyeIcon = solid(
<path
fillRule="evenodd"
clipRule="evenodd"
d="M12 5c4.3 0 7.6 2.7 9.5 6.1.3.56.3 1.24 0 1.8C19.6 16.3 16.3 19 12 19s-7.6-2.7-9.5-6.1a1.9 1.9 0 0 1 0-1.8C4.4 7.7 7.7 5 12 5m0 3.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7m0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3"
/>,
);
/** Punaise : panneau épinglé ou flottant. */
export const PinIcon = solid(
<g transform="rotate(35 12 12)">
<path d="M8.5 3h7a1.5 1.5 0 0 1 0 3H15v4l2.6 2.4c.95.88.33 2.6-1 2.6H7.4c-1.33 0-1.95-1.72-1-2.6L9 10V6h-.5a1.5 1.5 0 0 1 0-3z" />
<path d="M12 15v6" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" />
</g>,
);
// Métadonnées des schémas (vue Galerie, panneau Détails).
export const ClockIcon = pap(P.Clock);
export const TextIcon = pap(P.Font);
export const PhotoIcon = pap(P.Camera);
export const ArrowIcon = pap(P.ArrowRightUp);
/** Taille du fichier. */
export const SizeIcon = pap(P.Archive);
export const ShapesIcon = solid(
<>
<rect x="3" y="3" width="8.5" height="8.5" rx="2.5" />
<circle cx="17" cy="17" r="4.25" />
<path d="M15.7 3.75a1.5 1.5 0 0 1 2.6 0l3.2 5.5A1.5 1.5 0 0 1 20.2 11.5h-6.4a1.5 1.5 0 0 1-1.3-2.25z" />
</>,
);
export const FrameIcon = line(<path d="M4 7.5h16M4 16.5h16M7.5 4v16M16.5 4v16" />);
// --- Propres à Up And Down : types de fichiers, aperçu, comptes ----------------------
// Même esprit : Papicons quand l'équivalent existe, sinon formes pleines ou trait épais.
/** Feuille Papicons dont un motif est évidé (types de fichiers). */
const page = (glyph: ReactNode) =>
function Icon({ size, className }: IconProps) {
const id = useMaskId();
return (
<Svg size={size} className={className}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<g fill="none" stroke="#000" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
{glyph}
</g>
</mask>
<g mask={`url(#${id})`}>{paths(P.Paper)}</g>
</Svg>
);
};
export const FileTextIcon = page(<path d="M8.5 14.5h7M8.5 17.5h5" />);
export const FileCodeIcon = page(<path d="M10.5 13.5l-2 2.25 2 2.25M13.5 13.5l2 2.25-2 2.25" />);
export const FileZipIcon = page(
<>
<path d="M8.5 7h1.5M8.5 9.5h1.5M8.5 12h1.5" />
<rect x="8" y="14.5" width="3.5" height="4" rx="1" />
</>,
);
export const FileMusicIcon = page(
<>
<circle cx="10.5" cy="17.5" r="1.4" />
<path d="M11.9 17.5V13.5l2.6 1" />
</>,
);
export const FileVideoIcon = page(<path d="M10.5 13.5v5l4-2.5z" fill="#000" />);
export const FilePdfIcon = page(
<path d="M8.5 18.5v-4.5h1.3a1.3 1.3 0 0 1 0 2.6H8.5M12.7 14v4.5M12.7 14h.8a1.6 1.6 0 0 1 1.6 1.6v1.3a1.6 1.6 0 0 1-1.6 1.6h-.8" />,
);
export const FileSheetIcon = page(<path d="M8.5 14h7M8.5 17h7M12 13v6" />);
export const FileSlidesIcon = page(<path d="M9 18.5v-2M12 18.5v-4.5M15 18.5v-3" />);
export const FileImageIcon = page(
<>
<circle cx="9.75" cy="14" r="1" fill="#000" />
<path d="M8.5 18.5l2.75-2.5 1.75 1.5 2.5-2.5" />
</>,
);
export const PlayIcon = solid(<path d="M7 5.1v13.8a1.3 1.3 0 0 0 2 1.1l11-6.9a1.3 1.3 0 0 0 0-2.2L9 4a1.3 1.3 0 0 0-2 1.1z" />);
export const ChevronLeftIcon = line(<path d="M15 5.5 8.5 12l6.5 6.5" />);
export const ChevronRightIcon = line(<path d="M9 5.5 15.5 12 9 18.5" />);
export const ChevronDownIcon = line(<path d="M5.5 9 12 15.5 18.5 9" />);
export const LockIcon = pap(P.Lock);
export const KeyIcon = line(
<>
<circle cx="8" cy="15.5" r="3.75" />
<path d="M10.75 12.75 19 4.5M16.5 7l2.5 2.5M14 9.5l2 2" />
</>,
);
export const UsersIcon = solid(
<>
<circle cx="9" cy="7.75" r="3.75" />
<path d="M2.5 19a5.5 5.5 0 0 1 5.5-5.5h2a5.5 5.5 0 0 1 5.5 5.5v.5a1.5 1.5 0 0 1-1.5 1.5H4a1.5 1.5 0 0 1-1.5-1.5z" />
<circle cx="16.5" cy="7.25" r="3" />
<path d="M17 13.5h.5A4.5 4.5 0 0 1 22 18v1a1.5 1.5 0 0 1-1.5 1.5h-3.2c.13-.33.2-.69.2-1.07V19c0-2.1-.9-4-2.3-5.3.6-.13 1.2-.2 1.8-.2z" />
</>,
);
export const ShieldIcon = solid(
<path d="M11.3 2.7a2 2 0 0 1 1.4 0l6.5 2.4c.8.3 1.3 1 1.3 1.9V12c0 4.6-3.3 8.4-8 9.4a2.4 2.4 0 0 1-1 0c-4.7-1-8-4.8-8-9.4V7c0-.9.5-1.6 1.3-1.9z" />,
);
export const CheckIcon = line(<path d="M5 12.5l4.5 4.5L19 7.5" />);
export const PlusIcon = pap(P.Add);
export const HomeIcon = solid(
<path d="M10.6 3.6a2 2 0 0 1 2.8 0l7 6.6c.4.38.6.9.6 1.45V18a3 3 0 0 1-3 3h-3v-5a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v5H6a3 3 0 0 1-3-3v-6.35c0-.55.22-1.07.6-1.45z" />,
);
export const TableIcon = line(
<>
<rect x="3.5" y="4.5" width="17" height="15" rx="3" />
<path d="M3.5 10h17M10 10v9.5" />
</>,
);
const cloud = "M7 19.5a5 5 0 0 1-.6-9.96 6.5 6.5 0 0 1 12.4 1.56A4.25 4.25 0 0 1 17.5 19.5z";
export const CloudIcon = solid(<path d={cloud} />);
/** Nuage avec une flèche vers le haut évidée : logo par défaut. */
export function CloudUpIcon({ size, className }: IconProps) {
const id = useMaskId();
return (
<Svg size={size} className={className}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<path d="M12 17v-5.5M9.25 14 12 11.25 14.75 14" fill="none" stroke="#000" strokeWidth={2.25} strokeLinecap="round" strokeLinejoin="round" />
</mask>
<path d={cloud} mask={`url(#${id})`} />
</Svg>
);
}
export const ExpandIcon = line(<path d="M4.5 9.5v-5h5M19.5 9.5v-5h-5M4.5 14.5v5h5M19.5 14.5v5h-5" />);
export const CopyLinkIcon = CopyIcon;
export function WarningIcon({ size, className }: IconProps) {
const id = useMaskId();
return (
<Svg size={size} className={className}>
<mask id={id}>
<rect width="24" height="24" fill="#fff" />
<path d="M12 9.5v4" stroke="#000" strokeWidth={2.25} strokeLinecap="round" />
<circle cx="12" cy="17" r="1.25" fill="#000" />
</mask>
<path mask={`url(#${id})`} d="M10.27 3.98a2 2 0 0 1 3.46 0l8.02 13.9A2 2 0 0 1 20.02 21H3.98a2 2 0 0 1-1.73-3.12z" />
</Svg>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
+156
View File
@@ -0,0 +1,156 @@
// Tracés extraits de Papicons 0.2.3 (@getpapillon/papicons, https://github.com/PapillonApp/papicons),
// icônes de Tom Things pour Papillon. Licence MIT, (c) 2025 Association Papillon : voir THIRD_PARTY_NOTICES.md.
// Grille 24 x 24, formes pleines. Seules les icônes utilisées par Excalicloud sont reprises.
export type PapPath = { d: string; evenodd?: boolean };
export const Add: PapPath[] = [
{ d: "M20.414 10.515c.375.374.586.916.586 1.485s-.21 1.112-.585 1.486a1.8 1.8 0 0 1-1.415.515l-.35-.025-5.035-.36.36 5.035.026.349c.038.53-.14 1.04-.515 1.415-.374.375-.917.585-1.486.585s-1.111-.211-1.485-.586A1.79 1.79 0 0 1 10 19.001l.026-.35.36-5.036-5.037.36L5 14a1.79 1.79 0 0 1-1.413-.515C3.21 13.111 3 12.57 3 12s.21-1.112.585-1.486A1.8 1.8 0 0 1 5 10l.35.024 5.034.36L10 5c-.039-.53.138-1.04.514-1.415C10.888 3.21 11.431 3 12 3s1.111.211 1.485.586c.376.375.553.883.515 1.413l-.026.35-.359 5.036 5.036-.36L19 10a1.79 1.79 0 0 1 1.413.515" },
];
export const Archive: PapPath[] = [
{ d: "M12.935 9.076c3.192-.1 4.79-.15 5.381.368.066.057.089.08.148.144.536.576.536 1.92.536 4.605 0 2.641 0 3.962-.774 4.819a3 3 0 0 1-.214.214c-.857.774-2.178.774-4.819.774h-2.386c-2.641 0-3.962 0-4.819-.774a3 3 0 0 1-.214-.214C5 18.155 5 16.834 5 14.193c0-2.686 0-4.03.536-4.605.06-.064.082-.087.148-.144.592-.517 2.189-.468 5.381-.368a30 30 0 0 0 1.87 0M12 12c-.713 0-1.275.017-1.695.037C9.668 12.068 9 12.363 9 13s.668.932 1.305.963c.42.02.982.037 1.695.037s1.275-.017 1.695-.037C14.332 13.932 15 13.637 15 13s-.668-.932-1.305-.963A35 35 0 0 0 12 12m6.65-8c.745 0 1.35.605 1.35 1.35 0 .663-.48 1.224-1.138 1.297C17.547 6.795 15.151 7 12 7c-3.15 0-5.546-.205-6.862-.353A1.29 1.29 0 0 1 4 5.351C4 4.605 4.605 4 5.35 4z" },
];
export const ArrowDownBox: PapPath[] = [
{ d: "M21 12c0 1.483-.072 2.748-.178 3.805-.274 2.723-2.293 4.743-5.016 5.016a38 38 0 0 1-3.806.18c-1.483 0-2.748-.073-3.805-.18-2.723-.273-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.294-4.741 5.016-5.015A38 38 0 0 1 12 3c1.483 0 2.75.073 3.806.179 2.723.274 4.742 2.293 5.016 5.015C20.928 9.251 21 10.517 21 12m-4.122.828a1 1 0 1 0-1.414-1.414l-2.366 2.367.268-5.228.017-.322a1.23 1.23 0 0 0-.355-.944c-.25-.25-.606-.39-.978-.39s-.728.14-.978.39-.373.59-.355.944l.017.322.26 5.046-2.185-2.185a1 1 0 0 0-1.414 1.414l4.034 4.035c.39.39 1.024.39 1.415 0z", evenodd: true },
];
export const ArrowLeftUp: PapPath[] = [
{ d: "M4.5 15a1.5 1.5 0 0 0 3 0V9.621l9.44 9.44a1.5 1.5 0 1 0 2.12-2.122L9.622 7.5h5.38a1.5 1.5 0 0 0 0-3H6A1.5 1.5 0 0 0 4.5 6z" },
];
export const ArrowRightBox: PapPath[] = [
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m.828 4.122a1 1 0 1 0-1.414 1.414l2.367 2.367-5.228-.27-.322-.016a1.23 1.23 0 0 0-.944.356c-.25.25-.39.606-.39.977 0 .372.14.728.39.978s.59.374.944.355l.322-.016 5.046-.261-2.185 2.185a1 1 0 0 0 1.414 1.415l4.035-4.035c.391-.39.391-1.024 0-1.415z", evenodd: true },
];
export const ArrowRightUp: PapPath[] = [
{ d: "M19.5 15a1.5 1.5 0 0 1-3 0V9.621l-9.44 9.44a1.5 1.5 0 1 1-2.12-2.122L14.378 7.5H9a1.5 1.5 0 1 1 0-3h9A1.5 1.5 0 0 1 19.5 6z" },
];
export const ArrowUpBox: PapPath[] = [
{ d: "M21 12c0-1.483-.072-2.748-.178-3.805-.274-2.722-2.293-4.742-5.016-5.016A38 38 0 0 0 12 3c-1.483 0-2.748.073-3.805.179-2.723.274-4.742 2.293-5.016 5.016A38 38 0 0 0 3 12c0 1.483.073 2.75.179 3.806.274 2.723 2.294 4.742 5.016 5.015 1.057.107 2.322.18 3.805.18a38 38 0 0 0 3.806-.18c2.723-.274 4.742-2.292 5.016-5.015.106-1.057.178-2.323.178-3.806m-4.122-.828a1 1 0 0 1-1.414 1.414l-2.366-2.367.268 5.228.017.323c.018.353-.105.693-.355.943s-.606.39-.978.39-.728-.14-.978-.39-.373-.59-.355-.943l.017-.323.26-5.045-2.185 2.184a1 1 0 0 1-1.414-1.414l4.034-4.035c.39-.39 1.024-.39 1.415 0z", evenodd: true },
];
export const Calendar: PapPath[] = [
{ d: "M3 6.125C3 4.399 4.4 3 6.125 3h11.75C19.601 3 21 4.4 21 6.125 21 7.161 20.16 8 19.125 8H4.875A1.875 1.875 0 0 1 3 6.125M18.174 10.005a3 3 0 0 1 2.821 2.821c.003.048.002.101.002.174H17a4 4 0 0 0-4 4v3.99c-.373.009-.804.01-1.313.01h-2.4c-2.133 0-3.2 0-4.022-.396a4 4 0 0 1-1.869-1.869C3 17.913 3 16.846 3 14.714c0-1.6 0-2.399.297-3.016a3 3 0 0 1 1.401-1.401C5.315 10 6.115 10 7.714 10h10.065c.205 0 .308 0 .395.005" },
{ d: "M17 15h3.64c-.181.397-.426.766-.73 1.089-.04.042-.083.084-.168.169l-2.4 2.4c-1.087 1.087-1.665 1.66-2.342 1.978V17a2 2 0 0 1 1.796-1.99z" },
];
export const Camera: PapPath[] = [
{ d: "M12 11a2 2 0 1 1 0 4 2 2 0 0 1 0-4" },
{ d: "M12 4c1.73 0 3.103.853 3.963 2.153l-.102-.01c2.674.213 4.812 2.038 5.048 4.71A24 24 0 0 1 21 13a24 24 0 0 1-.09 2.148c-.237 2.671-2.375 4.496-5.049 4.708A49 49 0 0 1 12 20c-1.51 0-2.793-.058-3.861-.144-2.674-.213-4.812-2.037-5.048-4.709A24 24 0 0 1 3 13c0-.796.035-1.51.09-2.148.237-2.671 2.375-4.496 5.049-4.708q-.052.003-.103.01C8.896 4.851 10.27 4 12 4m0 5a4 4 0 1 0 0 8 4 4 0 0 0 0-8", evenodd: true },
];
export const Clock: PapPath[] = [
{ d: "M12 3a9 9 0 1 1 0 18 9 9 0 0 1 0-18m0 3a1 1 0 0 0-1 1v3.93c0 .334-.167.647-.445.832l-2.11 1.406a1 1 0 0 0 1.11 1.665l2.11-1.407A3 3 0 0 0 13 10.93V7a1 1 0 0 0-1-1", evenodd: true },
];
export const Code: PapPath[] = [
{ d: "M7.898 4.009c.52-.104 1.088.021 1.56.336s.806.79.91 1.31-.03 1.043-.355 1.463l-.221.286-3.553 4.605 3.553 4.604.22.287c.326.42.46.942.355 1.462-.103.52-.437.996-.909 1.31-.472.316-1.04.441-1.56.337a1.8 1.8 0 0 1-1.213-.89l-.18-.314q-1.612-2.826-3.226-5.65l-.178-.314a1.44 1.44 0 0 1-.182-.615v-.436a1.44 1.44 0 0 1 .182-.613l.178-.314 3.226-5.65.18-.313a1.8 1.8 0 0 1 1.213-.891M13.94 4.345c.472-.315 1.04-.44 1.559-.336.52.104.95.429 1.214.89l.18.314 3.225 5.65.179.314c.141.248.2.54.181.83.02.293-.04.585-.181.834l-.179.313-3.225 5.65-.18.314a1.8 1.8 0 0 1-1.214.89c-.52.105-1.087-.02-1.56-.335-.472-.315-.805-.791-.909-1.31-.104-.52.03-1.043.355-1.463l.22-.287 3.553-4.604-3.553-4.605-.22-.286a1.8 1.8 0 0 1-.355-1.463c.104-.52.437-.995.91-1.31" },
];
export const Cross: PapPath[] = [
{ d: "M17.958 3.958c.53 0 1.059.23 1.456.628.397.397.628.926.628 1.456s-.23 1.02-.628 1.372l-.317.282L14.253 12l4.844 4.304.317.282c.397.353.628.841.628 1.372 0 .53-.23 1.059-.628 1.456-.397.397-.926.628-1.456.628s-1.02-.23-1.372-.628l-.282-.317L12 14.253l-4.304 4.844-.282.317a1.82 1.82 0 0 1-1.372.628c-.53 0-1.059-.23-1.456-.628-.398-.397-.628-.926-.628-1.456s.23-1.02.628-1.372l.317-.282L9.746 12 4.903 7.696l-.317-.282a1.82 1.82 0 0 1-.628-1.372c0-.53.23-1.059.628-1.456.397-.398.926-.628 1.456-.628s1.02.23 1.372.628l.282.317L12 9.746l4.304-4.843.282-.317a1.82 1.82 0 0 1 1.372-.628" },
];
export const Dots: PapPath[] = [
{ d: "M10 12a2 2 0 1 1 4 0 2 2 0 0 1-4 0M10 6a2 2 0 1 1 4 0 2 2 0 0 1-4 0M10 18a2 2 0 1 1 4 0 2 2 0 0 1-4 0" },
];
export const Folder: PapPath[] = [
{ d: "M18.295 12c1.462 0 2.194 0 2.618.373.19.166.334.378.42.614.193.531-.073 1.213-.603 2.575-.71 1.822-1.066 2.733-1.725 3.353a4 4 0 0 1-1.018.695c-.816.39-1.795.39-3.75.39H9.831c-1.945 0-2.917 0-3.727-.382a4 4 0 0 1-1.12-.787c-.634-.633-.964-1.548-1.624-3.378-.468-1.3-.702-1.952-.521-2.459a1.5 1.5 0 0 1 .458-.651C3.714 12 4.405 12 5.788 12zM8.7 4c.484 0 .726 0 .947.05a2 2 0 0 1 1.063.638c.148.171.262.385.49.812s.341.64.49.812a2 2 0 0 0 1.063.637c.22.05.463.051.947.051H17a3 3 0 0 1 3 3H4V8.571c0-1.464 0-2.197.25-2.77A3 3 0 0 1 5.8 4.25C6.374 4 7.106 4 8.57 4z" },
];
export const Font: PapPath[] = [
{ d: "M8.303 5.71c1.362-3.297 6.032-3.297 7.394 0l2.29 5.542 2.817 5.885a2 2 0 1 1-3.608 1.726l-.878-1.834H7.682l-.878 1.834a2 2 0 1 1-3.608-1.726l2.816-5.885zm1.39 7.112-.022.051-.024.049-.051.107h4.808l-.052-.107-.023-.049-.021-.05L12 7.236z" },
];
export const Gallery: PapPath[] = [
{ d: "M12 3c1.483 0 2.748.072 3.805.179 2.723.273 4.743 2.293 5.016 5.016C20.927 9.252 21 10.517 21 12s-.073 2.748-.179 3.805c-.274 2.723-2.293 4.743-5.016 5.016A38 38 0 0 1 12 21c-1.483 0-2.748-.073-3.805-.179-2.723-.274-4.743-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.072-2.748.179-3.805.273-2.723 2.293-4.743 5.016-5.016A38 38 0 0 1 12 3M9.842 13.212a2 2 0 0 0-2.683 0l-1.628 1.47a1.1 1.1 0 0 0-.362.923c.179 1.777 1.45 3.047 3.226 3.226.988.1 2.187.169 3.605.169s2.617-.07 3.605-.169c1.217-.122 2.195-.758 2.747-1.717.357-.617.082-1.366-.447-1.844l-.063-.058a2 2 0 0 0-2.683 0l-.212.191a2 2 0 0 1-2.681 0zM15 7a2 2 0 1 0 0 4 2 2 0 0 0 0-4" },
];
export const Gears: PapPath[] = [
{ d: "M12 3c.593 0 1.309.202 1.892.412.66.238.99.948.822 1.63l-.183.746c-.098.4.114.809.47 1.016.357.207.814.184 1.112-.102l.555-.531c.508-.486 1.287-.557 1.824-.104.473.4 1.006.92 1.302 1.433.297.514.48 1.235.59 1.845.124.69-.328 1.33-1.002 1.527l-.739.215c-.396.115-.643.5-.643.913 0 .412.246.797.642.913l.741.216c.674.197 1.125.835 1 1.526-.11.61-.292 1.331-.589 1.845-.296.514-.829 1.032-1.302 1.433-.537.453-1.316.383-1.824-.103l-.555-.532c-.298-.286-.754-.31-1.112-.103-.356.207-.569.616-.47 1.016l.183.747c.167.682-.161 1.393-.822 1.63-.583.21-1.3.412-1.892.412-.594 0-1.309-.201-1.892-.411-.66-.238-.99-.949-.822-1.631l.182-.748c.098-.4-.114-.809-.47-1.015-.358-.206-.814-.183-1.112.103l-.554.532c-.508.486-1.288.556-1.824.103-.473-.4-1.006-.92-1.302-1.433-.297-.514-.48-1.235-.59-1.845-.125-.69.327-1.33 1-1.526l.74-.216c.396-.115.644-.5.644-.913 0-.412-.248-.798-.644-.913l-.74-.215c-.673-.196-1.124-.836-1-1.527.11-.61.293-1.331.59-1.845.296-.514.829-1.032 1.302-1.433.537-.453 1.316-.382 1.824.104l.554.531c.298.285.754.309 1.112.102.356-.207.568-.615.47-1.016l-.182-.746c-.167-.682.161-1.392.822-1.63.583-.21 1.298-.412 1.891-.412m0 6a3 3 0 1 0 0 6 3 3 0 0 0 0-6", evenodd: true },
];
export const Globe: PapPath[] = [
{ d: "M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2M4.74 9a.24.24 0 0 0-.22.16A8 8 0 0 0 12 20c.509 0 1-.328 1-.837a1.837 1.837 0 0 0-1.837-1.836H8.826a1.044 1.044 0 0 1 0-2.087h.043c.6 0 1.087-.486 1.087-1.087v-.51c0-.881-.714-1.596-1.596-1.596h-.358a1.523 1.523 0 0 1-1.523-1.524C6.479 9.683 5.796 9 4.955 9zm7.778-1.774a1.703 1.703 0 0 0 1.185 2.925h1.873A2.425 2.425 0 0 1 18 12.576v.924c0 .294.084.567.23.798.457.723 1.428.168 1.602-.669q.166-.79.168-1.629a7.99 7.99 0 0 0-3.654-6.717c-.679-.44-1.556-.262-2.136.3z", evenodd: true },
];
export const Grid: PapPath[] = [
{ d: "M7 13c.552 0 1.036.023 1.454.058 1.364.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.363-1.124 2.374-2.488 2.488C8.036 20.977 7.552 21 7 21s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.125-2.488-2.488A17 17 0 0 1 3 17c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C5.964 13.023 6.448 13 7 13M17 13c.552 0 1.036.023 1.454.058 1.363.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.363-1.125 2.374-2.488 2.488-.418.035-.902.058-1.454.058s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.125-2.488-2.488A18 18 0 0 1 13 17c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488.418-.035.902-.058 1.454-.058M7 3c.552 0 1.036.023 1.454.058 1.364.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.364-1.124 2.374-2.488 2.488C8.036 10.977 7.552 11 7 11s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.124-2.488-2.488A17 17 0 0 1 3 7c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C5.964 3.023 6.448 3 7 3M17 3c.552 0 1.036.023 1.454.058 1.363.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.364-1.125 2.374-2.488 2.488-.418.035-.902.058-1.454.058s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.124-2.488-2.488A18 18 0 0 1 13 7c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C15.964 3.023 16.448 3 17 3" },
];
export const Info: PapPath[] = [
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m0 8a1 1 0 0 0-1 1v5a1 1 0 1 0 2 0v-5a1 1 0 0 0-1-1m0-4a1 1 0 1 0 0 2 1 1 0 0 0 0-2", evenodd: true },
];
export const Link: PapPath[] = [
{ d: "M9.415 10.429a1.5 1.5 0 0 1 2.12 2.12 10 10 0 0 0-.223.231c-.56.6-.606 1.602.24 2.546q.528.593 1.276 1.344.476.475.888.86c1.203 1.123 2.568 1.096 3.232.432.606-.606.867-1.051.975-1.33.1-.258.075-.384.067-.42a.3.3 0 0 0-.092-.155l-.007-.008.012.01.017.011.012.01q.003.001.006.004l.005.002a1.5 1.5 0 0 1 1.653-2.503l-.58.882c.553-.84.58-.88.582-.881l.002.002.005.003.01.006q.008.007.02.014l.05.037q.057.041.134.105a3.32 3.32 0 0 1 1.09 1.775c.327 1.389-.222 2.94-1.839 4.557-2.274 2.274-5.565 1.352-7.4-.36a39 39 0 0 1-2.354-2.396c-1.571-1.755-2.108-4.55-.194-6.597q.139-.149.293-.301" },
{ d: "M5.981 4.112c2.274-2.274 5.566-1.35 7.4.362a39 39 0 0 1 2.353 2.395c1.572 1.755 2.11 4.55.196 6.596q-.14.15-.293.303a1.5 1.5 0 0 1-2.122-2.122q.119-.117.224-.23c.561-.6.606-1.602-.24-2.546a35.758 35.758 0 0 0-2.165-2.203c-1.203-1.123-2.566-1.097-3.23-.433-.606.606-.867 1.051-.975 1.33-.1.257-.076.383-.068.42a.3.3 0 0 0 .092.156l.007.008q0-.001-.012-.01l-.016-.013-.013-.008-.006-.005-.005-.002a1.5 1.5 0 0 1-1.653 2.502l.58-.881c-.552.837-.58.88-.582.881l-.002-.002-.005-.002-.009-.007-.02-.014-.051-.036a3.263 3.263 0 0 1-.496-.462A3.3 3.3 0 0 1 4.14 8.67c-.325-1.389.223-2.94 1.84-4.558" },
];
export const List: PapPath[] = [
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.273 4.742 2.293 5.016 5.015C20.927 9.251 21 10.517 21 12s-.073 2.748-.179 3.805c-.274 2.723-2.293 4.743-5.016 5.016A38 38 0 0 1 12 21c-1.483 0-2.749-.073-3.806-.179-2.722-.274-4.742-2.293-5.015-5.016A38 38 0 0 1 3 12c0-1.483.072-2.749.179-3.806.274-2.722 2.293-4.741 5.015-5.015A38 38 0 0 1 12 3m-.5 12c-1.31 0-2.281.025-2.937.052C7.86 15.08 7 15.298 7 16s.86.92 1.563.948c.656.027 1.626.052 2.937.052s2.281-.025 2.938-.052C15.139 16.92 16 16.702 16 16s-.86-.92-1.562-.948A74 74 0 0 0 11.5 15m-1-4c-.91 0-1.609.02-2.111.043-.657.03-1.389.3-1.389.957 0 .658.732.927 1.389.957C8.89 12.98 9.59 13 10.5 13s1.609-.02 2.111-.043c.657-.03 1.389-.3 1.389-.957 0-.658-.732-.927-1.389-.957A46 46 0 0 0 10.5 11M12 7a90 90 0 0 0-3.347.055C7.927 7.082 7 7.274 7 8s.927.918 1.653.945C9.383 8.973 10.487 9 12 9s2.617-.027 3.347-.055C16.073 8.918 17 8.726 17 8s-.927-.918-1.653-.945A90 90 0 0 0 12 7" },
];
export const Lock: PapPath[] = [
{ d: "M12.324 3.866c3.316.171 5.504 2.964 5.636 6.349q.029.78.035 1.68c.656.043 1.117.14 1.505.364a3 3 0 0 1 1.098 1.098c.402.696.402 1.63.402 3.5s0 2.804-.402 3.5a3 3 0 0 1-1.098 1.098c-.696.402-1.63.402-3.5.402H8c-1.87 0-2.804 0-3.5-.402a3 3 0 0 1-1.098-1.098C3 19.661 3 18.727 3 16.857s0-2.804.402-3.5A3 3 0 0 1 4.5 12.26c.387-.223.849-.32 1.504-.365q.002-.336.007-.655l.029-1.024C6.176 6.72 8.503 3.857 12 3.857zM12 6.857c-1.497 0-2.872 1.172-2.962 3.474q-.026.707-.033 1.526h5.99a51 51 0 0 0-.033-1.526c-.09-2.302-1.465-3.474-2.962-3.474", evenodd: true },
];
export const Logout: PapPath[] = [
{ d: "M7.5 3c1.272 0 2.281.143 3.045.321 1.234.288 2.004 1.367 2.15 2.626q.069.582.131 1.346c.065.811-.634 1.47-1.443 1.38L11 8.634c-.884-.098-1.732.167-2.357.794-.626.623-.976 1.557-.976 2.539s.35 1.916.976 2.539c.625.626 1.473.891 2.357.794l.382-.041c.81-.089 1.512.568 1.448 1.382a38 38 0 0 1-.136 1.413c-.146 1.259-.916 2.338-2.15 2.626C9.78 20.857 8.772 21 7.5 21s-2.282-.143-3.045-.321c-1.234-.288-2.004-1.367-2.15-2.626C2.152 16.74 2 14.743 2 12s.152-4.74.305-6.053c.146-1.259.916-2.338 2.15-2.626C5.218 3.143 6.228 3 7.5 3m8.396 4.384a1 1 0 0 1 1.414 0l3.773 3.773a1 1 0 0 1 0 1.414l-3.773 3.773a1 1 0 0 1-1.414-1.414L17.824 13l-6.442.281L11 13.3a1.25 1.25 0 0 1-.943-.361c-.25-.25-.39-.603-.39-.972 0-.37.14-.722.39-.972s.59-.377.943-.361l.382.016 6.655.29-2.141-2.141a1 1 0 0 1 0-1.414" },
];
export const Menu: PapPath[] = [
{ d: "M12 17c2.472 0 3.263.043 4.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415C15.263 19.957 14.472 20 12 20s-3.263-.043-4.429-.085C6.457 19.875 5 19.615 5 18.5s1.457-1.375 2.571-1.415C8.737 17.043 9.528 17 12 17M12 11c2.472 0 2.263.043 3.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415c-1.166.042-.957.085-3.429.085s-2.263-.043-3.429-.085C7.457 13.875 6 13.615 6 12.5s1.457-1.375 2.571-1.415C9.737 11.043 9.528 11 12 11M12 5c2.472 0 4.263.043 5.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415A152 152 0 0 1 12 8c-2.472 0-4.263-.043-5.429-.085C5.457 7.875 4 7.615 4 6.5s1.457-1.375 2.571-1.415C7.737 5.043 9.528 5 12 5" },
];
export const Moon: PapPath[] = [
{ d: "M11 3.857c.79 0 1 1.185.464 1.764a5.5 5.5 0 0 0 7.77 7.772c.58-.536 1.766-.325 1.766.464.003 4.97-4.03 8-9 8a9 9 0 0 1-9-9c0-4.97 3.03-9 8-9" },
];
export const Paper: PapPath[] = [
{ d: "M12 7.828a4 4 0 0 0 4 4c.932 0 1.398 0 1.765.152a2 2 0 0 1 1.083 1.082c.152.368.152.834.152 1.766V15c0 2.828 0 4.243-.879 5.122S15.828 21 13 21h-2c-2.828 0-4.242 0-5.121-.878C5 19.242 5 17.828 5 14.999v-4c0-2.808 0-4.212.674-5.221a4 4 0 0 1 1.103-1.104c.39-.26.837-.42 1.402-.518 1.538-.267 2.307-.401 2.99.09.073.053.165.13.23.193C12 5.028 12 5.961 12 7.828" },
{ d: "M14 6.365c0-1.004 0-1.506.304-1.636s.666.219 1.39.915l2.792 2.688c.316.304.501.701.507 1.14.003.186-.147.356-.334.356H16l-.204-.011A2 2 0 0 1 14 7.827z" },
];
export const PenAlt: PapPath[] = [
{ d: "M19.145 14.688a.4.4 0 0 1 .157.054c.229.125.343 1.145.573 3.184l.029.26c.122 1.088.184 1.633-.128 1.966q-.027.029-.057.055c-.337.308-.887.247-1.988.127l-.263-.029c-2.065-.226-3.097-.34-3.223-.566a.4.4 0 0 1-.055-.154c-.044-.254.746-1.036 2.327-2.598s2.371-2.343 2.628-2.299M12.326 8.006a1.19 1.19 0 0 1 1.676-.012c1.7 1.68 2.692 2.933 3.205 3.65.307.43.366.974.111 1.437-.332.602-.958 1.53-2.082 2.64s-2.062 1.729-2.672 2.057c-.468.252-1.018.194-1.454-.11-.725-.507-1.994-1.487-3.694-3.166a1.163 1.163 0 0 1 .012-1.656zM8.494 4.923c.681-.413 1.51-.325 2.151.147.552.406.585 1.207.098 1.688l-4.58 4.526c-.49.484-1.292.451-1.706-.099-.478-.634-.567-1.452-.149-2.126.365-.586.951-1.374 1.873-2.285s1.72-1.49 2.313-1.85" },
];
export const Pie: PapPath[] = [
{ d: "M11 12a1 1 0 0 0 1 1h4.477c2.117 0 3.175 0 3.736 1.074s.1 1.738-.824 3.065A9 9 0 1 1 6.862 4.612c1.326-.924 1.99-1.386 3.064-.825S11 5.407 11 7.523z" },
{ d: "M13 7.247c0-1.777 0-2.665.823-3.264.112-.082.336-.203.466-.252.95-.362 1.507 0 2.62.726a9.05 9.05 0 0 1 2.634 2.634c.726 1.113 1.088 1.67.726 2.62-.049.13-.17.354-.252.466-.599.823-1.487.823-3.264.823-1.647 0-2.47 0-3.024-.455a2 2 0 0 1-.274-.274C13 9.717 13 8.894 13 7.247" },
];
export const Placeholder: PapPath[] = [
{ d: "M4 17.357a1.5 1.5 0 0 1 1.5 1.5v.5H6a1.5 1.5 0 0 1 0 3H5a2.5 2.5 0 0 1-2.5-2.5v-1a1.5 1.5 0 0 1 1.5-1.5M13 19.357a1.5 1.5 0 0 1 0 3h-2a1.5 1.5 0 0 1 0-3zM20 17.357a1.5 1.5 0 0 1 1.5 1.5v1a2.5 2.5 0 0 1-2.5 2.5h-1a1.5 1.5 0 0 1 0-3h.5v-.5a1.5 1.5 0 0 1 1.5-1.5M4 10.357a1.5 1.5 0 0 1 1.5 1.5v2a1.5 1.5 0 0 1-3 0v-2a1.5 1.5 0 0 1 1.5-1.5M20 10.357a1.5 1.5 0 0 1 1.5 1.5v2a1.5 1.5 0 0 1-3 0v-2a1.5 1.5 0 0 1 1.5-1.5M6 3.357a1.5 1.5 0 1 1 0 3h-.5v.5a1.5 1.5 0 0 1-3 0v-1a2.5 2.5 0 0 1 2.5-2.5zM19 3.357a2.5 2.5 0 0 1 2.5 2.5v1a1.5 1.5 0 0 1-3 0v-.5H18a1.5 1.5 0 0 1 0-3zM13 3.357a1.5 1.5 0 0 1 0 3h-2a1.5 1.5 0 0 1 0-3z" },
];
export const Search: PapPath[] = [
{ d: "M10 3a7 7 0 0 1 5.573 11.232l4.078 3.548c1.28 1.114.492 3.22-1.205 3.22a1.84 1.84 0 0 1-1.43-.685l-3.453-4.29A7 7 0 1 1 10 3m0 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8", evenodd: true },
];
export const Sparkles: PapPath[] = [
{ d: "M12.647 16.859c-1.087 2.185-1.63 3.278-2.412 3.543a2 2 0 0 1-1.284 0c-.782-.265-1.325-1.358-2.412-3.543-1.156-.202-1.735-.302-1.876-.35-1.888-.626-1.801-3.326.123-3.831.144-.038.68-.097 1.753-.213 1.064-2.252 1.596-3.378 2.365-3.66a2 2 0 0 1 1.378 0c.77.282 1.301 1.408 2.365 3.66 1.176.114 1.765.172 1.91.208 1.958.49 2.038 3.246.11 3.849-.142.044-.768.142-2.02.337M14.294 9.114l-.25-.14c-.944-.531-1.416-.796-1.549-1.114a1 1 0 0 1 .081-.925c.186-.29.697-.47 1.718-.827.768-1.43 1.152-2.146 1.682-2.343a1.5 1.5 0 0 1 1.047 0c.53.197.915.912 1.683 2.343 1.021.358 1.532.537 1.718.827a1 1 0 0 1 .08.925c-.132.318-.604.583-1.547 1.113l-.251.141c-.79 1.39-1.184 2.085-1.726 2.269a1.5 1.5 0 0 1-.96 0c-.542-.183-.937-.879-1.726-2.269" },
];
export const Star: PapPath[] = [
{ d: "m7.82 8.84-1.563 5.203L12 17.68l5.744-3.637L16.18 8.84z" },
{ d: "M12 17.68c2.723 2.55 4.084 3.826 5.08 3.639a2 2 0 0 0 1.091-.6c.693-.74.347-2.573-.345-6.239l-.082-.437z" },
{ d: "m16.18 8.84 1.564 5.203c2.305-1.066 3.459-1.599 3.76-2a2 2 0 0 0-.651-2.965c-.443-.238-1.713-.238-4.254-.238zM7.82 8.84h8.36l-.564-1.192C14.05 4.335 13.266 2.68 12 2.68s-2.05 1.656-3.616 4.97zM6.174 14.48c-.692 3.666-1.038 5.499-.345 6.24a2 2 0 0 0 1.09.599c.997.187 2.359-1.088 5.081-3.639l-5.743-3.637zM6.257 14.043 7.82 8.84h-.419c-2.54 0-3.81 0-4.254.238a2 2 0 0 0-.652 2.965c.302.401 1.455.934 3.762 2" },
];
export const Tasks: PapPath[] = [
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m5.63 4.223a1 1 0 0 0-1.407.148l-5.773 7.136-2.213-2.214-.077-.068a1 1 0 0 0-1.338 1.482l2.214 2.214a2 2 0 0 0 2.97-.156l5.772-7.136a1 1 0 0 0-.149-1.406", evenodd: true },
];
export const Trash: PapPath[] = [
{ d: "M14.876 10.29c2.406-.085 3.608-.127 4.233.586.626.713.433 1.87.047 4.187l-.321 1.923c-.4 2.395-.598 3.592-1.437 4.303S15.344 22 12.917 22h-1.835c-2.427 0-3.641 0-4.48-.71-.84-.712-1.039-1.91-1.438-4.304l-.32-1.924c-.386-2.315-.58-3.473.046-4.186.625-.713 1.828-.67 4.234-.587.934.033 1.917.054 2.876.054s1.942-.021 2.876-.054M8.5 12a1 1 0 0 0-1 1v6a1 1 0 0 0 2 0v-6a1 1 0 0 0-1-1m3.5 0a1 1 0 0 0-1 1v6a1 1 0 1 0 2 0v-6a1 1 0 0 0-1-1m3.5 0a1 1 0 0 0-1 1v6a1 1 0 1 0 2 0v-6a1 1 0 0 0-1-1M12 2c1.275 0 2.271.276 2.97.854.722.597.978 1.388 1.022 2.083.024.376-.013.74-.073 1.063h2.73C19.395 6 20 6.605 20 7.35c0 .663-.48 1.224-1.138 1.297C17.547 8.795 15.151 9 12 9c-3.15 0-5.546-.205-6.862-.353A1.29 1.29 0 0 1 4 7.351C4 6.605 4.605 6 5.35 6h2.731a4.3 4.3 0 0 1-.073-1.063c.044-.695.3-1.486 1.021-2.083C9.73 2.276 10.725 2 12 2m0 2c-1.018 0-1.488.224-1.696.396-.186.153-.28.362-.3.667-.02.302.043.638.133.937h3.726c.09-.3.152-.635.133-.937-.02-.305-.114-.514-.3-.667C13.488 4.224 13.018 4 12 4" },
];
export const User: PapPath[] = [
{ d: "M17 8A5 5 0 1 1 7 8a5 5 0 0 1 10 0M4.345 18.582c.052-.358.077-.537.094-.628.41-2.155 2.06-3.414 4.247-3.24.091.008.35.04.868.105.85.107 1.705.181 2.446.181s1.595-.073 2.446-.18c.518-.066.777-.098.868-.106 2.187-.174 3.837 1.085 4.247 3.24.017.09.042.27.094.628.017.124.026.185.03.236a2 2 0 0 1-1.89 2.18c-.05.002-.113.002-.238.002H6.444c-.125 0-.188 0-.238-.003a2 2 0 0 1-1.89-2.18c.004-.05.013-.111.03-.235" },
];
File diff suppressed because it is too large. Load diff
+232
View File
@@ -0,0 +1,232 @@
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
import { errMsg } from "./api";
import { CheckIcon, CopyIcon } from "./icons";
// --- Chargement de données ---------------------------------------------------------
export function useLoad<T>(fn: () => Promise<T>, deps: unknown[] = []) {
const [state, setState] = useState<{ data?: T; error?: string; loading: boolean }>({ loading: true });
const [n, setN] = useState(0);
const fnRef = useRef(fn);
fnRef.current = fn;
useEffect(() => {
let live = true;
setState((s) => ({ ...s, loading: true }));
fnRef.current().then(
(data) => live && setState({ data, loading: false }),
(e) => live && setState({ error: errMsg(e), loading: false }),
);
return () => {
live = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...deps, n]);
const reload = useCallback(() => setN((x) => x + 1), []);
return { ...state, reload };
}
// --- Messages ------------------------------------------------------------------------
type Notify = (msg: string, kind?: "error" | "ok") => void;
const ToastCtx = createContext<Notify>(() => {});
export const useNotify = () => useContext(ToastCtx);
export function ToastProvider({ children }: { children: ReactNode }) {
const [toast, setToast] = useState<{ msg: string; kind: "error" | "ok" } | null>(null);
const timer = useRef<number>(0);
const notify = useCallback<Notify>((msg, kind = "error") => {
setToast({ msg, kind });
window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => setToast(null), kind === "error" ? 9000 : 3500);
}, []);
return (
<ToastCtx.Provider value={notify}>
{children}
{toast && (
<div className={`${toast.kind === "error" ? "error" : "notice"} floating`} role="alert" onClick={() => setToast(null)}>
{toast.msg}
</div>
)}
</ToastCtx.Provider>
);
}
/** Exécute une action : l'erreur éventuelle s'affiche en bandeau ; renvoie true si elle a réussi. */
export function useAct() {
const notify = useNotify();
return useCallback(
async (fn: () => Promise<unknown>, okMsg?: string) => {
try {
await fn();
if (okMsg) notify(okMsg, "ok");
return true;
} catch (e) {
notify(errMsg(e));
return false;
}
},
[notify],
);
}
// --- Composants ---------------------------------------------------------------------
export function Modal({ title, onClose, children, small }: { title: string; onClose: () => void; children: ReactNode; small?: boolean }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className={`modal ${small ? "small" : ""}`} role="dialog" aria-modal="true" aria-label={title}>
<h3>{title}</h3>
{children}
</div>
</div>
);
}
export function Confirm({
title,
message,
confirmLabel = "Confirmer",
requireText,
danger = true,
onConfirm,
onClose,
}: {
title: string;
message: ReactNode;
confirmLabel?: string;
/** Texte à retaper pour valider (suppressions). */
requireText?: string;
danger?: boolean;
onConfirm: () => Promise<unknown> | void;
onClose: () => void;
}) {
const [typed, setTyped] = useState("");
const [busy, setBusy] = useState(false);
const ok = !requireText || typed === requireText;
return (
<Modal title={title} onClose={onClose} small>
<div className="modal-text">{message}</div>
{requireText && (
<label className="field" style={{ marginTop: "0.8rem" }}>
<span>
Tapez <code>{requireText}</code> pour confirmer
</span>
<input type="text" value={typed} onChange={(e) => setTyped(e.target.value)} autoFocus autoComplete="off" />
</label>
)}
<div className="modal-actions">
<span className="spacer" />
<button onClick={onClose}>Annuler</button>
<button
className={danger ? "danger-fill" : "primary"}
disabled={!ok || busy}
onClick={async () => {
setBusy(true);
try {
await onConfirm();
} finally {
setBusy(false);
}
}}
>
{confirmLabel}
</button>
</div>
</Modal>
);
}
export async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
const t = document.createElement("textarea");
t.value = text;
t.style.position = "fixed";
t.style.opacity = "0";
document.body.appendChild(t);
t.select();
document.execCommand("copy");
t.remove();
}
}
export function CopyButton({ text, label }: { text: string; label?: string }) {
const [done, setDone] = useState(false);
return (
<button
className={label ? "" : "icon-btn"}
title="Copier"
aria-label="Copier"
onClick={async () => {
await copyText(text);
setDone(true);
setTimeout(() => setDone(false), 1500);
}}
>
{done ? <CheckIcon /> : <CopyIcon />}
{label}
</button>
);
}
/** Identifiant technique : tronqué à l'affichage, complet au survol et à la copie. */
export function Mono({ value, short = 12 }: { value: string; short?: number }) {
return (
<code title={value} className="mono">
{value.length > short + 1 ? value.slice(0, short) + "…" : value}
</code>
);
}
export function Status({ kind, children }: { kind: "ok" | "warn" | "bad" | "off"; children: ReactNode }) {
return <span className={`status ${kind}`}>{children}</span>;
}
export function UsageBar({ used, total, warn = 80 }: { used: number; total: number; warn?: number }) {
const pct = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
return (
<div className="bar" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100} title={`${pct} %`}>
<span style={{ width: `${pct}%` }} className={pct >= 90 ? "err" : pct >= warn ? "warn" : ""} />
</div>
);
}
export function PageHead({ title, children, back }: { title: ReactNode; children?: ReactNode; back?: { href: string; label: string } }) {
return (
<div className="page-head">
<div className="grow">
{back && (
<a className="back" href={back.href}>
← {back.label}
</a>
)}
<h2>{title}</h2>
</div>
{children}
</div>
);
}
export function Loading({ loading, error, onRetry }: { loading: boolean; error?: string; onRetry?: () => void }) {
if (error)
return (
<div className="error" style={{ cursor: "default" }}>
{error}
{onRetry && (
<>
{" "}
<button className="link" onClick={onRetry}>
Réessayer
</button>
</>
)}
</div>
);
return loading ? <p className="muted">Chargement…</p> : null;
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true,
"allowImportingTsExtensions": false,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
// Le build est embarqué dans le binaire Go (web/dist).
build: { outDir: "../web/dist", emptyOutDir: true },
// `npm run dev` : le serveur Go tourne sur :8080.
server: { proxy: { "/api": "http://localhost:8080" } },
});
+3
View File
@@ -0,0 +1,3 @@
module github.com/vLab-BZH/garage-ui
go 1.24.7
+10
View File
@@ -0,0 +1,10 @@
// Package web embarque le frontend compilé (frontend/ -> web/dist) dans le binaire.
package web
import "embed"
// Dist contient le build Vite. En développement, dist/ peut ne contenir que
// .gitkeep : le serveur affiche alors un message invitant à lancer le build.
//
//go:embed all:dist
var Dist embed.FS