From 4d1a5b9629e8747758770fba5c2c2d49979878ee Mon Sep 17 00:00:00 2001 From: Xor290 Date: Fri, 23 Oct 2026 16:51:57 +0200 Subject: [PATCH] chore: build --- backend/cmd/api/main.go | 9 + backend/internal/modules/ldmod/handler.go | 64 ++++ backend/internal/modules/ldmod/model.go | 17 ++ backend/internal/modules/ldmod/repository.go | 54 ++++ backend/internal/modules/ldmod/routes.go | 16 + backend/internal/modules/ldmod/service.go | 31 ++ .../migrations/000035_create_ld_mod.down.sql | 1 + .../migrations/000035_create_ld_mod.up.sql | 11 + backend/test/ldmod/ldmod_test.go | 151 ++++++++++ .../8d34481d-5e41-4f43-bb5a-68983fc204eb.png | Bin 4116 -> 0 bytes .../fb2c2ebf-de0b-4b7e-b423-dd9946292e47.png | Bin 4116 -> 0 bytes docker-compose.yml | 119 +++++++- frontend/nginx.compose.conf | 55 ++++ frontend/src/api/themeSettings.ts | 23 ++ .../features/admin/AppearanceSettingsPage.tsx | 69 ++++- .../src/features/admin/ContactLinksPage.tsx | 11 +- frontend/src/i18n/messages.ts | 6 + frontend/src/index.css | 183 +++++++++++- frontend/src/theme/ThemeContext.tsx | 7 +- frontend/src/ui/ColorPicker.tsx | 278 ++++++++++++++++++ frontend/src/ui/icons.tsx | 8 + 21 files changed, 1090 insertions(+), 23 deletions(-) create mode 100644 backend/internal/modules/ldmod/handler.go create mode 100644 backend/internal/modules/ldmod/model.go create mode 100644 backend/internal/modules/ldmod/repository.go create mode 100644 backend/internal/modules/ldmod/routes.go create mode 100644 backend/internal/modules/ldmod/service.go create mode 100644 backend/migrations/000035_create_ld_mod.down.sql create mode 100644 backend/migrations/000035_create_ld_mod.up.sql create mode 100644 backend/test/ldmod/ldmod_test.go delete mode 100644 backend/uploads/8d34481d-5e41-4f43-bb5a-68983fc204eb.png delete mode 100644 backend/uploads/fb2c2ebf-de0b-4b7e-b423-dd9946292e47.png create mode 100644 frontend/nginx.compose.conf create mode 100644 frontend/src/api/themeSettings.ts create mode 100644 frontend/src/ui/ColorPicker.tsx 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 dccc4d19b89b79ed83291420fe2fc4e9c8e5a7b4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4116 zcmV+v5bN)WP)001Tk1^@s6Lne^u00004b3#c}2nYxW zdI9 zVM$U*SOOSR5|*Tg5SG$Yn&|(Npa{`8h<+M=12Ex9@7z`L{OEU%x6ud~| zVG9I|J@)8H^WN(+k}{f_ddNgy0KN>x?@7<;lKe<*sOKNz{gv2_C~mjZJ{JTC{PM~>W+{f@Ht zutyxwH!ad>hN8;^-Vl*<0bfz|ICbRlKsa*Lp6Gj&y^E$gU?3Db+6+dYG7MP*oK~cN zC-6a$=sqY9m~GLS&Fp`ay^m%%pqSGlC;3Cs)rzh__-av|1@cR;cxL##gL4&LE>tM; zXL#g(=<+tfhEeuX8u;?Ny#CO(g#woY2g%UNEO3Y6k!uDv#e1znY1{ncOv8F;x0C8z ze{kEPOfUaZza69O&B(|iC4{>ICZC^&$`63{l3GXMZn62P)tA`d+I~{USaXc|B5-iN zWUJ-#h1l@wwwi4jr8$J>?&nkQbdTB-#E|}hLGvB@R)4yux+~rVS3d&II=t0P4}2fp z_KzTcQBtcQ%T=ALGQHhzR@C$H`hE>Y&JvMszz^(aW(Uu=U`cHsBZnD`-Y5oBE6F%Y z+EDGo!;|UF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dzr!(v{Ce-au`}lU zFgxg7KyJ6zPHw8*D#AvEmkmQ6aBE+{Kdtj1RecyVsPNlb^3O!LPhrS4Q8j8(p6@A-HXS#RIra(CQbCe<1 zK^>Jt$IgsQ8WOhJcbiSW`B15j0mcmPEXkg&8Ths@)VajKJ|E=kir4IQ$&ZlK~V~XFPKJ z7diEg@_$2B4hXwOr=<+d`uIfAo4gpm*_n!$C3B8MJ_>)nz&YfX0D|0;me%i*T$!#_ z-za+@RXZT$)@NckcTpau$O5ZW^=ZSyYOi6x-M{g*lBCiFo|YNODfXa!h#-f99?#H7 z|8|6{tYqRB?15afQT{Zk$pLe8dCl)H|IUc+%N zt1I_#l)aid957GY{FZrhC`a6N?(<{{i(oV6l?vkq{2Y zImllF2MUDA?PSN1yP))msD6qV8&#dv4)Sugcig%?`Ja|X**oxsVo?Kr1Mt5q-}ZmO S_Nx{E0000 { + 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 ( + + + + ); +}