diff --git a/apps/app/src/account/useProfileForm.ts b/apps/app/src/account/useProfileForm.ts new file mode 100644 index 00000000..6b31d03d --- /dev/null +++ b/apps/app/src/account/useProfileForm.ts @@ -0,0 +1,55 @@ +import { useState, type ChangeEvent, type FormEvent } from 'react' +import type { z, ZodType } from 'zod' +import type { OwnProfilePatch } from '@faunosteo/supabase' +import { fieldErrors, type FieldErrors } from '@/auth/validation' +import { useAuthStore } from '@/state/authStore' + +export type SaveState = 'idle' | 'saving' | 'saved' | 'failed' + +export interface ProfileForm> { + values: T + errors: FieldErrors + state: SaveState + field: (key: keyof T) => (e: ChangeEvent) => void + submit: (e: FormEvent) => Promise +} + +/** + * One account section = one form: local values seeded from the profile, + * Zod validation (i18n keys), one save into profiles. The values stay what + * the user typed after a save; a failure keeps them for correction. + */ +export function useProfileForm>( + initial: T, + schema: ZodType, + toPatch: (values: T) => OwnProfilePatch, +): ProfileForm { + const updateProfile = useAuthStore((s) => s.updateProfile) + const [values, setValues] = useState(initial) + const [errors, setErrors] = useState>({}) + const [state, setState] = useState('idle') + + const field = (key: keyof T) => (e: ChangeEvent) => { + setValues((v) => ({ ...v, [key]: e.target.value })) + if (state === 'saved') setState('idle') + } + + async function submit(e: FormEvent) { + e.preventDefault() + const parsed = schema.safeParse(values) + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setState('saving') + try { + await updateProfile(toPatch(parsed.data)) + setState('saved') + } catch { + setState('failed') + } + } + + return { values, errors, state, field, submit } +} diff --git a/apps/app/src/account/validation.ts b/apps/app/src/account/validation.ts new file mode 100644 index 00000000..4a06b0d7 --- /dev/null +++ b/apps/app/src/account/validation.ts @@ -0,0 +1,80 @@ +import { z } from 'zod' +import type { OwnProfilePatch } from '@faunosteo/supabase' + +/** + * Account forms. Messages are i18n keys; a `|value` suffix carries the + * placeholder (`account.error.too_long|80` → {max} = 80). + */ +function optionalText(max: number) { + return z.string().trim().max(max, `account.error.too_long|${max}`) +} + +export const personalSchema = z.object({ + display_name: z + .string() + .trim() + .min(1, 'account.error.required') + .max(80, 'account.error.too_long|80'), + first_name: optionalText(80), + last_name: optionalText(80), + phone: z + .string() + .trim() + .refine((v) => v === '' || /^\+[1-9][0-9]{6,14}$/.test(v), 'account.error.phone_format'), +}) +export type PersonalValues = z.infer + +export const professionalSchema = z.object({ + professional_title: optionalText(80), + practice_name: optionalText(120), + siret: z + .string() + .transform((v) => v.replace(/\s+/g, '')) + .refine((v) => v === '' || /^[0-9]{14}$/.test(v), 'account.error.siret_format'), +}) +export type ProfessionalValues = z.infer + +export const preferencesSchema = z.object({ + timezone: z + .string() + .trim() + .min(1, 'account.error.required') + .max(64, 'account.error.too_long|64'), +}) +export type PreferencesValues = z.infer + +/** '' → null: the columns are nullable and refuse empty strings. */ +function orNull(value: string): string | null { + return value === '' ? null : value +} + +export function personalPatch(v: PersonalValues): OwnProfilePatch { + return { + display_name: v.display_name, + first_name: orNull(v.first_name), + last_name: orNull(v.last_name), + phone: orNull(v.phone), + } +} + +export function professionalPatch(v: ProfessionalValues): OwnProfilePatch { + return { + professional_title: orNull(v.professional_title), + practice_name: orNull(v.practice_name), + siret: orNull(v.siret), + } +} + +export function preferencesPatch(v: PreferencesValues): OwnProfilePatch { + return { timezone: v.timezone } +} + +/** Splits `key|value` and fills {max}. */ +export function translateFieldError( + t: (key: string) => string, + message: string | undefined, +): string | undefined { + if (!message) return undefined + const [key, value] = message.split('|') + return value ? t(key).replace('{max}', value) : t(key) +} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index 349d4e24..ca232e07 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -1,12 +1,24 @@ import { BrowserRouter, Routes, Route } from 'react-router-dom' import { ConfigProvider } from './providers/ConfigProvider' +import { AuthProvider } from './providers/AuthProvider' import Footer from '@/components/brand/Footer' +import AppLayout from '@/components/shell/AppLayout' +import RequireAuth from './guards/RequireAuth' +import RedirectIfSignedIn from './guards/RedirectIfSignedIn' import HomeRoute from './routes/HomeRoute' import NewReportRoute from './routes/NewReportRoute' import EditorRoute from './routes/EditorRoute' import NotFoundRoute from './routes/NotFoundRoute' +import LoginRoute from './routes/auth/LoginRoute' +import SignupRoute from './routes/auth/SignupRoute' +import ForgotPasswordRoute from './routes/auth/ForgotPasswordRoute' +import ResetPasswordRoute from './routes/auth/ResetPasswordRoute' +import AuthCallbackRoute from './routes/auth/AuthCallbackRoute' +import DashboardRoute from './routes/app/DashboardRoute' +import AccountRoute from './routes/app/AccountRoute' -function AppShell() { +/** The local tool: unchanged routes, no account needed, shared footer. */ +function LocalToolShell() { return (
@@ -22,12 +34,37 @@ function AppShell() { ) } +/** Auth screens and the signed-in /app shell sit beside the local tool. */ +export function AppRoutes() { + return ( + + }> + } /> + } /> + } /> + + } /> + } /> + }> + }> + } /> + } /> + } /> + + + } /> + + ) +} + export default function App() { return ( - - - + + + + + ) } diff --git a/apps/app/src/app/guards/RedirectIfSignedIn.tsx b/apps/app/src/app/guards/RedirectIfSignedIn.tsx new file mode 100644 index 00000000..5aad80c2 --- /dev/null +++ b/apps/app/src/app/guards/RedirectIfSignedIn.tsx @@ -0,0 +1,14 @@ +import { Navigate, Outlet, useSearchParams } from 'react-router-dom' +import { useAuthStore } from '@/state/authStore' +import { safeNextPath } from '@/auth/redirects' + +/** Wraps login / signup / forgot: a signed-in user goes straight to the app. */ +export default function RedirectIfSignedIn() { + const status = useAuthStore((s) => s.status) + const recovery = useAuthStore((s) => s.recovery) + const [params] = useSearchParams() + if (status === 'signed_in' && !recovery) { + return + } + return +} diff --git a/apps/app/src/app/guards/RequireAuth.tsx b/apps/app/src/app/guards/RequireAuth.tsx new file mode 100644 index 00000000..d75130b9 --- /dev/null +++ b/apps/app/src/app/guards/RequireAuth.tsx @@ -0,0 +1,13 @@ +import { Navigate, Outlet, useLocation } from 'react-router-dom' +import { useAuthStore } from '@/state/authStore' +import SessionLoading from './SessionLoading' + +/** Wraps /app/*: waits for the session, else sends to /login with a return path. */ +export default function RequireAuth() { + const status = useAuthStore((s) => s.status) + const location = useLocation() + if (status === 'loading') return + if (status === 'signed_in') return + const next = encodeURIComponent(location.pathname + location.search) + return +} diff --git a/apps/app/src/app/guards/SessionLoading.tsx b/apps/app/src/app/guards/SessionLoading.tsx new file mode 100644 index 00000000..b4f4609d --- /dev/null +++ b/apps/app/src/app/guards/SessionLoading.tsx @@ -0,0 +1,19 @@ +import Brand from '@/components/brand/Brand' +import { useT } from '@/i18n/useT' + +/** Full-screen wait while the client reads the persisted session. */ +export default function SessionLoading() { + const t = useT() + return ( +
+ +

+ {t('shell.loading_session')} +

+
+ ) +} diff --git a/apps/app/src/app/providers/AuthProvider.tsx b/apps/app/src/app/providers/AuthProvider.tsx new file mode 100644 index 00000000..fba0a32c --- /dev/null +++ b/apps/app/src/app/providers/AuthProvider.tsx @@ -0,0 +1,16 @@ +import { useEffect, type ReactNode } from 'react' +import { useAuthStore } from '@/state/authStore' +import { startLocaleSync } from '@/services/localeSync' + +/** Starts the session subscription and the locale sync for the app lifetime. */ +export function AuthProvider({ children }: { children: ReactNode }) { + useEffect(() => { + const stopAuth = useAuthStore.getState().start() + const stopSync = startLocaleSync() + return () => { + stopAuth() + stopSync() + } + }, []) + return <>{children} +} diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index 044e4698..2a1665c2 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -6,6 +6,7 @@ import { type RebaseOutcome, } from '@faunosteo/domain' import AppHeader from '@/components/brand/AppHeader' +import HomeSpaceLink from '@/components/brand/HomeSpaceLink' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import' @@ -147,7 +148,9 @@ export default function HomeRoute() { return (
- + + +
{noSheet && ( diff --git a/apps/app/src/app/routes/app/AccountRoute.tsx b/apps/app/src/app/routes/app/AccountRoute.tsx new file mode 100644 index 00000000..b3c2c4d3 --- /dev/null +++ b/apps/app/src/app/routes/app/AccountRoute.tsx @@ -0,0 +1,35 @@ +import PersonalInfoForm from '@/components/account/PersonalInfoForm' +import PreferencesForm from '@/components/account/PreferencesForm' +import ProfessionalInfoForm from '@/components/account/ProfessionalInfoForm' +import RoleBadges from '@/components/account/RoleBadges' +import SecurityPanel from '@/components/account/SecurityPanel' +import Notice from '@/components/ui/Notice' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +/** "Mon compte": four sections, each with its own save. */ +export default function AccountRoute() { + const t = useT() + const profile = useAuthStore((s) => s.profile) + + return ( +
+
+

+ {t('account.title')} +

+ +
+ {profile ? ( + <> + + + + + ) : ( + {t('auth.loading')} + )} + +
+ ) +} diff --git a/apps/app/src/app/routes/app/DashboardRoute.tsx b/apps/app/src/app/routes/app/DashboardRoute.tsx new file mode 100644 index 00000000..45e3ca63 --- /dev/null +++ b/apps/app/src/app/routes/app/DashboardRoute.tsx @@ -0,0 +1,136 @@ +import type { Profile } from '@faunosteo/supabase' +import RoleBadges from '@/components/account/RoleBadges' +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import Icon from '@/components/ui/Icon' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType + +/** Profile fields the dashboard asks to complete, with their label keys. */ +const COMPLETENESS: readonly { key: keyof Profile; labelKey: string }[] = [ + { key: 'first_name', labelKey: 'account.personal.first_name' }, + { key: 'last_name', labelKey: 'account.personal.last_name' }, + { key: 'professional_title', labelKey: 'account.professional.professional_title' }, + { key: 'practice_name', labelKey: 'account.professional.practice_name' }, +] + +function missingFields(profile: Profile | null, t: Translate): string[] { + if (!profile) return [] + return COMPLETENESS.filter((f) => !profile[f.key]).map((f) => t(f.labelKey)) +} + +function greeting(profile: Profile | null, t: Translate): string { + const name = profile?.first_name ?? profile?.display_name + return name + ? t('dashboard.greeting').replace('{name}', name) + : t('dashboard.greeting_fallback') +} + +function ProfileCard({ missing }: { missing: string[] }) { + const t = useT() + const complete = missing.length === 0 + return ( + +

{t('dashboard.profile.title')}

+

+ {complete ? t('dashboard.profile.complete') : t('dashboard.profile.incomplete')} +

+ {!complete && ( +

+ + {t('dashboard.profile.missing_label')} + {' '} + {missing.join(', ')} +

+ )} + + {complete ? t('dashboard.profile.cta_view') : t('dashboard.profile.cta_complete')} + +
+ ) +} + +function ToolCard() { + const t = useT() + return ( + +

{t('dashboard.tool.title')}

+

+ {t('dashboard.tool.description')} +

+
+ + {t('dashboard.tool.cta_new')} + + + {t('dashboard.tool.cta_import')} + +
+
+ ) +} + +function AccountCard() { + const t = useT() + const user = useAuthStore((s) => s.user) + const roles = useAuthStore((s) => s.roles) + const locale = useLocaleStore((s) => s.locale) + const verified = Boolean(user?.email_confirmed_at) + const created = user?.created_at + ? new Date(user.created_at).toLocaleDateString(locale) + : null + return ( + +

{t('dashboard.account.title')}

+
+
+
{t('dashboard.account.email')}
+
{user?.email}
+
+
+ + {verified ? t('dashboard.account.verified') : t('dashboard.account.unverified')} +
+
+
{t('dashboard.account.language')}
+
{t(`lang.${locale}`)}
+
+
+
{t('dashboard.account.roles')}
+
{roles.length ? : t('dashboard.account.no_roles')}
+
+
+ {created && ( +

+ {t('dashboard.account.member_since').replace('{date}', created)} +

+ )} +
+ ) +} + +export default function DashboardRoute() { + const t = useT() + const profile = useAuthStore((s) => s.profile) + const missing = missingFields(profile, t) + return ( +
+
+

+ {greeting(profile, t)} +

+

+ {t('dashboard.intro')} +

+
+
+ + + +
+
+ ) +} diff --git a/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx b/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx new file mode 100644 index 00000000..733b34b4 --- /dev/null +++ b/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx @@ -0,0 +1,34 @@ +import { Navigate, useSearchParams } from 'react-router-dom' +import AuthLayout from '@/components/auth/AuthLayout' +import AuthLink from '@/components/auth/AuthLink' +import Notice from '@/components/ui/Notice' +import SessionLoading from '@/app/guards/SessionLoading' +import { APP_HOME_PATH, safeNextPath } from '@/auth/redirects' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +/** + * Landing of OAuth redirects and email confirmation links. The client reads + * the URL on start; this route only waits for the outcome. + */ +export default function AuthCallbackRoute() { + const t = useT() + const status = useAuthStore((s) => s.status) + const urlFailure = useAuthStore((s) => s.urlFailure) + const [params] = useSearchParams() + + if (status === 'signed_in') { + return + } + const providerError = params.get('error_description') ?? params.get('error') + if (status === 'loading' && !urlFailure && !providerError) { + return + } + // Landing here without a session means the exchange failed, whatever the client reported. + return ( + + {t('auth.callback.failed_description')} + {t('auth.callback.retry')} + + ) +} diff --git a/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx b/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx new file mode 100644 index 00000000..2467f980 --- /dev/null +++ b/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx @@ -0,0 +1,97 @@ +import { useState, type FormEvent } from 'react' +import { sendPasswordReset } from '@faunosteo/supabase' +import AuthLayout from '@/components/auth/AuthLayout' +import AuthLink from '@/components/auth/AuthLink' +import UnavailableNotice from '@/components/auth/UnavailableNotice' +import Button from '@/components/ui/Button' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { absoluteUrl, RESET_PASSWORD_PATH } from '@/auth/redirects' +import { emailSchema } from '@/auth/validation' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +export default function ForgotPasswordRoute() { + const t = useT() + const describe = useAuthFailureMessage() + const client = getSupabaseClient() + const [email, setEmail] = useState('') + const [error, setError] = useState(null) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + const [sentTo, setSentTo] = useState(null) + + async function submit(e: FormEvent) { + e.preventDefault() + if (!client) return + const parsed = emailSchema.safeParse(email) + if (!parsed.success) { + setError(parsed.error.issues[0]?.message ?? 'auth.error.email_invalid') + return + } + setError(null) + setFailure(null) + setBusy(true) + try { + await sendPasswordReset(client, parsed.data, absoluteUrl(RESET_PASSWORD_PATH)) + setSentTo(parsed.data) + } catch (err) { + setFailure(describe(err)) + setBusy(false) + } + } + + const footer = ( +

+ {t('auth.forgot.back_to_login')} +

+ ) + + if (sentTo) { + return ( + + + {t('auth.forgot.sent_description').replace('{email}', sentTo)} + + + ) + } + + return ( + + {!client ? ( + + ) : ( +
+ + setEmail(e.target.value)} + aria-invalid={Boolean(error)} + aria-describedby={fieldDescribedBy('forgot-email', undefined, error ?? undefined)} + required + /> + + {failure && {failure}} + +
+ )} +
+ ) +} diff --git a/apps/app/src/app/routes/auth/LoginRoute.tsx b/apps/app/src/app/routes/auth/LoginRoute.tsx new file mode 100644 index 00000000..bbc0728f --- /dev/null +++ b/apps/app/src/app/routes/auth/LoginRoute.tsx @@ -0,0 +1,115 @@ +import { useState, type FormEvent } from 'react' +import { useNavigate, useSearchParams } from 'react-router-dom' +import { signInWithPassword } from '@faunosteo/supabase' +import AuthLayout from '@/components/auth/AuthLayout' +import AuthLink from '@/components/auth/AuthLink' +import OAuthButtons from '@/components/auth/OAuthButtons' +import PasswordField from '@/components/auth/PasswordField' +import UnavailableNotice from '@/components/auth/UnavailableNotice' +import Button from '@/components/ui/Button' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { safeNextPath } from '@/auth/redirects' +import { fieldErrors, loginSchema, type FieldErrors } from '@/auth/validation' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +type LoginValues = { email: string; password: string } + +export default function LoginRoute() { + const t = useT() + const navigate = useNavigate() + const [params] = useSearchParams() + const describe = useAuthFailureMessage() + const client = getSupabaseClient() + const [values, setValues] = useState({ email: '', password: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + + async function submit(e: FormEvent) { + e.preventDefault() + if (!client) return + const parsed = loginSchema.safeParse(values) + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setFailure(null) + setBusy(true) + try { + await signInWithPassword(client, parsed.data) + navigate(safeNextPath(params.get('next')), { replace: true }) + } catch (err) { + setFailure(describe(err)) + setBusy(false) + } + } + + const footer = ( +

+ {t('auth.login.no_account')}{' '} + {t('auth.login.signup_link')} +

+ ) + + return ( + + {!client ? ( + + ) : ( + <> + +
+ + setValues({ ...values, email: e.target.value })} + aria-invalid={Boolean(errors.email)} + aria-describedby={fieldDescribedBy('login-email', undefined, errors.email)} + required + /> + + + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('login-password', undefined, errors.password)} + required + /> + + {failure && {failure}} + +

+ {t('auth.login.forgot')} +

+
+ + )} +
+ ) +} diff --git a/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx new file mode 100644 index 00000000..ef65bd9d --- /dev/null +++ b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx @@ -0,0 +1,131 @@ +import { useState, type FormEvent } from 'react' +import { useNavigate } from 'react-router-dom' +import { updatePassword } from '@faunosteo/supabase' +import AuthLayout from '@/components/auth/AuthLayout' +import AuthLink from '@/components/auth/AuthLink' +import PasswordField from '@/components/auth/PasswordField' +import UnavailableNotice from '@/components/auth/UnavailableNotice' +import Button from '@/components/ui/Button' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Notice from '@/components/ui/Notice' +import SessionLoading from '@/app/guards/SessionLoading' +import { APP_HOME_PATH } from '@/auth/redirects' +import { + fieldErrors, + newPasswordSchema, + PASSWORD_MIN_LENGTH, + type FieldErrors, +} from '@/auth/validation' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +type Values = { password: string; passwordConfirm: string } + +function NoSession() { + const t = useT() + return ( + + {t('auth.forgot.back_to_login')} +

+ } + > + {t('auth.reset.no_session_description')} + {t('auth.reset.request_again')} +
+ ) +} + +/** + * Landing of the recovery link. The client exchanges the code on load and + * emits PASSWORD_RECOVERY; any signed-in user may also change their password here. + */ +export default function ResetPasswordRoute() { + const t = useT() + const navigate = useNavigate() + const describe = useAuthFailureMessage() + const client = getSupabaseClient() + const status = useAuthStore((s) => s.status) + const clearRecovery = useAuthStore((s) => s.clearRecovery) + const [values, setValues] = useState({ password: '', passwordConfirm: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + + async function submit(e: FormEvent) { + e.preventDefault() + if (!client) return + const parsed = newPasswordSchema.safeParse(values) + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setFailure(null) + setBusy(true) + try { + await updatePassword(client, parsed.data.password) + clearRecovery() + navigate(APP_HOME_PATH, { replace: true }) + } catch (err) { + setFailure(describe(err)) + setBusy(false) + } + } + + if (!client) { + return ( + + + + ) + } + if (status === 'loading') return + if (status !== 'signed_in') return + + return ( + +
+ + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('reset-password', 'hint', errors.password)} + required + /> + + + setValues({ ...values, passwordConfirm: e.target.value })} + aria-invalid={Boolean(errors.passwordConfirm)} + aria-describedby={fieldDescribedBy('reset-password-confirm', undefined, errors.passwordConfirm)} + required + /> + + {failure && {failure}} + +
+
+ ) +} diff --git a/apps/app/src/app/routes/auth/SignupRoute.tsx b/apps/app/src/app/routes/auth/SignupRoute.tsx new file mode 100644 index 00000000..22e726e4 --- /dev/null +++ b/apps/app/src/app/routes/auth/SignupRoute.tsx @@ -0,0 +1,200 @@ +import { useState, type FormEvent } from 'react' +import { signUpWithPassword } from '@faunosteo/supabase' +import AuthLayout from '@/components/auth/AuthLayout' +import AuthLink from '@/components/auth/AuthLink' +import OAuthButtons from '@/components/auth/OAuthButtons' +import PasswordField from '@/components/auth/PasswordField' +import UnavailableNotice from '@/components/auth/UnavailableNotice' +import Button from '@/components/ui/Button' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { absoluteUrl, AUTH_CALLBACK_PATH } from '@/auth/redirects' +import { + fieldErrors, + PASSWORD_MIN_LENGTH, + signupSchema, + type FieldErrors, +} from '@/auth/validation' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type SignupValues = { + displayName: string + email: string + password: string + passwordConfirm: string +} + +const EMPTY: SignupValues = { + displayName: '', + email: '', + password: '', + passwordConfirm: '', +} + +function CheckInbox({ email }: { email: string }) { + const t = useT() + return ( + + {t('auth.signup.login_link')} +

+ } + > + + {t('auth.signup.check_inbox_description').replace('{email}', email)} + +

+ {t('auth.signup.check_inbox_spam')} +

+
+ ) +} + +export default function SignupRoute() { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const describe = useAuthFailureMessage() + const client = getSupabaseClient() + const [values, setValues] = useState(EMPTY) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + const [sentTo, setSentTo] = useState(null) + + function field(key: K) { + return (e: React.ChangeEvent) => + setValues((v) => ({ ...v, [key]: e.target.value })) + } + + async function submit(e: FormEvent) { + e.preventDefault() + if (!client) return + const parsed = signupSchema.safeParse(values) + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setFailure(null) + setBusy(true) + try { + await signUpWithPassword(client, { + email: parsed.data.email, + password: parsed.data.password, + displayName: parsed.data.displayName, + locale, + emailRedirectTo: absoluteUrl(AUTH_CALLBACK_PATH), + }) + setSentTo(parsed.data.email) + } catch (err) { + setFailure(describe(err)) + setBusy(false) + } + } + + if (sentTo) return + + const footer = ( +

+ {t('auth.signup.have_account')}{' '} + {t('auth.signup.login_link')} +

+ ) + const passwordHint = t('auth.password_hint').replace( + '{min}', + String(PASSWORD_MIN_LENGTH), + ) + + return ( + + {!client ? ( + + ) : ( + <> + +
+ + + + + + + + + + + + + {failure && {failure}} + +
+ + )} +
+ ) +} diff --git a/apps/app/src/auth/redirects.ts b/apps/app/src/auth/redirects.ts new file mode 100644 index 00000000..f8a2dfae --- /dev/null +++ b/apps/app/src/auth/redirects.ts @@ -0,0 +1,17 @@ +/** Absolute URLs the auth emails and OAuth providers come back to. */ +export const AUTH_CALLBACK_PATH = '/auth/callback' +export const RESET_PASSWORD_PATH = '/reset-password' +export const APP_HOME_PATH = '/app' + +export function absoluteUrl(path: string): string { + return new URL(path, window.location.origin).toString() +} + +/** + * The `next` query value is only honoured when it is a same-origin path: + * never a scheme, never a protocol-relative URL. + */ +export function safeNextPath(raw: string | null, fallback = APP_HOME_PATH) { + if (!raw || !raw.startsWith('/') || raw.startsWith('//')) return fallback + return raw +} diff --git a/apps/app/src/auth/useAuthFailureMessage.ts b/apps/app/src/auth/useAuthFailureMessage.ts new file mode 100644 index 00000000..c9efc84b --- /dev/null +++ b/apps/app/src/auth/useAuthFailureMessage.ts @@ -0,0 +1,12 @@ +import { AuthFailure, ProfileError } from '@faunosteo/supabase' +import { useT } from '@/i18n/useT' + +/** One sentence per failure kind; anything else is the generic line. */ +export function useAuthFailureMessage(): (error: unknown) => string { + const t = useT() + return (error) => { + if (error instanceof AuthFailure) return t(`auth.failure.${error.kind}`) + if (error instanceof ProfileError) return t('account.error.save_failed') + return t('auth.failure.unknown') + } +} diff --git a/apps/app/src/auth/validation.ts b/apps/app/src/auth/validation.ts new file mode 100644 index 00000000..c4f2a433 --- /dev/null +++ b/apps/app/src/auth/validation.ts @@ -0,0 +1,63 @@ +import { z } from 'zod' + +/** + * Mirrors supabase/config.toml: minimum_password_length = 12, + * password_requirements = "lower_upper_letters_digits". Issue messages are + * i18n keys; the forms translate them next to the field. + */ +export const PASSWORD_MIN_LENGTH = 12 + +export const emailSchema = z + .string() + .trim() + .min(1, 'auth.error.email_required') + .email('auth.error.email_invalid') + +export const passwordSchema = z + .string() + .min(PASSWORD_MIN_LENGTH, 'auth.error.password_rules') + .regex(/[a-z]/, 'auth.error.password_rules') + .regex(/[A-Z]/, 'auth.error.password_rules') + .regex(/[0-9]/, 'auth.error.password_rules') + +export const displayNameSchema = z + .string() + .trim() + .min(1, 'auth.error.display_name_required') + .max(80, 'auth.error.display_name_too_long') + +export const loginSchema = z.object({ + email: emailSchema, + password: z.string().min(1, 'auth.error.password_required'), +}) + +export const signupSchema = z + .object({ + displayName: displayNameSchema, + email: emailSchema, + password: passwordSchema, + passwordConfirm: z.string(), + }) + .refine((v) => v.password === v.passwordConfirm, { + message: 'auth.error.password_mismatch', + path: ['passwordConfirm'], + }) + +export const newPasswordSchema = z + .object({ password: passwordSchema, passwordConfirm: z.string() }) + .refine((v) => v.password === v.passwordConfirm, { + message: 'auth.error.password_mismatch', + path: ['passwordConfirm'], + }) + +export type FieldErrors = Partial> + +/** First issue per field, as an i18n key. */ +export function fieldErrors(error: z.ZodError): FieldErrors { + const out: Record = {} + for (const issue of error.issues) { + const field = String(issue.path[0] ?? '') + if (field && !out[field]) out[field] = issue.message + } + return out as FieldErrors +} diff --git a/apps/app/src/components/account/PersonalInfoForm.tsx b/apps/app/src/components/account/PersonalInfoForm.tsx new file mode 100644 index 00000000..209bbe63 --- /dev/null +++ b/apps/app/src/components/account/PersonalInfoForm.tsx @@ -0,0 +1,74 @@ +import type { Profile } from '@faunosteo/supabase' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import SaveRow from './SaveRow' +import SectionCard from './SectionCard' +import { personalPatch, personalSchema, translateFieldError, type PersonalValues } from '@/account/validation' +import { useProfileForm } from '@/account/useProfileForm' +import { useT } from '@/i18n/useT' + +function initialValues(profile: Profile): PersonalValues { + return { + display_name: profile.display_name, + first_name: profile.first_name ?? '', + last_name: profile.last_name ?? '', + phone: profile.phone ?? '', + } +} + +export default function PersonalInfoForm({ profile }: { profile: Profile }) { + const t = useT() + const form = useProfileForm(initialValues(profile), personalSchema, personalPatch) + const err = (key: keyof PersonalValues) => translateFieldError(t, form.errors[key]) + + return ( + +
+ + + +
+ + + + + + +
+ + + + + +
+ ) +} diff --git a/apps/app/src/components/account/PreferencesForm.tsx b/apps/app/src/components/account/PreferencesForm.tsx new file mode 100644 index 00000000..748501db --- /dev/null +++ b/apps/app/src/components/account/PreferencesForm.tsx @@ -0,0 +1,80 @@ +import type { Profile } from '@faunosteo/supabase' +import FormField from '@/components/ui/FormField' +import Select from '@/components/ui/Select' +import SaveRow from './SaveRow' +import SectionCard from './SectionCard' +import { + preferencesPatch, + preferencesSchema, + translateFieldError, +} from '@/account/validation' +import { useProfileForm } from '@/account/useProfileForm' +import { useLocaleStore } from '@/state/localeStore' +import type { Locale } from '@/i18n/types' +import { useT } from '@/i18n/useT' + +const LOCALES: { value: Locale; labelKey: string }[] = [ + { value: 'fr', labelKey: 'lang.switch_to_fr' }, + { value: 'en', labelKey: 'lang.switch_to_en' }, +] + +/** Browser list when available, else the current value alone. */ +function timezoneOptions(current: string): string[] { + const intl = Intl as unknown as { supportedValuesOf?: (key: string) => string[] } + const list = intl.supportedValuesOf?.('timeZone') ?? [] + return list.includes(current) ? list : [current, ...list] +} + +/** + * Language is saved through the locale store (the sync writes profiles.locale) + * so switching here and in the header behave the same. Timezone saves directly. + */ +export default function PreferencesForm({ profile }: { profile: Profile }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const setLocale = useLocaleStore((s) => s.setLocale) + const form = useProfileForm( + { timezone: profile.timezone }, + preferencesSchema, + preferencesPatch, + ) + + return ( + +
+ + + + + + + + +
+ ) +} diff --git a/apps/app/src/components/account/ProfessionalInfoForm.tsx b/apps/app/src/components/account/ProfessionalInfoForm.tsx new file mode 100644 index 00000000..adf20d12 --- /dev/null +++ b/apps/app/src/components/account/ProfessionalInfoForm.tsx @@ -0,0 +1,85 @@ +import type { Profile } from '@faunosteo/supabase' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import SaveRow from './SaveRow' +import SectionCard from './SectionCard' +import { + professionalPatch, + professionalSchema, + translateFieldError, + type ProfessionalValues, +} from '@/account/validation' +import { useProfileForm } from '@/account/useProfileForm' +import { useT } from '@/i18n/useT' + +function initialValues(profile: Profile): ProfessionalValues { + return { + professional_title: profile.professional_title ?? '', + practice_name: profile.practice_name ?? '', + siret: profile.siret ?? '', + } +} + +export default function ProfessionalInfoForm({ profile }: { profile: Profile }) { + const t = useT() + const form = useProfileForm(initialValues(profile), professionalSchema, professionalPatch) + const err = (key: keyof ProfessionalValues) => translateFieldError(t, form.errors[key]) + + return ( + +
+ + + + + + + + + + + +
+ ) +} diff --git a/apps/app/src/components/account/RoleBadges.tsx b/apps/app/src/components/account/RoleBadges.tsx new file mode 100644 index 00000000..21fc00ee --- /dev/null +++ b/apps/app/src/components/account/RoleBadges.tsx @@ -0,0 +1,19 @@ +import Badge from '@/components/ui/Badge' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +/** Platform roles, read-only. Nothing when the account has none. */ +export default function RoleBadges() { + const roles = useAuthStore((s) => s.roles) + const t = useT() + if (roles.length === 0) return null + return ( +
    + {roles.map((role) => ( +
  • + {t(`shell.role.${role}`)} +
  • + ))} +
+ ) +} diff --git a/apps/app/src/components/account/SaveRow.tsx b/apps/app/src/components/account/SaveRow.tsx new file mode 100644 index 00000000..fc1ef709 --- /dev/null +++ b/apps/app/src/components/account/SaveRow.tsx @@ -0,0 +1,20 @@ +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import type { SaveState } from '@/account/useProfileForm' +import { useT } from '@/i18n/useT' + +/** Save button plus the outcome line of a section form. */ +export default function SaveRow({ state }: { state: SaveState }) { + const t = useT() + return ( +
+ + {state === 'saved' && {t('account.saved')}} + {state === 'failed' && ( + {t('account.error.save_failed')} + )} +
+ ) +} diff --git a/apps/app/src/components/account/SectionCard.tsx b/apps/app/src/components/account/SectionCard.tsx new file mode 100644 index 00000000..501afd5c --- /dev/null +++ b/apps/app/src/components/account/SectionCard.tsx @@ -0,0 +1,28 @@ +import type { ReactNode } from 'react' +import Card from '@/components/ui/Card' + +export interface SectionCardProps { + id: string + title: string + description?: string + children: ReactNode +} + +/** One account section: heading column on large screens, content beside it. */ +export default function SectionCard({ id, title, description, children }: SectionCardProps) { + return ( + +
+
+

+ {title} +

+ {description && ( +

{description}

+ )} +
+
{children}
+
+
+ ) +} diff --git a/apps/app/src/components/account/SecurityPanel.tsx b/apps/app/src/components/account/SecurityPanel.tsx new file mode 100644 index 00000000..7d9244bb --- /dev/null +++ b/apps/app/src/components/account/SecurityPanel.tsx @@ -0,0 +1,133 @@ +import { useState, type FormEvent } from 'react' +import { updatePassword } from '@faunosteo/supabase' +import PasswordField from '@/components/auth/PasswordField' +import Button from '@/components/ui/Button' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Notice from '@/components/ui/Notice' +import SignOutButton from '@/components/shell/SignOutButton' +import SectionCard from './SectionCard' +import { + fieldErrors, + newPasswordSchema, + PASSWORD_MIN_LENGTH, + type FieldErrors, +} from '@/auth/validation' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +type Values = { password: string; passwordConfirm: string } +type State = 'idle' | 'saving' | 'saved' + +function ChangePasswordForm() { + const t = useT() + const describe = useAuthFailureMessage() + const [values, setValues] = useState({ password: '', passwordConfirm: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [state, setState] = useState('idle') + + async function submit(e: FormEvent) { + e.preventDefault() + const client = getSupabaseClient() + const parsed = newPasswordSchema.safeParse(values) + if (!client) return + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setFailure(null) + setState('saving') + try { + await updatePassword(client, parsed.data.password) + setValues({ password: '', passwordConfirm: '' }) + setState('saved') + } catch (err) { + setFailure(describe(err)) + setState('idle') + } + } + + return ( +
+ + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('new-password', 'hint', errors.password)} + /> + + + setValues({ ...values, passwordConfirm: e.target.value })} + aria-invalid={Boolean(errors.passwordConfirm)} + aria-describedby={fieldDescribedBy('new-password-confirm', undefined, errors.passwordConfirm)} + /> + +
+ + {state === 'saved' && ( + {t('account.security.password_changed')} + )} + {failure && {failure}} +
+
+ ) +} + +export default function SecurityPanel() { + const t = useT() + const email = useAuthStore((s) => s.user?.email) + return ( + +
+
+

+ {t('account.security.email_label')} +

+

{email}

+
+ +
+

+ {t('account.security.mfa_title')} +

+

+ {t('account.security.mfa_note')} +

+
+
+

+ {t('account.security.sign_out_everywhere_note')} +

+ +
+
+
+ ) +} diff --git a/apps/app/src/components/auth/AuthLayout.tsx b/apps/app/src/components/auth/AuthLayout.tsx new file mode 100644 index 00000000..2d7342c0 --- /dev/null +++ b/apps/app/src/components/auth/AuthLayout.tsx @@ -0,0 +1,78 @@ +import type { ReactNode } from 'react' +import { Link } from 'react-router-dom' +import Brand from '@/components/brand/Brand' +import LanguageSwitcher from '@/components/brand/LanguageSwitcher' +import Card from '@/components/ui/Card' +import { useConfig } from '@/app/providers/ConfigProvider' +import { useT } from '@/i18n/useT' + +export interface AuthLayoutProps { + title: string + subtitle?: string + children: ReactNode + /** Links under the card (switch between login / signup, back links). */ + footer?: ReactNode +} + +/** + * Two columns on large screens: a warm brand panel and the form card. On + * small screens the panel collapses to the logo above the card. + */ +export default function AuthLayout({ + title, + subtitle, + children, + footer, +}: AuthLayoutProps) { + const cfg = useConfig() + const t = useT() + return ( +
+ + +
+
+ + + + +
+
+
+ +
+

+ {title} +

+ {subtitle && ( +

+ {subtitle} +

+ )} +
+ {children} +
+ {footer && ( +
+ {footer} +
+ )} +
+
+
+
+ ) +} diff --git a/apps/app/src/components/auth/AuthLink.tsx b/apps/app/src/components/auth/AuthLink.tsx new file mode 100644 index 00000000..86a39467 --- /dev/null +++ b/apps/app/src/components/auth/AuthLink.tsx @@ -0,0 +1,11 @@ +import { Link, type LinkProps } from 'react-router-dom' + +/** Accent link used under the auth cards. */ +export default function AuthLink({ className = '', ...rest }: LinkProps) { + return ( + + ) +} diff --git a/apps/app/src/components/auth/OAuthButtons.tsx b/apps/app/src/components/auth/OAuthButtons.tsx new file mode 100644 index 00000000..573b3022 --- /dev/null +++ b/apps/app/src/components/auth/OAuthButtons.tsx @@ -0,0 +1,65 @@ +import { useState } from 'react' +import { signInWithOAuth, type OAuthProvider } from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import Icon from '@/components/ui/Icon' +import Notice from '@/components/ui/Notice' +import { useConfig } from '@/app/providers/ConfigProvider' +import { getSupabaseClient } from '@/lib/supabase' +import { absoluteUrl, AUTH_CALLBACK_PATH } from '@/auth/redirects' +import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { useT } from '@/i18n/useT' + +const LABEL: Record = { + google: 'auth.continue_with_google', + apple: 'auth.continue_with_apple', +} + +/** One button per configured provider, with the "or" rule under them. Nothing when none is configured. */ +export default function OAuthButtons() { + const { authProviders } = useConfig() + const t = useT() + const describe = useAuthFailureMessage() + const [error, setError] = useState(null) + const [pending, setPending] = useState(null) + + if (authProviders.length === 0) return null + + async function start(provider: OAuthProvider) { + const client = getSupabaseClient() + if (!client) return + setPending(provider) + setError(null) + try { + await signInWithOAuth(client, provider, absoluteUrl(AUTH_CALLBACK_PATH)) + } catch (err) { + setError(describe(err)) + setPending(null) + } + } + + return ( +
+
+ {authProviders.map((provider) => ( + + ))} +
+ {error && {error}} +
+ + {t('auth.or')} + +
+
+ ) +} diff --git a/apps/app/src/components/auth/PasswordField.tsx b/apps/app/src/components/auth/PasswordField.tsx new file mode 100644 index 00000000..fb8ab2c0 --- /dev/null +++ b/apps/app/src/components/auth/PasswordField.tsx @@ -0,0 +1,30 @@ +import { useState, type InputHTMLAttributes } from 'react' +import Input from '@/components/ui/Input' +import Icon from '@/components/ui/Icon' +import { useT } from '@/i18n/useT' + +type Props = Omit, 'type'> + +/** Password input with a show/hide toggle; the toggle is a labelled button. */ +export default function PasswordField({ className = '', ...rest }: Props) { + const [visible, setVisible] = useState(false) + const t = useT() + return ( +
+ + +
+ ) +} diff --git a/apps/app/src/components/auth/UnavailableNotice.tsx b/apps/app/src/components/auth/UnavailableNotice.tsx new file mode 100644 index 00000000..a2161715 --- /dev/null +++ b/apps/app/src/components/auth/UnavailableNotice.tsx @@ -0,0 +1,21 @@ +import { useNavigate } from 'react-router-dom' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { useT } from '@/i18n/useT' + +/** Shown on the auth screens when the deployment has no Supabase. */ +export default function UnavailableNotice() { + const t = useT() + const navigate = useNavigate() + return ( +
+ +

{t('auth.unavailable_title')}

+

{t('auth.unavailable_description')}

+
+ +
+ ) +} diff --git a/apps/app/src/components/brand/HomeSpaceLink.tsx b/apps/app/src/components/brand/HomeSpaceLink.tsx new file mode 100644 index 00000000..c61c3a2f --- /dev/null +++ b/apps/app/src/components/brand/HomeSpaceLink.tsx @@ -0,0 +1,25 @@ +import ButtonLink from '@/components/ui/ButtonLink' +import { useConfig } from '@/app/providers/ConfigProvider' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +/** + * Header entry to the signed-in space, only when a backend is configured: + * "Mon espace" for a signed-in user, "Se connecter" otherwise. + */ +export default function HomeSpaceLink() { + const { supabase } = useConfig() + const status = useAuthStore((s) => s.status) + const t = useT() + if (!supabase) return null + const signedIn = status === 'signed_in' + return ( + + {signedIn ? t('home.space.open') : t('home.space.signin')} + + ) +} diff --git a/apps/app/src/components/shell/AppLayout.tsx b/apps/app/src/components/shell/AppLayout.tsx new file mode 100644 index 00000000..521b624e --- /dev/null +++ b/apps/app/src/components/shell/AppLayout.tsx @@ -0,0 +1,77 @@ +import { useState } from 'react' +import { Link, Outlet, useLocation } from 'react-router-dom' +import Brand from '@/components/brand/Brand' +import LanguageSwitcher from '@/components/brand/LanguageSwitcher' +import Icon from '@/components/ui/Icon' +import MobileDrawer from './MobileDrawer' +import SidebarNav, { NAV_ITEMS } from './SidebarNav' +import SignOutButton from './SignOutButton' +import UserBadge from './UserBadge' +import { useT } from '@/i18n/useT' + +/** Title of the current /app page for the top bar, from the nav table. */ +function pageTitleKey(pathname: string): string { + const match = NAV_ITEMS.find((item) => + item.end ? item.to === pathname : pathname.startsWith(item.to) && item.to !== '/', + ) + return match?.labelKey ?? 'shell.nav.dashboard' +} + +/** + * Authenticated shell: fixed sidebar on large screens, light top bar with a + * drawer button below. The page content scrolls on its own. + */ +export default function AppLayout() { + const t = useT() + const location = useLocation() + const [drawerOpen, setDrawerOpen] = useState(false) + + return ( +
+ + +
+
+ + + + +

+ {t(pageTitleKey(location.pathname))} +

+
+ +
+
+
+
+ +
+
+
+ + setDrawerOpen(false)} /> +
+ ) +} diff --git a/apps/app/src/components/shell/MobileDrawer.tsx b/apps/app/src/components/shell/MobileDrawer.tsx new file mode 100644 index 00000000..d9ef839a --- /dev/null +++ b/apps/app/src/components/shell/MobileDrawer.tsx @@ -0,0 +1,74 @@ +import { useEffect } from 'react' +import { Link } from 'react-router-dom' +import { AnimatePresence, motion } from 'motion/react' +import Brand from '@/components/brand/Brand' +import Icon from '@/components/ui/Icon' +import SidebarNav from './SidebarNav' +import SignOutButton from './SignOutButton' +import UserBadge from './UserBadge' +import { useT } from '@/i18n/useT' + +export interface MobileDrawerProps { + open: boolean + onClose: () => void +} + +/** Left-side navigation drawer for small screens (transform + opacity only). */ +export default function MobileDrawer({ open, onClose }: MobileDrawerProps) { + const t = useT() + useEffect(() => { + if (!open) return + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [open, onClose]) + + return ( + + {open && ( +
+ + +
+ + + + +
+
+ +
+
+ + +
+
+
+ )} +
+ ) +} diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx new file mode 100644 index 00000000..98f9830e --- /dev/null +++ b/apps/app/src/components/shell/SidebarNav.tsx @@ -0,0 +1,60 @@ +import { NavLink } from 'react-router-dom' +import Icon, { type IconName } from '@/components/ui/Icon' +import { useT } from '@/i18n/useT' + +interface NavItem { + to: string + icon: IconName + labelKey: string + hintKey?: string + end?: boolean +} + +export const NAV_ITEMS: readonly NavItem[] = [ + { to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true }, + { to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' }, + { + to: '/', + icon: 'tool', + labelKey: 'shell.nav.local_tool', + hintKey: 'shell.nav.local_tool_hint', + }, +] + +function linkClass(active: boolean): string { + return [ + 'relative flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors min-h-11', + 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]', + active + ? 'bg-[var(--color-surface-strong)] text-[var(--color-ink)] font-medium before:absolute before:left-0 before:top-2 before:bottom-2 before:w-0.5 before:rounded-full before:bg-[var(--color-accent)]' + : 'text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] hover:text-[var(--color-ink)]', + ].join(' ') +} + +/** The three destinations of the shell; `onNavigate` closes the mobile drawer. */ +export default function SidebarNav({ onNavigate }: { onNavigate?: () => void }) { + const t = useT() + return ( + + ) +} diff --git a/apps/app/src/components/shell/SignOutButton.tsx b/apps/app/src/components/shell/SignOutButton.tsx new file mode 100644 index 00000000..d302cab2 --- /dev/null +++ b/apps/app/src/components/shell/SignOutButton.tsx @@ -0,0 +1,36 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import Button from '@/components/ui/Button' +import Icon from '@/components/ui/Icon' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +export default function SignOutButton({ className = '' }: { className?: string }) { + const t = useT() + const navigate = useNavigate() + const signOut = useAuthStore((s) => s.signOut) + const [busy, setBusy] = useState(false) + + async function onClick() { + setBusy(true) + try { + await signOut() + } finally { + // The guard would redirect anyway; going home keeps the local tool one step away. + navigate('/', { replace: true }) + } + } + + return ( + + ) +} diff --git a/apps/app/src/components/shell/UserBadge.tsx b/apps/app/src/components/shell/UserBadge.tsx new file mode 100644 index 00000000..f4ebba77 --- /dev/null +++ b/apps/app/src/components/shell/UserBadge.tsx @@ -0,0 +1,38 @@ +import { useAuthStore } from '@/state/authStore' + +/** Two-letter monogram from the display name, else the email. */ +export function monogram(name: string | undefined, email: string | undefined) { + const source = (name ?? '').trim() || (email ?? '').trim() + if (!source) return '?' + const parts = source.split(/\s+/).filter(Boolean) + const letters = + parts.length >= 2 ? parts[0][0] + parts[1][0] : source.slice(0, 2) + return letters.toUpperCase() +} + +/** Avatar monogram + display name + email, as shown at the bottom of the sidebar. */ +export default function UserBadge() { + const profile = useAuthStore((s) => s.profile) + const user = useAuthStore((s) => s.user) + const name = profile?.display_name ?? user?.email ?? '' + return ( +
+ + + + {name} + + {user?.email && profile?.display_name && ( + + {user.email} + + )} + +
+ ) +} diff --git a/apps/app/src/components/ui/Button.tsx b/apps/app/src/components/ui/Button.tsx index 50d310e3..a5c1a3da 100644 --- a/apps/app/src/components/ui/Button.tsx +++ b/apps/app/src/components/ui/Button.tsx @@ -23,6 +23,20 @@ const SIZES: Record, string> = { lg: 'h-12 px-5 sm:px-6 text-base rounded-lg', } +/** The button look, reusable by links that act as buttons (ButtonLink). */ +export function buttonClassName( + variant: NonNullable = 'primary', + size: NonNullable = 'md', + className = '', +): string { + return [ + 'inline-flex items-center justify-center font-medium transition disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2', + VARIANTS[variant], + SIZES[size], + className, + ].join(' ') +} + export default function Button({ variant = 'primary', size = 'md', @@ -32,12 +46,7 @@ export default function Button({ }: ButtonProps) { return (