diff --git a/backend/cmd/api/main.go b/backend/cmd/api/main.go index 3589f50..c6e0efd 100644 --- a/backend/cmd/api/main.go +++ b/backend/cmd/api/main.go @@ -12,6 +12,7 @@ import ( "backend/internal/modules/checkoutfields" "backend/internal/modules/contactlinks" "backend/internal/modules/customerverification" + "backend/internal/modules/ldmod" "backend/internal/modules/media" "backend/internal/modules/orders" "backend/internal/modules/pricing" @@ -91,6 +92,11 @@ func main() { checkoutFieldsService := checkoutfields.NewService(checkoutFieldsRepo) checkoutFieldsHandler := checkoutfields.NewHandler(checkoutFieldsService) + // --- Light/dark mode module --- + ldModRepo := ldmod.NewRepository(database) + ldModService := ldmod.NewService(ldModRepo) + ldModHandler := ldmod.NewHandler(ldModService) + // --- Products module --- productsRepo := products.NewRepository(database) productsService := products.NewService(productsRepo, categoriesRepo) @@ -175,6 +181,9 @@ func main() { checkoutfields.RegisterAdminRoutes(api, checkoutFieldsHandler, requireAdmin) checkoutfields.RegisterPublicRoutes(api, checkoutFieldsHandler) + ldmod.RegisterAdminRoutes(api, ldModHandler, requireAdmin) + ldmod.RegisterPublicRoutes(api, ldModHandler) + products.RegisterAdminRoutes(api, productsHandler, requireAdmin) products.RegisterPublicRoutes(api, productsHandler) diff --git a/backend/internal/modules/ldmod/handler.go b/backend/internal/modules/ldmod/handler.go new file mode 100644 index 0000000..4ce3b81 --- /dev/null +++ b/backend/internal/modules/ldmod/handler.go @@ -0,0 +1,64 @@ +package ldmod + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" +) + +type Handler struct { + service *Service +} + +func NewHandler(service *Service) *Handler { + return &Handler{service: service} +} + +// settingsPayload est à la fois la réponse et la requête. +type settingsPayload struct { + ToggleEnabled bool `json:"toggle_enabled"` + DefaultTheme string `json:"default_theme" binding:"omitempty,oneof=light dark"` +} + +func toPayload(m *LDMod) settingsPayload { + return settingsPayload{ToggleEnabled: m.ToggleEnabled, DefaultTheme: m.DefaultTheme} +} + +func (h *Handler) fail(c *gin.Context, err error, msg string) { + switch { + case errors.Is(err, ErrNotFound): + c.JSON(http.StatusNotFound, gin.H{"error": "ld mod settings not found"}) + case errors.Is(err, ErrInvalidTheme): + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + default: + c.JSON(http.StatusInternalServerError, gin.H{"error": msg}) + } +} + +// Get : lecture publique, utilisée par le storefront pour savoir si le +// bouton de bascule clair/sombre doit s'afficher et, sinon, quel thème +// forcer. +func (h *Handler) Get(c *gin.Context) { + m, err := h.service.Get(c.Request.Context()) + if err != nil { + h.fail(c, err, "failed to load theme settings") + return + } + c.JSON(http.StatusOK, toPayload(m)) +} + +// Update : écriture admin des deux réglages d'un coup. +func (h *Handler) Update(c *gin.Context) { + var req settingsPayload + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()}) + return + } + m, err := h.service.Update(c.Request.Context(), &LDMod{ToggleEnabled: req.ToggleEnabled, DefaultTheme: req.DefaultTheme}) + if err != nil { + h.fail(c, err, "failed to update theme settings") + return + } + c.JSON(http.StatusOK, toPayload(m)) +} diff --git a/backend/internal/modules/ldmod/model.go b/backend/internal/modules/ldmod/model.go new file mode 100644 index 0000000..d575948 --- /dev/null +++ b/backend/internal/modules/ldmod/model.go @@ -0,0 +1,17 @@ +package ldmod + +// LDMod : réglage global du mode clair/sombre côté storefront. L'admin +// décide si le client peut basculer lui-même (ToggleEnabled) ou si le site +// reste figé sur DefaultTheme. Ligne unique, comme checkoutfields. +type LDMod struct { + ID int16 `gorm:"primaryKey"` + ToggleEnabled bool `gorm:"not null;default:true"` + DefaultTheme string `gorm:"not null;default:'dark'"` +} + +func (LDMod) TableName() string { return "ld_mod" } + +const ( + ThemeLight = "light" + ThemeDark = "dark" +) diff --git a/backend/internal/modules/ldmod/repository.go b/backend/internal/modules/ldmod/repository.go new file mode 100644 index 0000000..0baf9e9 --- /dev/null +++ b/backend/internal/modules/ldmod/repository.go @@ -0,0 +1,54 @@ +package ldmod + +import ( + "context" + "errors" + + "gorm.io/gorm" +) + +// singletonID : l'unique ligne de ld_mod (voir la contrainte CHECK (id = 1) +// de la migration 000035). +const singletonID int16 = 1 + +var ErrNotFound = errors.New("ld mod settings not found") + +type Repository interface { + Get(ctx context.Context) (*LDMod, error) + Update(ctx context.Context, m *LDMod) (*LDMod, error) +} + +type gormRepository struct { + db *gorm.DB +} + +func NewRepository(db *gorm.DB) Repository { + return &gormRepository{db: db} +} + +func (r *gormRepository) Get(ctx context.Context) (*LDMod, error) { + var m LDMod + err := r.db.WithContext(ctx).First(&m, singletonID).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &m, nil +} + +// Update écrit tous les réglages sur la ligne unique. Select("*") est voulu : +// sans lui GORM ignore les champs à valeur zéro d'une struct, donc passer +// false n'écrirait rien et l'admin ne pourrait jamais désactiver le toggle. +func (r *gormRepository) Update(ctx context.Context, m *LDMod) (*LDMod, error) { + m.ID = singletonID + res := r.db.WithContext(ctx).Model(&LDMod{}).Where("id = ?", singletonID).Select("*").Updates(m) + if res.Error != nil { + return nil, res.Error + } + if res.RowsAffected == 0 { + return nil, ErrNotFound + } + return r.Get(ctx) +} diff --git a/backend/internal/modules/ldmod/routes.go b/backend/internal/modules/ldmod/routes.go new file mode 100644 index 0000000..f452b6a --- /dev/null +++ b/backend/internal/modules/ldmod/routes.go @@ -0,0 +1,16 @@ +package ldmod + +import "github.com/gin-gonic/gin" + +func RegisterAdminRoutes(rg *gin.RouterGroup, h *Handler, requireAdmin gin.HandlerFunc) { + group := rg.Group("/admin/theme-settings", requireAdmin) + group.GET("", h.Get) + group.PUT("", h.Update) +} + +// RegisterPublicRoutes expose les réglages en lecture seule : le storefront +// en a besoin pour savoir s'il doit afficher le bouton de bascule clair/ +// sombre, et sinon quel thème forcer. +func RegisterPublicRoutes(rg *gin.RouterGroup, h *Handler) { + rg.GET("/theme-settings", h.Get) +} diff --git a/backend/internal/modules/ldmod/service.go b/backend/internal/modules/ldmod/service.go new file mode 100644 index 0000000..2ac0fee --- /dev/null +++ b/backend/internal/modules/ldmod/service.go @@ -0,0 +1,31 @@ +package ldmod + +import ( + "context" + "errors" +) + +var ErrInvalidTheme = errors.New("default_theme must be 'light' or 'dark'") + +type Service struct { + repo Repository +} + +func NewService(repo Repository) *Service { + return &Service{repo: repo} +} + +func (s *Service) Get(ctx context.Context) (*LDMod, error) { + return s.repo.Get(ctx) +} + +// Update remplace les deux réglages. default_theme n'a de sens que parmi les +// deux thèmes que le frontend sait rendre (voir theme/ThemeContext.tsx côté +// frontend) : le client ne doit jamais pouvoir pousser une valeur arbitraire +// qui ferait planter le rendu. +func (s *Service) Update(ctx context.Context, m *LDMod) (*LDMod, error) { + if m.DefaultTheme != ThemeLight && m.DefaultTheme != ThemeDark { + return nil, ErrInvalidTheme + } + return s.repo.Update(ctx, m) +} diff --git a/backend/migrations/000035_create_ld_mod.down.sql b/backend/migrations/000035_create_ld_mod.down.sql new file mode 100644 index 0000000..8092b22 --- /dev/null +++ b/backend/migrations/000035_create_ld_mod.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ld_mod; diff --git a/backend/migrations/000035_create_ld_mod.up.sql b/backend/migrations/000035_create_ld_mod.up.sql new file mode 100644 index 0000000..4867542 --- /dev/null +++ b/backend/migrations/000035_create_ld_mod.up.sql @@ -0,0 +1,11 @@ +-- Réglage global du mode clair/sombre côté storefront : l'admin décide si le +-- client peut basculer lui-même (toggle_enabled) ou si le site reste figé +-- sur default_theme. Une seule ligne : CHECK (id = 1) interdit toute autre +-- ligne, comme checkout_fields (voir 000032). +CREATE TABLE ld_mod ( + id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1), + toggle_enabled BOOLEAN NOT NULL DEFAULT true, + default_theme TEXT NOT NULL DEFAULT 'dark' CHECK (default_theme IN ('light', 'dark')) +); + +INSERT INTO ld_mod (id) VALUES (1); diff --git a/backend/test/ldmod/ldmod_test.go b/backend/test/ldmod/ldmod_test.go new file mode 100644 index 0000000..0bbed44 --- /dev/null +++ b/backend/test/ldmod/ldmod_test.go @@ -0,0 +1,151 @@ +package ldmod_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/gin-gonic/gin" + "gorm.io/gorm/schema" + + "backend/internal/modules/ldmod" +) + +// fakeRepository garde la ligne unique en mémoire. Comme le vrai dépôt, +// Update remplace TOUS les champs. +type fakeRepository struct { + mu sync.Mutex + row *ldmod.LDMod +} + +func newFakeRepository() *fakeRepository { + return &fakeRepository{row: &ldmod.LDMod{ID: 1, ToggleEnabled: true, DefaultTheme: ldmod.ThemeDark}} +} + +func (r *fakeRepository) Get(context.Context) (*ldmod.LDMod, error) { + r.mu.Lock() + defer r.mu.Unlock() + cp := *r.row + return &cp, nil +} + +func (r *fakeRepository) Update(_ context.Context, m *ldmod.LDMod) (*ldmod.LDMod, error) { + r.mu.Lock() + defer r.mu.Unlock() + cp := *m + cp.ID = 1 + r.row = &cp + out := cp + return &out, nil +} + +func newRouter() *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + h := ldmod.NewHandler(ldmod.NewService(newFakeRepository())) + api := r.Group("/api") + ldmod.RegisterPublicRoutes(api, h) + ldmod.RegisterAdminRoutes(api, h, func(c *gin.Context) { c.Next() }) + return r +} + +func do(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +func decode(t *testing.T, w *httptest.ResponseRecorder) map[string]any { + t.Helper() + var m map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil { + t.Fatalf("réponse JSON invalide: %v (%s)", err, w.Body) + } + return m +} + +func TestGet_ReturnsCurrentSettings(t *testing.T) { + w := do(newRouter(), "GET", "/api/theme-settings", "") + if w.Code != http.StatusOK { + t.Fatalf("HTTP %d, attendu 200", w.Code) + } + m := decode(t, w) + if m["toggle_enabled"] != true || m["default_theme"] != "dark" { + t.Errorf("valeurs par défaut inattendues: %v", m) + } +} + +func TestUpdate_CanDisableToggleAndForceLight(t *testing.T) { + r := newRouter() + w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":false,"default_theme":"light"}`) + if w.Code != http.StatusOK { + t.Fatalf("HTTP %d: %s", w.Code, w.Body) + } + m := decode(t, w) + if m["toggle_enabled"] != false || m["default_theme"] != "light" { + t.Errorf("valeurs = %v", m) + } + // toggle_enabled=false doit bien persister (pas ignoré comme un zéro de struct Go). + if got := decode(t, do(r, "GET", "/api/theme-settings", "")); got["toggle_enabled"] != false { + t.Errorf("le GET public ne reflète pas la désactivation: %v", got) + } +} + +func TestUpdate_RejectsInvalidTheme(t *testing.T) { + r := newRouter() + w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":true,"default_theme":"purple"}`) + if w.Code != http.StatusBadRequest { + t.Errorf("HTTP %d, attendu 400", w.Code) + } +} + +func TestUpdate_RejectsInvalidBody(t *testing.T) { + w := do(newRouter(), "PUT", "/api/admin/theme-settings", `not json`) + if w.Code != http.StatusBadRequest { + t.Errorf("HTTP %d, attendu 400", w.Code) + } +} + +func TestAdminRoute_RequiresAdminMiddleware(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + h := ldmod.NewHandler(ldmod.NewService(newFakeRepository())) + api := r.Group("/api") + ldmod.RegisterPublicRoutes(api, h) + ldmod.RegisterAdminRoutes(api, h, func(c *gin.Context) { c.AbortWithStatus(http.StatusUnauthorized) }) + + if w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":true,"default_theme":"dark"}`); w.Code != http.StatusUnauthorized { + t.Errorf("PUT admin sans droit : HTTP %d, attendu 401", w.Code) + } + if w := do(r, "GET", "/api/theme-settings", ""); w.Code != http.StatusOK { + t.Errorf("GET public : HTTP %d, attendu 200", w.Code) + } +} + +// Les noms de colonnes de la migration 000035 doivent être ceux que GORM +// déduit des champs de la struct. +func TestModelColumnsMatchMigration(t *testing.T) { + want := []string{"id", "toggle_enabled", "default_theme"} + s, err := schema.Parse(&ldmod.LDMod{}, &sync.Map{}, schema.NamingStrategy{}) + if err != nil { + t.Fatal(err) + } + got := map[string]bool{} + for _, f := range s.Fields { + got[f.DBName] = true + } + for _, col := range want { + if !got[col] { + t.Errorf("colonne %q absente du modèle (colonnes GORM: %v)", col, s.DBNames) + } + } + if s.Table != "ld_mod" { + t.Errorf("table %q, attendu ld_mod", s.Table) + } +} diff --git a/backend/uploads/8d34481d-5e41-4f43-bb5a-68983fc204eb.png b/backend/uploads/8d34481d-5e41-4f43-bb5a-68983fc204eb.png deleted file mode 100644 index dccc4d1..0000000 Binary files a/backend/uploads/8d34481d-5e41-4f43-bb5a-68983fc204eb.png and /dev/null differ diff --git a/backend/uploads/fb2c2ebf-de0b-4b7e-b423-dd9946292e47.png b/backend/uploads/fb2c2ebf-de0b-4b7e-b423-dd9946292e47.png deleted file mode 100644 index dccc4d1..0000000 Binary files a/backend/uploads/fb2c2ebf-de0b-4b7e-b423-dd9946292e47.png and /dev/null differ diff --git a/docker-compose.yml b/docker-compose.yml index c84998f..7462a2d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,3 +1,33 @@ +# Stack locale complète : base, cache, API, migrations, frontend. +# +# Démarrage : +# cp .env.example .env # puis remplacer les mots de passe et JWT_SECRET +# docker compose up -d --build +# docker compose --profile seed run --rm seed # une seule fois : compte admin +# +# Ouvrir http://localhost:${FRONTEND_PORT:-8081}. L'API n'est pas publiée +# directement : tout passe par le frontend, comme en production. +# +# Les mots de passe sont insérés dans les URL (DATABASE_URL, REDIS_URL) : ils +# ne doivent contenir ni @ : / ? # ni %, sinon les encoder en %XX. + +x-backend-env: &backend-env + DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}?sslmode=disable + REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379/0 + JWT_SECRET: ${JWT_SECRET:?JWT_SECRET est requis dans .env} + GIN_MODE: release + PORT: "8080" + COOKIE_SECURE: "false" + CORS_ORIGIN: http://localhost:${FRONTEND_PORT:-8081} + ACCESS_TOKEN_TTL_MINUTES: ${ACCESS_TOKEN_TTL_MINUTES:-15} + REFRESH_TOKEN_TTL_HOURS: ${REFRESH_TOKEN_TTL_HOURS:-168} + ADMIN_NUMBER: ${ADMIN_NUMBER:-1} + MEDIA_STORAGE_DRIVER: local + MEDIA_MAX_UPLOAD_MB: ${MEDIA_MAX_UPLOAD_MB:-10} + MEDIA_LOCAL_DIR: /app/uploads + MEDIA_LOCAL_BASE_URL: http://localhost:${FRONTEND_PORT:-8081}/uploads + VERIFICATION_UPLOAD_DIR: /app/verification-uploads + services: postgres: image: postgres:16-alpine @@ -8,7 +38,7 @@ services: POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_DB: ${DB_NAME} ports: - - "${DB_PORT}:5432" + - "${DB_PORT:-5432}:5432" volumes: - postgres_data:/var/lib/postgresql/data healthcheck: @@ -23,7 +53,7 @@ services: restart: unless-stopped command: ["redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD}"] ports: - - "${REDIS_PORT}:6379" + - "${REDIS_PORT:-6379}:6379" volumes: - redis_data:/data healthcheck: @@ -32,6 +62,91 @@ services: timeout: 5s retries: 5 + # Applique backend/migrations une fois, avant l'API. Idempotent : on peut + # relancer `docker compose up` sans risque. + migrate: + image: migrate/migrate:v4.18.1 + container_name: platform-migrate + restart: "no" + volumes: + - ./backend/migrations:/migrations:ro + command: + - -path=/migrations + - -database=postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}?sslmode=disable + - up + depends_on: + postgres: + condition: service_healthy + + backend: + build: + context: ./backend + dockerfile: Dockerfile + image: platform-backend:local + container_name: platform-backend + restart: unless-stopped + environment: + <<: *backend-env + volumes: + - uploads:/app/uploads + - verification_uploads:/app/verification-uploads + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + healthcheck: + # 127.0.0.1, not localhost: busybox wget tries ::1 first (see + # /etc/hosts in the image) and doesn't fall back to IPv4 when nginx/ + # the app only listens on 0.0.0.0, so "localhost" here reports + # unhealthy even though the service is actually fine. + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/health"] + interval: 10s + timeout: 5s + retries: 5 + + # Crée le compte admin initial. Non idempotent : à lancer une seule fois, + # via `docker compose --profile seed run --rm seed`. + seed: + image: platform-backend:local + profiles: ["seed"] + restart: "no" + entrypoint: ["/app/seed"] + environment: + <<: *backend-env + SEED_ADMIN_USERNAME: ${SEED_ADMIN_USERNAME:-admin} + SEED_ADMIN_PASSWORD: ${SEED_ADMIN_PASSWORD:?SEED_ADMIN_PASSWORD est requis pour le seed} + depends_on: + migrate: + condition: service_completed_successfully + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + image: platform-frontend:local + container_name: platform-frontend + restart: unless-stopped + ports: + - "${FRONTEND_PORT:-8081}:8080" + volumes: + # Remplace la config de production : ici nginx relaie /api et /uploads + # au service "backend" (voir frontend/nginx.compose.conf). + - ./frontend/nginx.compose.conf:/etc/nginx/conf.d/default.conf:ro + depends_on: + backend: + condition: service_healthy + healthcheck: + # 127.0.0.1, not localhost: busybox wget tries ::1 first and doesn't + # fall back to IPv4 when nginx only listens on 0.0.0.0 (see backend's + # healthcheck comment above for the full explanation). + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"] + interval: 10s + timeout: 5s + retries: 5 + volumes: postgres_data: redis_data: + uploads: + verification_uploads: diff --git a/frontend/nginx.compose.conf b/frontend/nginx.compose.conf new file mode 100644 index 0000000..0a44497 --- /dev/null +++ b/frontend/nginx.compose.conf @@ -0,0 +1,55 @@ +server { + listen 8080; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # Même limite que MEDIA_MAX_UPLOAD_MB (10 Mo par défaut, voir .env) avec + # une marge pour le multipart. + client_max_body_size 12m; + + # Liveness/readiness probe target -- doesn't touch the filesystem or + # fall through to the SPA fallback below. + location = /healthz { + access_log off; + return 200 "ok\n"; + add_header Content-Type text/plain; + } + + # Hashed build assets (Vite fingerprints these) can be cached forever. + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + # Config docker-compose UNIQUEMENT (voir docker-compose.yml, qui monte ce + # fichier à la place de nginx.conf) : en local il n'y a pas d'ingress, donc + # nginx relaie /api et /uploads au service "backend" (nom résolu par le + # DNS interne de Docker Compose), pour que le navigateur ne voie qu'une + # seule origine -- même principe que le proxy dev de vite.config.ts. + # L'image de production (nginx.conf) n'en a pas besoin : le routage y est + # fait par l'IngressRoute Traefik, directement vers le Service backend. + location /api/ { + proxy_pass http://backend:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location /uploads/ { + proxy_pass http://backend:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # BrowserRouter (see src/App.tsx) needs every unknown path to fall back + # to index.html so client-side routing can take over. + location / { + try_files $uri $uri/ /index.html; + add_header Cache-Control "no-cache"; + } +} diff --git a/frontend/src/api/themeSettings.ts b/frontend/src/api/themeSettings.ts new file mode 100644 index 0000000..03b2eec --- /dev/null +++ b/frontend/src/api/themeSettings.ts @@ -0,0 +1,23 @@ +import { apiFetch } from "./client"; + +export interface ThemeSettings { + toggle_enabled: boolean; + default_theme: "light" | "dark"; +} + +// Public : le storefront en a besoin pour savoir s'il doit afficher le +// bouton de bascule clair/sombre, et sinon quel thème forcer. +export function getThemeSettings(): Promise { + return apiFetch("/api/theme-settings"); +} + +export function getAdminThemeSettings(): Promise { + return apiFetch("/api/admin/theme-settings"); +} + +export function updateThemeSettings(settings: ThemeSettings): Promise { + return apiFetch("/api/admin/theme-settings", { + method: "PUT", + body: JSON.stringify(settings), + }); +} diff --git a/frontend/src/features/admin/AppearanceSettingsPage.tsx b/frontend/src/features/admin/AppearanceSettingsPage.tsx index 68b6258..95b8ccb 100644 --- a/frontend/src/features/admin/AppearanceSettingsPage.tsx +++ b/frontend/src/features/admin/AppearanceSettingsPage.tsx @@ -1,9 +1,12 @@ -import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from "react"; +import { useEffect, useRef, useState, type ChangeEvent, type FormEvent, type MouseEvent } from "react"; import { apiFetch, apiUpload } from "../../api/client"; import { HERO_PAGES, PRODUCT_COLUMNS, PRODUCT_LAYOUTS, PRODUCT_SCROLL_DIRECTIONS, type Media, type SiteSettings } from "../../api/types"; import { useI18n } from "../../i18n/LanguageContext"; import type { MessageKey } from "../../i18n/messages"; import { useToast } from "../../ui/ToastContext"; +import { useConfirm } from "../../ui/ConfirmContext"; +import { CloseIcon } from "../../ui/icons"; +import ColorPicker from "../../ui/ColorPicker"; import AccordionSection from "../../ui/Accordion"; const PRODUCT_LAYOUT_KEYS: Record<(typeof PRODUCT_LAYOUTS)[number], MessageKey> = { @@ -30,6 +33,7 @@ const HERO_PAGE_KEYS: Record<(typeof HERO_PAGES)[number], MessageKey> = { export default function AppearanceSettingsPage() { const { t } = useI18n(); const toast = useToast(); + const confirm = useConfirm(); const [settings, setSettings] = useState(null); const [mediaLibrary, setMediaLibrary] = useState([]); const [loading, setLoading] = useState(true); @@ -129,19 +133,37 @@ export default function AppearanceSettingsPage() { return (
-
- setSettings({ ...settings!, [key]: e.target.value })} - /> - {value} -
+ setSettings({ ...settings!, [key]: hex })} />
); } + // Deleting a media that's currently selected as logo/hero (here or on a + // category/product/contact link) is safe at the DB level -- every + // *_media_id column is ON DELETE SET NULL (see migrations 000025/000026, + // products/contact_links) -- so there's never a dangling reference. If + // it's selected in THIS form, clear the local selection too so the UI + // doesn't keep pointing at a media.id that no longer exists until reload. + async function handleDeleteMedia(m: Media, e: MouseEvent) { + e.stopPropagation(); // don't also trigger the picker's onClick (select) + if (!(await confirm({ message: t("admin.appearance.confirmDeleteImage"), danger: true }))) return; + try { + await apiFetch(`/api/admin/media/${m.id}`, { method: "DELETE" }); + setMediaLibrary((current) => current.filter((item) => item.id !== m.id)); + setSettings((current) => { + if (!current) return current; + return { + ...current, + logo_media_id: current.logo_media_id === m.id ? null : current.logo_media_id, + hero_media_id: current.hero_media_id === m.id ? null : current.hero_media_id, + }; + }); + toast.success(t("admin.appearance.imageDeleted")); + } catch { + toast.error(t("admin.appearance.deleteImageError")); + } + } + function imagePicker(target: "logo" | "hero", currentId: string | null, onSelect: (id: string | null) => void) { return (
@@ -169,12 +191,39 @@ export default function AppearanceSettingsPage() { key={m.id} onClick={() => onSelect(m.id)} style={{ + position: "relative", cursor: "pointer", border: currentId === m.id ? "2px solid var(--color-primary)" : "1px solid var(--color-border)", borderRadius: 6, padding: 4, }} > + {m.alt_text}
))} diff --git a/frontend/src/features/admin/ContactLinksPage.tsx b/frontend/src/features/admin/ContactLinksPage.tsx index 0b023e4..d03ff26 100644 --- a/frontend/src/features/admin/ContactLinksPage.tsx +++ b/frontend/src/features/admin/ContactLinksPage.tsx @@ -6,6 +6,7 @@ import { getSocialIcon, SocialIconGlyph, SOCIAL_ICONS } from "../../socialIcons" import { useI18n } from "../../i18n/LanguageContext"; import { useConfirm } from "../../ui/ConfirmContext"; import { useToast } from "../../ui/ToastContext"; +import ColorPicker from "../../ui/ColorPicker"; const emptyForm = { label: "", @@ -223,15 +224,7 @@ export default function ContactLinksPage() {
-
- setForm({ ...form, color: e.target.value })} - /> - {form.color} -
+ setForm({ ...form, color: hex })} />
diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index c5d0bc7..8410aa7 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -27,6 +27,8 @@ export const messages = { "common.active": { en: "active", fr: "actif", es: "activo", de: "aktiv" }, "common.inactive": { en: "inactive", fr: "inactif", es: "inactivo", de: "inaktiv" }, "common.none": { en: "None", fr: "Aucun", es: "Ninguno", de: "Keine" }, + "ui.colorPicker.title": { en: "Color picker", fr: "Sélecteur de couleur", es: "Selector de color", de: "Farbwähler" }, + "ui.colorPicker.hexLabel": { en: "Hex color", fr: "Couleur hexadécimale", es: "Color hexadecimal", de: "Hex-Farbe" }, "common.creating": { en: "Creating…", fr: "Création…", es: "Creando…", de: "Wird erstellt…" }, "common.uploading": { en: "Uploading…", fr: "Envoi…", es: "Subiendo…", de: "Wird hochgeladen…" }, "common.moveUp": { en: "Move up", fr: "Monter", es: "Subir", de: "Nach oben" }, @@ -142,6 +144,10 @@ export const messages = { "admin.appearance.pageAccount": { en: "Account", fr: "Compte", es: "Cuenta", de: "Konto" }, "admin.appearance.pageContact": { en: "Contact", fr: "Contact", es: "Contacto", de: "Kontakt" }, "admin.appearance.uploadImage": { en: "Upload image", fr: "Envoyer une image", es: "Subir imagen", de: "Bild hochladen" }, + "admin.appearance.deleteImage": { en: "Delete image", fr: "Supprimer l'image", es: "Eliminar imagen", de: "Bild löschen" }, + "admin.appearance.confirmDeleteImage": { en: "Delete this image? It will be removed everywhere it's used (logo, hero, products, categories, contact links).", fr: "Supprimer cette image ? Elle sera retirée partout où elle est utilisée (logo, bannière, produits, catégories, liens de contact).", es: "¿Eliminar esta imagen? Se quitará de todos los lugares donde se usa (logo, portada, productos, categorías, enlaces de contacto).", de: "Dieses Bild löschen? Es wird überall entfernt, wo es verwendet wird (Logo, Hero, Produkte, Kategorien, Kontaktlinks)." }, + "admin.appearance.imageDeleted": { en: "Image deleted.", fr: "Image supprimée.", es: "Imagen eliminada.", de: "Bild gelöscht." }, + "admin.appearance.deleteImageError": { en: "Failed to delete image.", fr: "Échec de la suppression de l'image.", es: "No se pudo eliminar la imagen.", de: "Bild konnte nicht gelöscht werden." }, "admin.appearance.imageUploadError": { en: "Failed to upload image.", fr: "Échec de l'envoi de l'image.", es: "No se pudo subir la imagen.", de: "Bild konnte nicht hochgeladen werden." }, // --- admin users --- diff --git a/frontend/src/index.css b/frontend/src/index.css index 4ea12e6..e006ed0 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -121,6 +121,7 @@ button { width: 100%; max-width: 360px; background: var(--color-surface); + color: var(--color-text); border: 1px solid var(--color-border); border-radius: var(--radius); padding: 2rem; @@ -345,8 +346,15 @@ tr:last-child td { border-bottom: none; } +/* Cards/panels are neutral chrome: always this app's own surface + text + tokens, regardless of the site's branded --sf-body-* colors. Letting + them inherit --sf-body-text (set in StorefrontLayout.tsx when the + admin's body_text_color differs from the DB defaults, e.g. a + dark-branded site forcing white body text) would make text invisible + against a panel that itself fell back to a different background. */ .panel { background: var(--color-surface); + color: var(--color-text); border: 1px solid var(--color-border); border-radius: var(--radius); padding: 1.25rem; @@ -484,8 +492,19 @@ tr:last-child td { .storefront-logo { height: 36px; - width: auto; + width: 36px; display: block; + border-radius: 50%; + /* object-fit:cover crops to fill the circle instead of squashing a + non-square logo into an ellipse. */ + object-fit: cover; + /* A visible ring regardless of the logo's own colors -- most logos (like + a dark neon badge) have hard square edges that read as a clipping + mistake sitting directly on a light header; the ring gives the circle + a deliberate, finished edge in both themes. --color-border already + adapts between light/dark (see :root / :root[data-theme="light"]). */ + border: 1.5px solid var(--color-border); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); } /* Fills every bit of vertical space left in the .storefront-shell flex @@ -1527,3 +1546,165 @@ tr:last-child td { max-height: 90vh; } } + +/* --- color picker (replaces the OS's native ) ------- */ + +.color-picker { + position: relative; + display: inline-flex; +} + +.color-picker-trigger { + display: inline-flex; + align-items: center; + gap: 0.5rem; + padding: 0.35rem 0.65rem; + border-radius: var(--radius); + border: 1px solid var(--color-border); + background: var(--color-surface-alt); + color: var(--color-text-muted); + font: inherit; + font-size: 0.85rem; + cursor: pointer; +} + +.color-picker-trigger:hover { + border-color: var(--color-primary); +} + +.color-picker-swatch { + width: 1.3rem; + height: 1.3rem; + border-radius: 50%; + border: 1px solid rgba(255, 255, 255, 0.25); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3); + flex-shrink: 0; +} + +.color-picker-swatch-lg { + width: 2.4rem; + height: 2.4rem; + border-radius: calc(var(--radius) - 2px); +} + +.color-picker-popover { + /* position:fixed + top/left set inline by ColorPicker.tsx (portaled to + document.body, positioned from the trigger's own rect). */ + z-index: 1000; + width: 220px; + padding: 0.85rem; + border-radius: var(--radius); + border: 1px solid var(--color-border); + background: var(--color-surface); + box-shadow: 0 16px 36px rgba(0, 0, 0, 0.45); +} + +.color-picker-square { + position: relative; + width: 100%; + height: 140px; + border-radius: calc(var(--radius) - 2px); + overflow: hidden; + cursor: crosshair; + touch-action: none; +} + +.color-picker-square-white { + position: absolute; + inset: 0; + background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); +} + +.color-picker-square-black { + position: absolute; + inset: 0; + background: linear-gradient(to top, #000, rgba(0, 0, 0, 0)); +} + +.color-picker-square-cursor { + position: absolute; + width: 14px; + height: 14px; + border-radius: 50%; + border: 2px solid #fff; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6), 0 1px 4px rgba(0, 0, 0, 0.5); + transform: translate(-50%, -50%); + pointer-events: none; +} + +.color-picker-hue { + position: relative; + height: 14px; + margin-top: 0.75rem; + border-radius: 999px; + cursor: pointer; + touch-action: none; + background: linear-gradient( + to right, + #ff0000 0%, + #ffff00 17%, + #00ff00 33%, + #00ffff 50%, + #0000ff 67%, + #ff00ff 83%, + #ff0000 100% + ); +} + +.color-picker-hue-thumb { + position: absolute; + top: 50%; + width: 18px; + height: 18px; + border-radius: 50%; + border: 2px solid #fff; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6), 0 1px 4px rgba(0, 0, 0, 0.5); + transform: translate(-50%, -50%); + pointer-events: none; +} + +.color-picker-hex-row { + display: flex; + align-items: center; + gap: 0.6rem; + margin-top: 0.85rem; +} + +.color-picker-hex-input { + flex: 1; + min-width: 0; + padding: 0.4rem 0.55rem; + border-radius: calc(var(--radius) - 2px); + border: 1px solid var(--color-border); + background: var(--color-bg); + color: var(--color-text); + font-family: ui-monospace, monospace; + font-size: 0.85rem; + text-transform: lowercase; +} + +.color-picker-hex-input:focus { + outline: none; + border-color: var(--color-primary); +} + +.color-picker-presets { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 0.4rem; + margin-top: 0.85rem; +} + +.color-picker-preset { + width: 100%; + aspect-ratio: 1; + border-radius: 50%; + border: 1px solid rgba(255, 255, 255, 0.2); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3); + cursor: pointer; + padding: 0; +} + +.color-picker-preset:hover { + transform: scale(1.15); +} diff --git a/frontend/src/theme/ThemeContext.tsx b/frontend/src/theme/ThemeContext.tsx index 42657cb..47e64de 100644 --- a/frontend/src/theme/ThemeContext.tsx +++ b/frontend/src/theme/ThemeContext.tsx @@ -13,6 +13,11 @@ function detectInitialTheme(): Theme { interface ThemeContextValue { theme: Theme; toggleTheme: () => void; + // Direct setter, alongside toggleTheme -- needed by StorefrontChrome to + // force a specific theme when the admin disables the client-facing + // light/dark toggle (see ldmod module / useThemeSettings), which + // toggleTheme's binary flip can't express on its own. + setTheme: (theme: Theme) => void; } const ThemeContext = createContext(undefined); @@ -29,7 +34,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) { setTheme((current) => (current === "dark" ? "light" : "dark")); } - return {children}; + return {children}; } export function useTheme(): ThemeContextValue { diff --git a/frontend/src/ui/ColorPicker.tsx b/frontend/src/ui/ColorPicker.tsx new file mode 100644 index 0000000..e117dbf --- /dev/null +++ b/frontend/src/ui/ColorPicker.tsx @@ -0,0 +1,278 @@ +import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; +import { createPortal } from "react-dom"; +import { useI18n } from "../i18n/LanguageContext"; + +// Replaces the OS's native dialog (ugly, inconsistent +// across platforms, and visually jarring against the admin's own design) +// with a custom HSL picker: a saturation/lightness square, a hue strip, a +// hex field for direct entry, and a preset palette matching the storefront +// accent used elsewhere. Pure CSS gradients + pointer events, no canvas and +// no new dependency. + +interface HSL { + h: number; // 0-360 + s: number; // 0-100 + l: number; // 0-100 +} + +function hexToHsl(hex: string): HSL { + const m = /^#?([0-9a-f]{6})$/i.exec(hex); + if (!m) return { h: 0, s: 0, l: 0 }; + const r = parseInt(m[1].slice(0, 2), 16) / 255; + const g = parseInt(m[1].slice(2, 4), 16) / 255; + const b = parseInt(m[1].slice(4, 6), 16) / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const l = (max + min) / 2; + if (max === min) return { h: 0, s: 0, l: l * 100 }; + const d = max - min; + const s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + let h: number; + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + default: + h = (r - g) / d + 4; + } + return { h: h * 60, s: s * 100, l: l * 100 }; +} + +function hslToHex({ h, s, l }: HSL): string { + const sN = s / 100; + const lN = l / 100; + const k = (n: number) => (n + h / 30) % 12; + const a = sN * Math.min(lN, 1 - lN); + const f = (n: number) => lN - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))); + const toHex = (n: number) => + Math.round(f(n) * 255) + .toString(16) + .padStart(2, "0"); + return `#${toHex(0)}${toHex(8)}${toHex(4)}`; +} + +// Curated preset palette -- includes the storefront's own default accent +// (--color-primary, #6d28d9) plus a spread of hues at a few lightness/ +// saturation steps, so picking a brand color is usually a single click +// rather than a drag. +const PRESETS = [ + "#6d28d9", + "#dc2626", + "#ea580c", + "#d97706", + "#ca8a04", + "#65a30d", + "#16a34a", + "#059669", + "#0891b2", + "#0284c7", + "#2563eb", + "#4f46e5", + "#9333ea", + "#c026d3", + "#db2777", + "#e11d48", + "#1c1a1f", + "#525058", + "#a3a3a3", + "#f4f4f6", + "#ffffff", +]; + +interface ColorPickerProps { + id?: string; + value: string; + onChange: (hex: string) => void; +} + +export default function ColorPicker({ id, value, onChange }: ColorPickerProps) { + const { t } = useI18n(); + const [open, setOpen] = useState(false); + const [hsl, setHsl] = useState(() => hexToHsl(value)); + const [hexInput, setHexInput] = useState(value); + const rootRef = useRef(null); + const triggerRef = useRef(null); + const popoverRef = useRef(null); + const squareRef = useRef(null); + const hueRef = useRef(null); + const draggingRef = useRef<"square" | "hue" | null>(null); + const [popoverPos, setPopoverPos] = useState({ top: 0, left: 0 }); + + // Re-sync from the parent's value when the popover (re)opens -- the admin + // may have changed it elsewhere (e.g. reset the form) while this was closed. + useEffect(() => { + if (open) { + setHsl(hexToHsl(value)); + setHexInput(value); + } + }, [open, value]); + + // Portaled to document.body (below) so the popover isn't clipped by an + // ancestor with overflow:hidden -- AccordionSection's collapsible panels + // need that overflow to clip their own rounded corners, which would + // otherwise cut this popover off a few pixels in. Position is computed + // from the trigger button's own rect since the portal breaks normal + // document-flow positioning. + useLayoutEffect(() => { + if (!open || !triggerRef.current) return; + const rect = triggerRef.current.getBoundingClientRect(); + const popoverWidth = 220; + const left = Math.min(rect.left, window.innerWidth - popoverWidth - 8); + setPopoverPos({ top: rect.bottom + 8, left: Math.max(8, left) }); + }, [open]); + + useEffect(() => { + if (!open) return; + function handleClickOutside(e: MouseEvent) { + const target = e.target as Node; + const insideTrigger = rootRef.current?.contains(target); + const insidePopover = popoverRef.current?.contains(target); + if (!insideTrigger && !insidePopover) setOpen(false); + } + function handleEscape(e: KeyboardEvent) { + if (e.key === "Escape") setOpen(false); + } + document.addEventListener("mousedown", handleClickOutside); + document.addEventListener("keydown", handleEscape); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + document.removeEventListener("keydown", handleEscape); + }; + }, [open]); + + function commit(next: HSL) { + setHsl(next); + const hex = hslToHex(next); + setHexInput(hex); + onChange(hex); + } + + function updateFromSquare(clientX: number, clientY: number) { + const rect = squareRef.current?.getBoundingClientRect(); + if (!rect) return; + const x = Math.min(Math.max(clientX - rect.left, 0), rect.width); + const y = Math.min(Math.max(clientY - rect.top, 0), rect.height); + // x = saturation (0 at left), y = lightness (100 at top, 0 at bottom, + // peaking at 50 in the middle -- standard HSL square convention). + const s = (x / rect.width) * 100; + const l = 100 - (y / rect.height) * 100; + commit({ ...hsl, s, l }); + } + + function updateFromHue(clientX: number) { + const rect = hueRef.current?.getBoundingClientRect(); + if (!rect) return; + const x = Math.min(Math.max(clientX - rect.left, 0), rect.width); + commit({ ...hsl, h: (x / rect.width) * 360 }); + } + + function handlePointerDown(target: "square" | "hue") { + return (e: ReactPointerEvent) => { + e.preventDefault(); + draggingRef.current = target; + (target === "square" ? updateFromSquare : updateFromHue)(e.clientX, e.clientY); + function handleMove(ev: PointerEvent) { + (target === "square" ? updateFromSquare : updateFromHue)(ev.clientX, ev.clientY); + } + function handleUp() { + draggingRef.current = null; + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + } + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + }; + } + + function handleHexSubmit(raw: string) { + setHexInput(raw); + const normalized = raw.startsWith("#") ? raw : `#${raw}`; + if (/^#[0-9a-f]{6}$/i.test(normalized)) { + setHsl(hexToHsl(normalized)); + onChange(normalized); + } + } + + const huePure = `hsl(${hsl.h}, 100%, 50%)`; + + return ( +
+ + + {open && + createPortal( +
+
+
+
+
+
+ +
+
+
+ +
+ + handleHexSubmit(e.target.value)} + spellCheck={false} + maxLength={7} + aria-label={t("ui.colorPicker.hexLabel")} + /> +
+ +
+ {PRESETS.map((hex) => ( +
+
, + document.body, + )} +
+ ); +} diff --git a/frontend/src/ui/icons.tsx b/frontend/src/ui/icons.tsx index 3824401..637f395 100644 --- a/frontend/src/ui/icons.tsx +++ b/frontend/src/ui/icons.tsx @@ -166,3 +166,11 @@ export function LanguageIcon(props: SVGProps) { ); } + +export function CloseIcon(props: SVGProps) { + return ( + + + + ); +}