chore: build
This commit is contained in:
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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<ThemeSettings> {
|
||||
return apiFetch<ThemeSettings>("/api/theme-settings");
|
||||
}
|
||||
|
||||
export function getAdminThemeSettings(): Promise<ThemeSettings> {
|
||||
return apiFetch<ThemeSettings>("/api/admin/theme-settings");
|
||||
}
|
||||
|
||||
export function updateThemeSettings(settings: ThemeSettings): Promise<ThemeSettings> {
|
||||
return apiFetch<ThemeSettings>("/api/admin/theme-settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(settings),
|
||||
});
|
||||
}
|
||||
@@ -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<SiteSettings | null>(null);
|
||||
const [mediaLibrary, setMediaLibrary] = useState<Media[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -129,19 +133,37 @@ export default function AppearanceSettingsPage() {
|
||||
return (
|
||||
<div className="field">
|
||||
<label htmlFor={key}>{label}</label>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
|
||||
<input
|
||||
id={key}
|
||||
type="color"
|
||||
value={value}
|
||||
onChange={(e) => setSettings({ ...settings!, [key]: e.target.value })}
|
||||
/>
|
||||
<code style={{ color: "var(--color-text-muted)", fontSize: "0.85rem" }}>{value}</code>
|
||||
</div>
|
||||
<ColorPicker id={key} value={value} onChange={(hex) => setSettings({ ...settings!, [key]: hex })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div>
|
||||
@@ -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,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => handleDeleteMedia(m, e)}
|
||||
aria-label={t("admin.appearance.deleteImage")}
|
||||
title={t("admin.appearance.deleteImage")}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: -6,
|
||||
right: -6,
|
||||
width: 20,
|
||||
height: 20,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: "50%",
|
||||
border: "1px solid var(--color-border)",
|
||||
background: "var(--color-danger)",
|
||||
color: "#fff",
|
||||
fontSize: "0.65rem",
|
||||
cursor: "pointer",
|
||||
padding: 0,
|
||||
zIndex: 1,
|
||||
}}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<img src={m.url} alt={m.alt_text} style={{ width: "100%", height: 52, objectFit: "cover", borderRadius: 4 }} />
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -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() {
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="link-color">{t("admin.contactLinks.color")}</label>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
|
||||
<input
|
||||
id="link-color"
|
||||
type="color"
|
||||
value={form.color}
|
||||
onChange={(e) => setForm({ ...form, color: e.target.value })}
|
||||
/>
|
||||
<code style={{ color: "var(--color-text-muted)", fontSize: "0.85rem" }}>{form.color}</code>
|
||||
</div>
|
||||
<ColorPicker id="link-color" value={form.color} onChange={(hex) => setForm({ ...form, color: hex })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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 ---
|
||||
|
||||
+182
-1
@@ -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 <input type="color">) ------- */
|
||||
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -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<ThemeContextValue | undefined>(undefined);
|
||||
@@ -29,7 +34,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
setTheme((current) => (current === "dark" ? "light" : "dark"));
|
||||
}
|
||||
|
||||
return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>;
|
||||
return <ThemeContext.Provider value={{ theme, toggleTheme, setTheme }}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
|
||||
@@ -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 <input type="color"> 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<HSL>(() => hexToHsl(value));
|
||||
const [hexInput, setHexInput] = useState(value);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const popoverRef = useRef<HTMLDivElement>(null);
|
||||
const squareRef = useRef<HTMLDivElement>(null);
|
||||
const hueRef = useRef<HTMLDivElement>(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 (
|
||||
<div className="color-picker" ref={rootRef}>
|
||||
<button
|
||||
type="button"
|
||||
id={id}
|
||||
ref={triggerRef}
|
||||
className="color-picker-trigger"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
>
|
||||
<span className="color-picker-swatch" style={{ background: value }} />
|
||||
<code>{value}</code>
|
||||
</button>
|
||||
|
||||
{open &&
|
||||
createPortal(
|
||||
<div
|
||||
className="color-picker-popover"
|
||||
ref={popoverRef}
|
||||
role="dialog"
|
||||
aria-label={t("ui.colorPicker.title")}
|
||||
style={{ position: "fixed", top: popoverPos.top, left: popoverPos.left }}
|
||||
>
|
||||
<div
|
||||
className="color-picker-square"
|
||||
ref={squareRef}
|
||||
style={{ background: huePure }}
|
||||
onPointerDown={handlePointerDown("square")}
|
||||
>
|
||||
<div className="color-picker-square-white" />
|
||||
<div className="color-picker-square-black" />
|
||||
<div
|
||||
className="color-picker-square-cursor"
|
||||
style={{ left: `${hsl.s}%`, top: `${100 - hsl.l}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="color-picker-hue" ref={hueRef} onPointerDown={handlePointerDown("hue")}>
|
||||
<div className="color-picker-hue-thumb" style={{ left: `${(hsl.h / 360) * 100}%`, background: huePure }} />
|
||||
</div>
|
||||
|
||||
<div className="color-picker-hex-row">
|
||||
<span className="color-picker-swatch color-picker-swatch-lg" style={{ background: value }} />
|
||||
<input
|
||||
type="text"
|
||||
className="color-picker-hex-input"
|
||||
value={hexInput}
|
||||
onChange={(e) => handleHexSubmit(e.target.value)}
|
||||
spellCheck={false}
|
||||
maxLength={7}
|
||||
aria-label={t("ui.colorPicker.hexLabel")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="color-picker-presets">
|
||||
{PRESETS.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
className="color-picker-preset"
|
||||
style={{ background: hex }}
|
||||
aria-label={hex}
|
||||
title={hex}
|
||||
onClick={() => {
|
||||
setHsl(hexToHsl(hex));
|
||||
setHexInput(hex);
|
||||
onChange(hex);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -166,3 +166,11 @@ export function LanguageIcon(props: SVGProps<SVGSVGElement>) {
|
||||
</IconBase>
|
||||
);
|
||||
}
|
||||
|
||||
export function CloseIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<IconBase {...props}>
|
||||
<path d="M5 5l14 14M19 5L5 19" />
|
||||
</IconBase>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user