diff --git a/apps/api/features/preferences.feature b/apps/api/features/preferences.feature new file mode 100644 index 0000000..17cd1b9 --- /dev/null +++ b/apps/api/features/preferences.feature @@ -0,0 +1,23 @@ +Feature: User preferences (theme) + As a signed-in user + I want to choose a light, dark, or system theme + So that the app matches how I like to read it + + Scenario: A visitor without a session cannot read preferences + When I send a GET request to "/preferences" + Then the response status should be 401 + And the response error code should be "NOT_AUTHENTICATED" + + Scenario: A signed-in user with no preferences yet defaults to SYSTEM + Given a profile already exists with email "alice@example.com" and password "correct-horse-battery-staple" + And I log in with email "alice@example.com" and password "correct-horse-battery-staple" + When I request my preferences + Then the response status should be 200 + And my theme preference should be "SYSTEM" + + Scenario: A signed-in user sets their theme preference + Given a profile already exists with email "alice@example.com" and password "correct-horse-battery-staple" + And I log in with email "alice@example.com" and password "correct-horse-battery-staple" + When I set my theme preference to "DARK" + Then the response status should be 200 + And my theme preference should be "DARK" diff --git a/apps/api/features/step-definitions/preferences.steps.ts b/apps/api/features/step-definitions/preferences.steps.ts new file mode 100644 index 0000000..3062682 --- /dev/null +++ b/apps/api/features/step-definitions/preferences.steps.ts @@ -0,0 +1,15 @@ +import assert from "node:assert/strict"; +import { Then, When } from "@cucumber/cucumber"; +import type { CustomWorld } from "../support/world.js"; + +When("I request my preferences", async function (this: CustomWorld) { + this.response = await this.agent.get("/preferences"); +}); + +When("I set my theme preference to {string}", async function (this: CustomWorld, theme: string) { + this.response = await this.agent.patch("/preferences").send({ theme }); +}); + +Then("my theme preference should be {string}", function (this: CustomWorld, theme: string) { + assert.equal(this.response.body.theme, theme); +}); diff --git a/apps/api/prisma/migrations/20260817120000_add_user_preference/migration.sql b/apps/api/prisma/migrations/20260817120000_add_user_preference/migration.sql new file mode 100644 index 0000000..f888721 --- /dev/null +++ b/apps/api/prisma/migrations/20260817120000_add_user_preference/migration.sql @@ -0,0 +1,13 @@ +-- CreateEnum +CREATE TYPE "ThemePreference" AS ENUM ('LIGHT', 'DARK', 'SYSTEM'); + +-- CreateTable +CREATE TABLE "user_preference" ( + "user_profile_id" INTEGER NOT NULL, + "theme" "ThemePreference" NOT NULL DEFAULT 'SYSTEM', + + CONSTRAINT "user_preference_pkey" PRIMARY KEY ("user_profile_id") +); + +-- AddForeignKey +ALTER TABLE "user_preference" ADD CONSTRAINT "user_preference_user_profile_id_fkey" FOREIGN KEY ("user_profile_id") REFERENCES "user_profiles"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 769943d..f398ab4 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -98,10 +98,36 @@ model UserProfile { /// a time — but Prisma models the admin side of a one-to-many FK as a /// list regardless of that real-world cardinality. administeredHouses House[] @relation("HouseAdmin") + preferences UserPreference? @@map("user_profiles") } +/// Not in the original spec doc — personalization settings (theme for now, +/// meant to grow), one row per profile, created on demand (see +/// `preferences.service.ts`) rather than at signup — same "absent means the +/// default" philosophy as `dietId`/allergies. +enum ThemePreference { + LIGHT + DARK + /// Follow the OS/browser preference — the default. Not "no row yet" (that + /// case is handled in the service layer) but an explicit choice to track + /// the system, distinguishable from a user who hasn't decided yet if this + /// model ever needs that distinction. + SYSTEM +} + +model UserPreference { + /// Both the primary key and the FK — a strict 1-1 with UserProfile, no + /// separate auto-incrementing id (a profile has at most one preferences row). + userProfileId Int @id @map("user_profile_id") + theme ThemePreference @default(SYSTEM) + + userProfile UserProfile @relation(fields: [userProfileId], references: [id], onDelete: Cascade) + + @@map("user_preference") +} + /// Explicit join table for the user_profiles <-> allergy association /// (documented in the spec as a plain many-to-many, no extra fields). model UserProfileAllergy { diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index c4f8727..b86dc5d 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -6,6 +6,7 @@ import { env } from "./config/env.js"; import { authRouter } from "./modules/auth/auth.routes.js"; import { houseRouter } from "./modules/house/house.routes.js"; import { planningRouter } from "./modules/planning/planning.routes.js"; +import { preferencesRouter } from "./modules/preferences/preferences.routes.js"; import { profileRouter } from "./modules/profile/profile.routes.js"; import { referenceRouter } from "./modules/reference/reference.routes.js"; @@ -28,6 +29,7 @@ export function createServer(): ExpressServer { server.mountRouter("/auth", authRouter); server.mountRouter("/house", houseRouter); server.mountRouter("/planning", planningRouter); + server.mountRouter("/preferences", preferencesRouter); server.mountRouter("/profile", profileRouter); server.mountRouter("/reference", referenceRouter); diff --git a/apps/api/src/modules/preferences/preferences.routes.ts b/apps/api/src/modules/preferences/preferences.routes.ts new file mode 100644 index 0000000..67b0cc9 --- /dev/null +++ b/apps/api/src/modules/preferences/preferences.routes.ts @@ -0,0 +1,27 @@ +import { wrapAsyncHandler } from "@batch-cooking/express-tools"; +import { updatePreferencesSchema } from "@batch-cooking/shared"; +import { Router } from "express"; +import { type AuthLocals, requireAuth } from "../../middlewares/require-auth.js"; +import { getPreferences, updatePreferences } from "./preferences.service.js"; + +/** Router mounted at `/preferences` in app.ts. Every route requires a session — this is the authenticated user's own preferences. */ +export const preferencesRouter = Router(); + +preferencesRouter.get( + "/", + requireAuth, + wrapAsyncHandler(async (_req, res) => { + const preferences = await getPreferences(res.locals.userProfile.id); + res.status(200).json(preferences); + }), +); + +preferencesRouter.patch( + "/", + requireAuth, + wrapAsyncHandler(async (req, res) => { + const input = updatePreferencesSchema.parse(req.body); + const preferences = await updatePreferences(res.locals.userProfile.id, input.theme); + res.status(200).json(preferences); + }), +); diff --git a/apps/api/src/modules/preferences/preferences.service.ts b/apps/api/src/modules/preferences/preferences.service.ts new file mode 100644 index 0000000..6e6d2a0 --- /dev/null +++ b/apps/api/src/modules/preferences/preferences.service.ts @@ -0,0 +1,31 @@ +import type { PreferencesView, ThemePreference } from "@batch-cooking/shared"; +import { prisma } from "../../db/prisma.js"; + +/** + * A profile's personalization preferences. `SYSTEM` (the schema default) + * is returned both when a row already says so *and* when there's no row + * yet at all — same "absent means the default" philosophy as + * `dietId`/allergies elsewhere in `profile.service.ts`, no row is created + * just to read it. + */ +export async function getPreferences(userProfileId: number): Promise { + const preferences = await prisma.userPreference.findUnique({ where: { userProfileId } }); + return { theme: preferences?.theme ?? "SYSTEM" }; +} + +/** + * Sets a profile's theme preference, creating its preferences row on first + * write (an `upsert` rather than requiring a separate "create" step — a + * profile never needs to explicitly initialize this row before using it). + */ +export async function updatePreferences( + userProfileId: number, + theme: ThemePreference, +): Promise { + const preferences = await prisma.userPreference.upsert({ + where: { userProfileId }, + create: { userProfileId, theme }, + update: { theme }, + }); + return { theme: preferences.theme }; +} diff --git a/apps/api/test-support/reset-db.ts b/apps/api/test-support/reset-db.ts index 9b5b54e..c758f49 100644 --- a/apps/api/test-support/reset-db.ts +++ b/apps/api/test-support/reset-db.ts @@ -10,7 +10,7 @@ import { seedReferenceData } from "../src/db/reference-seed-data.js"; export async function resetDatabase() { await prisma.$executeRawUnsafe(` TRUNCATE TABLE - "user_profile_allergy", "allergy", "category", + "user_profile_allergy", "user_preference", "allergy", "category", "planning_item", "planning", "recipe_ingredient", "step", "tech_step_mapping", "tech_step", "recipe", "ingredients", "sources", diff --git a/apps/api/test/preferences.test.ts b/apps/api/test/preferences.test.ts new file mode 100644 index 0000000..959da81 --- /dev/null +++ b/apps/api/test/preferences.test.ts @@ -0,0 +1,98 @@ +import { ErrorCode, type SignupInput } from "@batch-cooking/shared"; +import { faker } from "@faker-js/faker"; +import { expect } from "chai"; +import request from "supertest"; +import { createApp } from "../src/app.js"; +import { prisma } from "../src/db/prisma.js"; +import { resetDatabase } from "../test-support/reset-db.js"; + +function buildSignupPayload(): SignupInput { + const firstName = faker.person.firstName(); + const lastName = faker.person.lastName(); + return { + firstName, + lastName, + email: faker.internet.email({ firstName, lastName }).toLowerCase(), + password: faker.internet.password({ length: 16 }), + }; +} + +describe("Preferences", () => { + const app = createApp(); + + beforeEach(async () => { + await resetDatabase(); + }); + + after(async () => { + await prisma.$disconnect(); + }); + + describe("GET /preferences", () => { + it("rejects requests without a session cookie with 401 NOT_AUTHENTICATED", async () => { + const res = await request(app).get("/preferences"); + + expect(res.status).to.equal(401); + expect(res.body.code).to.equal(ErrorCode.NOT_AUTHENTICATED); + }); + + it("defaults to SYSTEM when the profile has no preferences row yet", async () => { + const agent = request.agent(app); + await agent.post("/auth/signup").send(buildSignupPayload()); + + const res = await agent.get("/preferences"); + + expect(res.status).to.equal(200); + expect(res.body).to.deep.equal({ theme: "SYSTEM" }); + }); + }); + + describe("PATCH /preferences", () => { + it("rejects requests without a session cookie with 401 NOT_AUTHENTICATED", async () => { + const res = await request(app).patch("/preferences").send({ theme: "DARK" }); + + expect(res.status).to.equal(401); + expect(res.body.code).to.equal(ErrorCode.NOT_AUTHENTICATED); + }); + + it("rejects an unknown theme with 400 VALIDATION_ERROR", async () => { + const agent = request.agent(app); + await agent.post("/auth/signup").send(buildSignupPayload()); + + const res = await agent.patch("/preferences").send({ theme: "PURPLE" }); + + expect(res.status).to.equal(400); + expect(res.body.code).to.equal(ErrorCode.VALIDATION_ERROR); + }); + + it("creates the preferences row on first write, and reuses it on later reads/writes", async () => { + const agent = request.agent(app); + await agent.post("/auth/signup").send(buildSignupPayload()); + + const patchRes = await agent.patch("/preferences").send({ theme: "DARK" }); + expect(patchRes.status).to.equal(200); + expect(patchRes.body).to.deep.equal({ theme: "DARK" }); + + const getRes = await agent.get("/preferences"); + expect(getRes.body).to.deep.equal({ theme: "DARK" }); + + const secondPatchRes = await agent.patch("/preferences").send({ theme: "LIGHT" }); + expect(secondPatchRes.body).to.deep.equal({ theme: "LIGHT" }); + + const secondGetRes = await agent.get("/preferences"); + expect(secondGetRes.body).to.deep.equal({ theme: "LIGHT" }); + }); + + it("scopes preferences to the caller's own profile", async () => { + const aliceAgent = request.agent(app); + await aliceAgent.post("/auth/signup").send(buildSignupPayload()); + await aliceAgent.patch("/preferences").send({ theme: "DARK" }); + + const bobAgent = request.agent(app); + await bobAgent.post("/auth/signup").send(buildSignupPayload()); + + const res = await bobAgent.get("/preferences"); + expect(res.body).to.deep.equal({ theme: "SYSTEM" }); + }); + }); +}); diff --git a/apps/web/cypress/e2e/auth.cy.ts b/apps/web/cypress/e2e/auth.cy.ts index 9be4fde..e0baebd 100644 --- a/apps/web/cypress/e2e/auth.cy.ts +++ b/apps/web/cypress/e2e/auth.cy.ts @@ -76,7 +76,7 @@ describe("Signup", () => { describe("Login", () => { it("logs in and lands on the home page", () => { cy.intercept("GET", "**/auth/me", { statusCode: 401 }); - cy.intercept("GET", "**/planning/current", { statusCode: 200, body: null }); + cy.intercept("GET", /\/planning\?/, { statusCode: 200, body: null }); cy.intercept("POST", "**/auth/login", { statusCode: 200, body: { @@ -130,7 +130,7 @@ describe("Already authenticated", () => { dietId: null, }, }); - cy.intercept("GET", "**/planning/current", { statusCode: 200, body: null }); + cy.intercept("GET", /\/planning\?/, { statusCode: 200, body: null }); cy.visit("/login"); cy.url().should("not.include", "/login"); @@ -150,7 +150,7 @@ describe("Already authenticated", () => { dietId: null, }, }); - cy.intercept("GET", "**/planning/current", { statusCode: 200, body: null }); + cy.intercept("GET", /\/planning\?/, { statusCode: 200, body: null }); cy.intercept("POST", "**/auth/logout", { statusCode: 204 }).as("logout"); cy.visit("/"); diff --git a/apps/web/cypress/e2e/onboarding.cy.ts b/apps/web/cypress/e2e/onboarding.cy.ts index 8906290..c8cf368 100644 --- a/apps/web/cypress/e2e/onboarding.cy.ts +++ b/apps/web/cypress/e2e/onboarding.cy.ts @@ -16,7 +16,7 @@ const signupResponse = { function signupAndReachOnboarding() { cy.intercept("GET", "**/auth/me", { statusCode: 401 }); cy.intercept("POST", "**/auth/signup", { statusCode: 201, body: signupResponse }).as("signup"); - cy.intercept("GET", "**/planning/current", { statusCode: 200, body: null }); + cy.intercept("GET", /\/planning\?/, { statusCode: 200, body: null }); cy.visit("/signup"); cy.get("#firstName").type("Alice"); diff --git a/apps/web/cypress/e2e/sidebar.cy.ts b/apps/web/cypress/e2e/sidebar.cy.ts index 07295d2..2d69946 100644 --- a/apps/web/cypress/e2e/sidebar.cy.ts +++ b/apps/web/cypress/e2e/sidebar.cy.ts @@ -13,7 +13,9 @@ const authenticatedProfile = { describe("Sidebar — settings menu and account menu", () => { beforeEach(() => { cy.intercept("GET", "**/auth/me", { statusCode: 200, body: authenticatedProfile }); - cy.intercept("GET", "**/planning/current", { statusCode: 200, body: null }); + // Not "**/planning*" — that glob also matches the Vite dev request for + // planning-page.scss (see planning-page.cy.ts for the same gotcha). + cy.intercept("GET", /\/planning\?/, { statusCode: 200, body: null }); }); it("no longer lists Foyer in the main nav", () => { @@ -21,15 +23,24 @@ describe("Sidebar — settings menu and account menu", () => { cy.get(".app-sidebar__nav a").should("not.contain", "Foyer"); }); - it("reveals the three settings pages behind the Paramètres toggle", () => { + it("reveals the four settings pages behind the Paramètres toggle", () => { cy.visit("/"); cy.contains("a", "Compte").should("not.exist"); cy.contains("button", "Paramètres").click(); cy.contains("a", "Compte").should("have.attr", "href", "/parametres/compte"); - cy.contains("a", "Préférences").should("have.attr", "href", "/parametres/preferences"); + cy.contains("a", "Préférences alimentaires").should( + "have.attr", + "href", + "/parametres/preferences", + ); cy.contains("a", "Foyer").should("have.attr", "href", "/parametres/foyer"); + cy.contains("a", "Préférences utilisateur").should( + "have.attr", + "href", + "/parametres/preferences-utilisateur", + ); }); it("opens the account menu from the greeting and links to Mon compte", () => { @@ -47,4 +58,26 @@ describe("Sidebar — settings menu and account menu", () => { cy.visit("/foyer"); cy.url().should("include", "/parametres/foyer"); }); + + it("collapses to an icon-only rail and back, persisting the choice across reloads", () => { + cy.visit("/"); + + cy.get(".app-sidebar").should("not.have.class", "collapsed"); + cy.contains("nav a", "Planning").should("be.visible"); + + cy.get(".app-sidebar__collapse-toggle").click(); + cy.get(".app-sidebar").should("have.class", "collapsed"); + // The label text hides (not removed from the DOM — still there for the + // `title` tooltip/accessibility), while the link itself stays visible, + // icon-only. + cy.contains("span.label", "Planning").should("exist").and("not.be.visible"); + cy.get("nav a[title='Planning']").should("be.visible"); + + cy.reload(); + cy.get(".app-sidebar").should("have.class", "collapsed"); + + cy.get(".app-sidebar__collapse-toggle").click(); + cy.get(".app-sidebar").should("not.have.class", "collapsed"); + cy.contains("nav a", "Planning").should("be.visible"); + }); }); diff --git a/apps/web/cypress/e2e/user-preferences.cy.ts b/apps/web/cypress/e2e/user-preferences.cy.ts new file mode 100644 index 0000000..0c09b1c --- /dev/null +++ b/apps/web/cypress/e2e/user-preferences.cy.ts @@ -0,0 +1,54 @@ +// Mocks the API via cy.intercept — see auth.cy.ts for the rationale. + +const authenticatedProfile = { + id: 1, + firstName: "Alice", + lastName: "Martin", + email: "alice@example.com", + tokenVersion: 0, + houseId: null, + dietId: null, +}; + +describe("User preferences (/parametres/preferences-utilisateur)", () => { + beforeEach(() => { + cy.intercept("GET", "**/auth/me", { statusCode: 200, body: authenticatedProfile }); + }); + + it("shows SYSTEM selected by default", () => { + cy.intercept("GET", "**/preferences", { statusCode: 200, body: { theme: "SYSTEM" } }); + + cy.visit("/parametres/preferences-utilisateur"); + + cy.contains("label", "Système").find("input[type=radio]").should("be.checked"); + cy.contains("label", "Clair").find("input[type=radio]").should("not.be.checked"); + cy.contains("label", "Sombre").find("input[type=radio]").should("not.be.checked"); + // SYSTEM never sets an override — the OS/browser preference decides. + cy.get("html").should("not.have.attr", "data-theme"); + }); + + it("shows the previously saved theme selected, and applies it to the document", () => { + cy.intercept("GET", "**/preferences", { statusCode: 200, body: { theme: "DARK" } }); + + cy.visit("/parametres/preferences-utilisateur"); + + cy.contains("label", "Sombre").find("input[type=radio]").should("be.checked"); + cy.get("html").should("have.attr", "data-theme", "dark"); + }); + + it("switching theme autosaves and applies immediately, no explicit save button", () => { + cy.intercept("GET", "**/preferences", { statusCode: 200, body: { theme: "SYSTEM" } }); + cy.intercept("PATCH", "**/preferences", { statusCode: 200, body: { theme: "LIGHT" } }).as( + "updatePreferences", + ); + + cy.visit("/parametres/preferences-utilisateur"); + cy.contains("button", "Enregistrer").should("not.exist"); + + cy.contains("label", "Clair").click(); + + cy.wait("@updatePreferences").its("request.body").should("deep.equal", { theme: "LIGHT" }); + cy.contains("Enregistré ✓").should("be.visible"); + cy.get("html").should("have.attr", "data-theme", "light"); + }); +}); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 4abe841..eda674e 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -13,6 +13,7 @@ import { OnboardingHouseholdPage } from "./pages/onboarding/OnboardingHouseholdP import { AccountSettingsPage } from "./pages/settings/AccountSettingsPage"; import { HouseholdSettingsPage } from "./pages/settings/HouseholdSettingsPage"; import { PreferencesPage } from "./pages/settings/PreferencesPage"; +import { UserPreferencesPage } from "./pages/settings/UserPreferencesPage"; /** * Top-level route table. Every authenticated section is nested under one @@ -22,12 +23,12 @@ import { PreferencesPage } from "./pages/settings/PreferencesPage"; * {@link RedirectIfAuthenticated}). Anything else falls back to `/`, which * itself redirects to `/login` if needed. * - * `/parametres/*` (compte/préférences/foyer) are the settings pages, - * reachable from the sidebar's bottom "Paramètres" menu and the account - * menu (see `AppLayout`) — nested under `AppLayout` like every other - * authenticated section. `/foyer` is the old, pre-split combined page's - * path; it now just redirects to `/parametres/foyer` so an existing - * bookmark/link keeps working. + * `/parametres/*` (compte/préférences alimentaires/foyer/préférences + * utilisateur) are the settings pages, reachable from the sidebar's bottom + * "Paramètres" menu and the account menu (see `AppLayout`) — nested under + * `AppLayout` like every other authenticated section. `/foyer` is the old, + * pre-split combined page's path; it now just redirects to + * `/parametres/foyer` so an existing bookmark/link keeps working. * * `/onboarding/*` (regime/foyer/allergens, in that order) is also * `RequireAuth`-gated — reached right after signup, once a session already @@ -51,6 +52,7 @@ export function App() { } /> } /> } /> + } /> } /> { + return this.request("/preferences"); + } + + /** Sets the current user's theme preference. */ + public updatePreferences(theme: ThemePreference): Promise { + return this.request("/preferences", { method: "PATCH", body: JSON.stringify({ theme }) }); + } } /** Single shared instance — this client is stateless, no need for one per caller. */ diff --git a/apps/web/src/features/theme/ThemeContext.tsx b/apps/web/src/features/theme/ThemeContext.tsx new file mode 100644 index 0000000..f8c1021 --- /dev/null +++ b/apps/web/src/features/theme/ThemeContext.tsx @@ -0,0 +1,89 @@ +import type { ThemePreference } from "@batch-cooking/shared"; +import { type ReactNode, createContext, useCallback, useContext, useEffect, useState } from "react"; +import { apiClient } from "../../api/client"; +import { useAuth } from "../auth/AuthContext"; + +/** Shape of the theme state/actions exposed via {@link useTheme}. */ +interface ThemeContextValue { + /** The signed-in user's theme preference — `"SYSTEM"` (the default) for a logged-out visitor too, nothing to load a preference for. */ + theme: ThemePreference; + /** Persists `theme` and applies it immediately. Throws `ApiError` on failure. */ + setTheme: (theme: ThemePreference) => Promise; +} + +/** React context carrying {@link ThemeContextValue} — always accessed through {@link useTheme}, never directly. */ +const ThemeContext = createContext(null); + +/** + * Applies `theme` to the document. `SYSTEM` *removes* the override rather + * than setting a literal `"system"` value `_theme.scss` wouldn't recognize + * — with no `data-theme` attribute at all, its `prefers-color-scheme` + * media query decides instead, exactly the "system" behavior. + */ +function applyTheme(theme: ThemePreference) { + if (theme === "SYSTEM") { + delete document.documentElement.dataset.theme; + } else { + document.documentElement.dataset.theme = theme.toLowerCase(); + } +} + +/** + * Provides the signed-in user's theme preference and keeps the document in + * sync with it. Must be nested inside `AuthProvider` (reads `useAuth()`'s + * `user` to know when a profile is available to load a preference for) — + * see `main.tsx`. + * + * Keyed on `user?.id` rather than `user` itself: `AuthContext`'s `user` + * object is a fresh reference every time it refreshes (e.g. after an + * unrelated `refreshUser()` call elsewhere), which shouldn't re-trigger a + * preferences fetch — only actually signing in/out or switching accounts + * should. + */ +export function ThemeProvider({ children }: { children: ReactNode }) { + const { user } = useAuth(); + const [theme, setThemeState] = useState("SYSTEM"); + + // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the id on purpose, see the doc comment above. + useEffect(() => { + if (!user) { + setThemeState("SYSTEM"); + applyTheme("SYSTEM"); + return; + } + + let cancelled = false; + apiClient + .getPreferences() + .then((preferences) => { + if (cancelled) return; + setThemeState(preferences.theme); + applyTheme(preferences.theme); + }) + // Failing to load a preference (e.g. a network hiccup) shouldn't break + // the rest of the app — worst case the theme just stays at its + // current/default value, same "not fatal" spirit as AuthContext's own + // `me()` call on mount. + .catch(() => {}); + return () => { + cancelled = true; + }; + }, [user?.id]); + + const setTheme = useCallback(async (newTheme: ThemePreference) => { + await apiClient.updatePreferences(newTheme); + setThemeState(newTheme); + applyTheme(newTheme); + }, []); + + return {children}; +} + +/** Reads the current theme state/actions. Must be called from within a {@link ThemeProvider}. */ +export function useTheme(): ThemeContextValue { + const ctx = useContext(ThemeContext); + if (!ctx) { + throw new Error("useTheme must be used within a ThemeProvider"); + } + return ctx; +} diff --git a/apps/web/src/layouts/AppLayout.scss b/apps/web/src/layouts/AppLayout.scss index f8ffa0c..6cb886f 100644 --- a/apps/web/src/layouts/AppLayout.scss +++ b/apps/web/src/layouts/AppLayout.scss @@ -15,7 +15,9 @@ // Fixed-width nav rail. Its own surface (not the page background), same // elevation language as a card, so it reads as a distinct, permanent piece -// of chrome rather than part of the scrolling content. +// of chrome rather than part of the scrolling content. `width` transitions +// so collapsing/expanding (see `.collapsed` below) reads as a deliberate +// motion rather than an abrupt layout jump. .app-sidebar { display: flex; flex-direction: column; @@ -24,13 +26,55 @@ padding: var(--space-lg) var(--space-md); background: var(--color-surface); border-right: 1px solid var(--color-border); + transition: width 0.15s ease; + + &__top { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 var(--space-sm) var(--space-xl); + } &__brand { - padding: 0 var(--space-sm) var(--space-xl); + display: flex; + align-items: center; font-family: var(--font-display); font-weight: 700; font-size: var(--font-size-lg); color: var(--color-primary); + overflow: hidden; + white-space: nowrap; + } + + // Full wordmark by default; swapped for a short monogram when collapsed + // (see `.collapsed &__brand-full`/`&__brand-mark` below) — clearer than + // an arbitrary icon standing in for the brand itself. + &__brand-mark { + display: none; + } + + &__collapse-toggle { + width: 1.75rem; + height: 1.75rem; + flex-shrink: 0; + display: grid; + place-items: center; + border: 1px solid var(--color-border); + border-radius: var(--radius-base); + background: var(--color-surface); + color: var(--color-text-muted); + cursor: pointer; + + svg { + width: 1rem; + height: 1rem; + transition: transform 0.15s ease; + } + + &:hover { + background: var(--color-surface-alt); + color: var(--color-text); + } } &__nav { @@ -40,12 +84,23 @@ gap: var(--space-xs); a { + display: flex; + align-items: center; + gap: var(--space-sm); padding: var(--space-sm); border-radius: var(--radius-base); color: var(--color-text); font-weight: 600; font-size: var(--font-size-sm); text-decoration: none; + white-space: nowrap; + overflow: hidden; + + svg { + flex-shrink: 0; + width: 1.25rem; + height: 1.25rem; + } &:hover { background: var(--color-surface-alt); @@ -87,6 +142,19 @@ } } + &__settings-toggle-left { + display: flex; + align-items: center; + gap: var(--space-sm); + overflow: hidden; + + svg { + flex-shrink: 0; + width: 1.25rem; + height: 1.25rem; + } + } + &__settings-nav { margin-top: var(--space-xs); } @@ -99,8 +167,11 @@ } &__account-toggle { + display: flex; + align-items: center; + gap: var(--space-sm); width: 100%; - padding: 0.5rem var(--space-sm); + padding: 0.4rem var(--space-sm); font-family: var(--font-body); font-size: var(--font-size-sm); font-weight: 600; @@ -110,12 +181,27 @@ border: 1px solid var(--color-border); background: var(--color-surface); color: var(--color-text); + overflow: hidden; + white-space: nowrap; &:hover { background: var(--color-surface-alt); } } + &__avatar { + flex-shrink: 0; + width: 1.5rem; + height: 1.5rem; + display: grid; + place-items: center; + border-radius: 50%; + background: var(--color-primary); + color: #fff; + font-size: var(--font-size-xs); + font-weight: 700; + } + // Anchored just above the toggle rather than inline in the flow — it's a // transient overlay, not part of the sidebar's permanent layout. &__account-menu { @@ -143,12 +229,68 @@ background: none; border: none; cursor: pointer; + white-space: nowrap; &:hover { background: var(--color-surface-alt); } } } + + // --- Collapsed (icon-only rail) state ----------------------------------- + // A single class toggle on the root element — every nested rule below + // just hides labels/chevrons and re-centers icons via CSS, no child + // component needs to know the sidebar is collapsed. + &.collapsed { + width: 4.25rem; + padding-left: var(--space-sm); + padding-right: var(--space-sm); + + .app-sidebar__top { + flex-direction: column; + gap: var(--space-sm); + padding-left: 0; + padding-right: 0; + } + + .app-sidebar__brand-full { + display: none; + } + + .app-sidebar__brand-mark { + display: block; + } + + .app-sidebar__collapse-toggle svg { + transform: rotate(180deg); + } + + .app-sidebar__nav a, + .app-sidebar__settings-toggle, + .app-sidebar__account-toggle { + justify-content: center; + padding-left: 0; + padding-right: 0; + } + + .app-sidebar__settings-toggle-left { + gap: 0; + } + + .label, + .chevron { + display: none; + } + + // The popover would otherwise shrink to the icon rail's own width, + // squashing "Mon compte"/"Se déconnecter" — give it a normal, + // comfortable width instead, still anchored to the rail's left edge. + .app-sidebar__account-menu { + left: 0; + right: auto; + width: 12rem; + } + } } .app-content { @@ -176,10 +318,14 @@ border-right: none; border-bottom: 1px solid var(--color-border); - &__brand { + &__top { padding: 0 var(--space-sm) 0 0; } + &__brand { + padding: 0; + } + &__nav { flex-direction: row; overflow-x: auto; diff --git a/apps/web/src/layouts/AppLayout.tsx b/apps/web/src/layouts/AppLayout.tsx index eb58f9a..8012f9a 100644 --- a/apps/web/src/layouts/AppLayout.tsx +++ b/apps/web/src/layouts/AppLayout.tsx @@ -3,6 +3,20 @@ import { useTranslation } from "react-i18next"; import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; import { useAuth } from "../features/auth/AuthContext"; import "./AppLayout.scss"; +import { + AccountIcon, + ChevronLeftIcon, + DietPreferencesIcon, + HouseholdIcon, + PlanningIcon, + RecipesIcon, + SettingsIcon, + ShoppingListIcon, + UserPreferencesIcon, +} from "./nav-icons"; + +/** `localStorage` key persisting {@link AppLayout}'s collapsed/expanded sidebar state across reloads. */ +const SIDEBAR_COLLAPSED_KEY = "batchcooking:sidebarCollapsed"; /** * One entry in the sidebar's main nav. `key` maps to `layout.nav.` in @@ -10,9 +24,9 @@ import "./AppLayout.scss"; * one locale key, no other file to touch. */ const NAV_ITEMS = [ - { to: "/", key: "planning" }, - { to: "/recettes", key: "recipes" }, - { to: "/liste-de-courses", key: "shoppingList" }, + { to: "/", key: "planning", Icon: PlanningIcon }, + { to: "/recettes", key: "recipes", Icon: RecipesIcon }, + { to: "/liste-de-courses", key: "shoppingList", Icon: ShoppingListIcon }, ] as const; /** @@ -20,9 +34,10 @@ const NAV_ITEMS = [ * maps to `layout.settings.nav.`. */ const SETTINGS_ITEMS = [ - { to: "/parametres/compte", key: "account" }, - { to: "/parametres/preferences", key: "preferences" }, - { to: "/parametres/foyer", key: "household" }, + { to: "/parametres/compte", key: "account", Icon: AccountIcon }, + { to: "/parametres/preferences", key: "preferences", Icon: DietPreferencesIcon }, + { to: "/parametres/foyer", key: "household", Icon: HouseholdIcon }, + { to: "/parametres/preferences-utilisateur", key: "userPreferences", Icon: UserPreferencesIcon }, ] as const; /** @@ -30,20 +45,52 @@ const SETTINGS_ITEMS = [ * collapsible "Paramètres" nav, and the account menu at the bottom) plus a * main content area rendering the matched child route via ``. * + * The sidebar itself can be collapsed to an icon-only rail (see + * `isCollapsed`/`SIDEBAR_COLLAPSED_KEY`) — every nav item keeps its icon + * and gains a `title` tooltip, its label just hides via CSS + * (`.app-sidebar.collapsed .label`, see AppLayout.scss), so collapsing is a + * single class toggle on the `