feat(app): identity screens and /app shell — auth store, login/signup/reset flows, dashboard, account
- state/authStore: session subscription (initialize + onAuthStateChange), profile + roles load, recovery flag, URL failure; services/localeSync: profiles.locale <-> localeStore - routes: /login, /signup, /forgot-password, /reset-password, /auth/callback; guards RequireAuth (next=) and RedirectIfSignedIn; /app (dashboard), /app/account behind the guard - shell: AppLayout (desktop sidebar, light top bar, mobile drawer), SidebarNav, UserBadge, SignOutButton - account: personal / professional / preferences / security sections, one save each, Zod validation with i18n keys - ui: Icon, FormField, Notice, ButtonLink (buttonClassName shared), PasswordField, OAuthButtons (config-driven) - Home header: Mon espace / Se connecter when Supabase is configured; local tool routes untouched - i18n: auth.*, shell.*, dashboard.*, account.*, home.space.* in fr + en
This commit is contained in:
1 parent
0f7292f9b3
commit
c517ea267b
46 files changed
+2798
-11
No files matched your search
@@ -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<T extends Record<string, string>> {
|
||||
values: T
|
||||
errors: FieldErrors<T>
|
||||
state: SaveState
|
||||
field: (key: keyof T) => (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => void
|
||||
submit: (e: FormEvent) => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<T extends Record<string, string>>(
|
||||
initial: T,
|
||||
schema: ZodType<T, z.ZodTypeDef, unknown>,
|
||||
toPatch: (values: T) => OwnProfilePatch,
|
||||
): ProfileForm<T> {
|
||||
const updateProfile = useAuthStore((s) => s.updateProfile)
|
||||
const [values, setValues] = useState<T>(initial)
|
||||
const [errors, setErrors] = useState<FieldErrors<T>>({})
|
||||
const [state, setState] = useState<SaveState>('idle')
|
||||
|
||||
const field = (key: keyof T) => (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
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 }
|
||||
}
|
||||
@@ -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<typeof personalSchema>
|
||||
|
||||
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<typeof professionalSchema>
|
||||
|
||||
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<typeof preferencesSchema>
|
||||
|
||||
/** '' → 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)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex min-h-screen flex-col">
|
||||
<main className="flex-1 flex flex-col">
|
||||
@@ -22,12 +34,37 @@ function AppShell() {
|
||||
)
|
||||
}
|
||||
|
||||
/** Auth screens and the signed-in /app shell sit beside the local tool. */
|
||||
export function AppRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route element={<RedirectIfSignedIn />}>
|
||||
<Route path="/login" element={<LoginRoute />} />
|
||||
<Route path="/signup" element={<SignupRoute />} />
|
||||
<Route path="/forgot-password" element={<ForgotPasswordRoute />} />
|
||||
</Route>
|
||||
<Route path="/reset-password" element={<ResetPasswordRoute />} />
|
||||
<Route path="/auth/callback" element={<AuthCallbackRoute />} />
|
||||
<Route path="/app" element={<RequireAuth />}>
|
||||
<Route element={<AppLayout />}>
|
||||
<Route index element={<DashboardRoute />} />
|
||||
<Route path="account" element={<AccountRoute />} />
|
||||
<Route path="*" element={<NotFoundRoute />} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<LocalToolShell />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ConfigProvider>
|
||||
<BrowserRouter>
|
||||
<AppShell />
|
||||
</BrowserRouter>
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<AppRoutes />
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
</ConfigProvider>
|
||||
)
|
||||
}
|
||||
@@ -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 <Navigate to={safeNextPath(params.get('next'))} replace />
|
||||
}
|
||||
return <Outlet />
|
||||
}
|
||||
@@ -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 <SessionLoading />
|
||||
if (status === 'signed_in') return <Outlet />
|
||||
const next = encodeURIComponent(location.pathname + location.search)
|
||||
return <Navigate to={`/login?next=${next}`} replace />
|
||||
}
|
||||
@@ -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 (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex min-h-dvh flex-col items-center justify-center gap-4"
|
||||
>
|
||||
<Brand size="lg" />
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('shell.loading_session')}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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}</>
|
||||
}
|
||||
@@ -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 (
|
||||
<main className="flex-1 flex flex-col">
|
||||
<AppHeader />
|
||||
<AppHeader>
|
||||
<HomeSpaceLink />
|
||||
</AppHeader>
|
||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
||||
{noSheet && (
|
||||
|
||||
@@ -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 (
|
||||
<div className="space-y-6">
|
||||
<header className="space-y-2">
|
||||
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
|
||||
{t('account.title')}
|
||||
</h1>
|
||||
<RoleBadges />
|
||||
</header>
|
||||
{profile ? (
|
||||
<>
|
||||
<PersonalInfoForm key={`p-${profile.id}`} profile={profile} />
|
||||
<ProfessionalInfoForm key={`pro-${profile.id}`} profile={profile} />
|
||||
<PreferencesForm key={`pref-${profile.id}`} profile={profile} />
|
||||
</>
|
||||
) : (
|
||||
<Notice tone="info">{t('auth.loading')}</Notice>
|
||||
)}
|
||||
<SecurityPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<typeof useT>
|
||||
|
||||
/** 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 (
|
||||
<Card as="section" className="p-5 sm:p-6 space-y-3">
|
||||
<h2 className="font-serif text-xl">{t('dashboard.profile.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{complete ? t('dashboard.profile.complete') : t('dashboard.profile.incomplete')}
|
||||
</p>
|
||||
{!complete && (
|
||||
<p className="text-sm">
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
{t('dashboard.profile.missing_label')}
|
||||
</span>{' '}
|
||||
{missing.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
<ButtonLink to="/app/account" variant={complete ? 'secondary' : 'primary'}>
|
||||
{complete ? t('dashboard.profile.cta_view') : t('dashboard.profile.cta_complete')}
|
||||
</ButtonLink>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function ToolCard() {
|
||||
const t = useT()
|
||||
return (
|
||||
<Card as="section" className="p-5 sm:p-6 space-y-3">
|
||||
<h2 className="font-serif text-xl">{t('dashboard.tool.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('dashboard.tool.description')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<ButtonLink to="/new" variant="secondary">
|
||||
{t('dashboard.tool.cta_new')}
|
||||
</ButtonLink>
|
||||
<ButtonLink to="/" variant="ghost">
|
||||
{t('dashboard.tool.cta_import')}
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<Card as="section" className="p-5 sm:p-6 space-y-3">
|
||||
<h2 className="font-serif text-xl">{t('dashboard.account.title')}</h2>
|
||||
<dl className="grid gap-2 text-sm">
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.email')}</dt>
|
||||
<dd className="truncate">{user?.email}</dd>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-1.5 text-[var(--color-ink-muted)]">
|
||||
<Icon name={verified ? 'check' : 'alert'} size={16} />
|
||||
<span>{verified ? t('dashboard.account.verified') : t('dashboard.account.unverified')}</span>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.language')}</dt>
|
||||
<dd>{t(`lang.${locale}`)}</dd>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.roles')}</dt>
|
||||
<dd>{roles.length ? <RoleBadges /> : t('dashboard.account.no_roles')}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{created && (
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
{t('dashboard.account.member_since').replace('{date}', created)}
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DashboardRoute() {
|
||||
const t = useT()
|
||||
const profile = useAuthStore((s) => s.profile)
|
||||
const missing = missingFields(profile, t)
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header className="space-y-1">
|
||||
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
|
||||
{greeting(profile, t)}
|
||||
</h1>
|
||||
<p className="max-w-prose text-sm text-[var(--color-ink-muted)]">
|
||||
{t('dashboard.intro')}
|
||||
</p>
|
||||
</header>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<ProfileCard missing={missing} />
|
||||
<ToolCard />
|
||||
<AccountCard />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 <Navigate to={safeNextPath(params.get('next'), APP_HOME_PATH)} replace />
|
||||
}
|
||||
const providerError = params.get('error_description') ?? params.get('error')
|
||||
if (status === 'loading' && !urlFailure && !providerError) {
|
||||
return <SessionLoading />
|
||||
}
|
||||
// Landing here without a session means the exchange failed, whatever the client reported.
|
||||
return (
|
||||
<AuthLayout title={t('auth.callback.failed_title')}>
|
||||
<Notice tone="error">{t('auth.callback.failed_description')}</Notice>
|
||||
<AuthLink to="/login">{t('auth.callback.retry')}</AuthLink>
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
@@ -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<string | null>(null)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [sentTo, setSentTo] = useState<string | null>(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 = (
|
||||
<p>
|
||||
<AuthLink to="/login">{t('auth.forgot.back_to_login')}</AuthLink>
|
||||
</p>
|
||||
)
|
||||
|
||||
if (sentTo) {
|
||||
return (
|
||||
<AuthLayout title={t('auth.forgot.sent_title')} footer={footer}>
|
||||
<Notice tone="success">
|
||||
{t('auth.forgot.sent_description').replace('{email}', sentTo)}
|
||||
</Notice>
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthLayout
|
||||
title={t('auth.forgot.title')}
|
||||
subtitle={t('auth.forgot.subtitle')}
|
||||
footer={client ? footer : undefined}
|
||||
>
|
||||
{!client ? (
|
||||
<UnavailableNotice />
|
||||
) : (
|
||||
<form onSubmit={submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="forgot-email"
|
||||
label={t('auth.email')}
|
||||
error={error ? t(error) : undefined}
|
||||
>
|
||||
<Input
|
||||
id="forgot-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
inputMode="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={fieldDescribedBy('forgot-email', undefined, error ?? undefined)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
{failure && <Notice tone="error">{failure}</Notice>}
|
||||
<Button type="submit" size="lg" className="w-full" disabled={busy}>
|
||||
{busy ? t('auth.forgot.submitting') : t('auth.forgot.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
@@ -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<LoginValues>({ email: '', password: '' })
|
||||
const [errors, setErrors] = useState<FieldErrors<LoginValues>>({})
|
||||
const [failure, setFailure] = useState<string | null>(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 = (
|
||||
<p>
|
||||
{t('auth.login.no_account')}{' '}
|
||||
<AuthLink to="/signup">{t('auth.login.signup_link')}</AuthLink>
|
||||
</p>
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthLayout
|
||||
title={t('auth.login.title')}
|
||||
subtitle={t('auth.login.subtitle')}
|
||||
footer={client ? footer : undefined}
|
||||
>
|
||||
{!client ? (
|
||||
<UnavailableNotice />
|
||||
) : (
|
||||
<>
|
||||
<OAuthButtons />
|
||||
<form onSubmit={submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="login-email"
|
||||
label={t('auth.email')}
|
||||
error={errors.email && t(errors.email)}
|
||||
>
|
||||
<Input
|
||||
id="login-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
inputMode="email"
|
||||
value={values.email}
|
||||
onChange={(e) => setValues({ ...values, email: e.target.value })}
|
||||
aria-invalid={Boolean(errors.email)}
|
||||
aria-describedby={fieldDescribedBy('login-email', undefined, errors.email)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="login-password"
|
||||
label={t('auth.password')}
|
||||
error={errors.password && t(errors.password)}
|
||||
>
|
||||
<PasswordField
|
||||
id="login-password"
|
||||
autoComplete="current-password"
|
||||
value={values.password}
|
||||
onChange={(e) => setValues({ ...values, password: e.target.value })}
|
||||
aria-invalid={Boolean(errors.password)}
|
||||
aria-describedby={fieldDescribedBy('login-password', undefined, errors.password)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
{failure && <Notice tone="error">{failure}</Notice>}
|
||||
<Button type="submit" size="lg" className="w-full" disabled={busy}>
|
||||
{busy ? t('auth.login.submitting') : t('auth.login.submit')}
|
||||
</Button>
|
||||
<p className="text-center text-sm">
|
||||
<AuthLink to="/forgot-password">{t('auth.login.forgot')}</AuthLink>
|
||||
</p>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<AuthLayout
|
||||
title={t('auth.reset.no_session_title')}
|
||||
footer={
|
||||
<p>
|
||||
<AuthLink to="/login">{t('auth.forgot.back_to_login')}</AuthLink>
|
||||
</p>
|
||||
}
|
||||
>
|
||||
<Notice tone="error">{t('auth.reset.no_session_description')}</Notice>
|
||||
<AuthLink to="/forgot-password">{t('auth.reset.request_again')}</AuthLink>
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Values>({ password: '', passwordConfirm: '' })
|
||||
const [errors, setErrors] = useState<FieldErrors<Values>>({})
|
||||
const [failure, setFailure] = useState<string | null>(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 (
|
||||
<AuthLayout title={t('auth.reset.title')}>
|
||||
<UnavailableNotice />
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
if (status === 'loading') return <SessionLoading />
|
||||
if (status !== 'signed_in') return <NoSession />
|
||||
|
||||
return (
|
||||
<AuthLayout title={t('auth.reset.title')} subtitle={t('auth.reset.subtitle')}>
|
||||
<form onSubmit={submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="reset-password"
|
||||
label={t('auth.password')}
|
||||
hint={t('auth.password_hint').replace('{min}', String(PASSWORD_MIN_LENGTH))}
|
||||
error={errors.password && t(errors.password)}
|
||||
>
|
||||
<PasswordField
|
||||
id="reset-password"
|
||||
autoComplete="new-password"
|
||||
value={values.password}
|
||||
onChange={(e) => setValues({ ...values, password: e.target.value })}
|
||||
aria-invalid={Boolean(errors.password)}
|
||||
aria-describedby={fieldDescribedBy('reset-password', 'hint', errors.password)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="reset-password-confirm"
|
||||
label={t('auth.password_confirm')}
|
||||
error={errors.passwordConfirm && t(errors.passwordConfirm)}
|
||||
>
|
||||
<PasswordField
|
||||
id="reset-password-confirm"
|
||||
autoComplete="new-password"
|
||||
value={values.passwordConfirm}
|
||||
onChange={(e) => setValues({ ...values, passwordConfirm: e.target.value })}
|
||||
aria-invalid={Boolean(errors.passwordConfirm)}
|
||||
aria-describedby={fieldDescribedBy('reset-password-confirm', undefined, errors.passwordConfirm)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
{failure && <Notice tone="error">{failure}</Notice>}
|
||||
<Button type="submit" size="lg" className="w-full" disabled={busy}>
|
||||
{busy ? t('auth.reset.submitting') : t('auth.reset.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<AuthLayout
|
||||
title={t('auth.signup.check_inbox_title')}
|
||||
footer={
|
||||
<p>
|
||||
<AuthLink to="/login">{t('auth.signup.login_link')}</AuthLink>
|
||||
</p>
|
||||
}
|
||||
>
|
||||
<Notice tone="success">
|
||||
{t('auth.signup.check_inbox_description').replace('{email}', email)}
|
||||
</Notice>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('auth.signup.check_inbox_spam')}
|
||||
</p>
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SignupRoute() {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const describe = useAuthFailureMessage()
|
||||
const client = getSupabaseClient()
|
||||
const [values, setValues] = useState<SignupValues>(EMPTY)
|
||||
const [errors, setErrors] = useState<FieldErrors<SignupValues>>({})
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [sentTo, setSentTo] = useState<string | null>(null)
|
||||
|
||||
function field<K extends keyof SignupValues>(key: K) {
|
||||
return (e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
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 <CheckInbox email={sentTo} />
|
||||
|
||||
const footer = (
|
||||
<p>
|
||||
{t('auth.signup.have_account')}{' '}
|
||||
<AuthLink to="/login">{t('auth.signup.login_link')}</AuthLink>
|
||||
</p>
|
||||
)
|
||||
const passwordHint = t('auth.password_hint').replace(
|
||||
'{min}',
|
||||
String(PASSWORD_MIN_LENGTH),
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthLayout
|
||||
title={t('auth.signup.title')}
|
||||
subtitle={t('auth.signup.subtitle')}
|
||||
footer={client ? footer : undefined}
|
||||
>
|
||||
{!client ? (
|
||||
<UnavailableNotice />
|
||||
) : (
|
||||
<>
|
||||
<OAuthButtons />
|
||||
<form onSubmit={submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="signup-name"
|
||||
label={t('auth.signup.display_name')}
|
||||
hint={t('auth.signup.display_name_hint')}
|
||||
error={errors.displayName && t(errors.displayName)}
|
||||
>
|
||||
<Input
|
||||
id="signup-name"
|
||||
autoComplete="name"
|
||||
value={values.displayName}
|
||||
onChange={field('displayName')}
|
||||
aria-invalid={Boolean(errors.displayName)}
|
||||
aria-describedby={fieldDescribedBy('signup-name', 'hint', errors.displayName)}
|
||||
required
|
||||
maxLength={80}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="signup-email"
|
||||
label={t('auth.email')}
|
||||
error={errors.email && t(errors.email)}
|
||||
>
|
||||
<Input
|
||||
id="signup-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
inputMode="email"
|
||||
value={values.email}
|
||||
onChange={field('email')}
|
||||
aria-invalid={Boolean(errors.email)}
|
||||
aria-describedby={fieldDescribedBy('signup-email', undefined, errors.email)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="signup-password"
|
||||
label={t('auth.password')}
|
||||
hint={passwordHint}
|
||||
error={errors.password && t(errors.password)}
|
||||
>
|
||||
<PasswordField
|
||||
id="signup-password"
|
||||
autoComplete="new-password"
|
||||
value={values.password}
|
||||
onChange={field('password')}
|
||||
aria-invalid={Boolean(errors.password)}
|
||||
aria-describedby={fieldDescribedBy('signup-password', 'hint', errors.password)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="signup-password-confirm"
|
||||
label={t('auth.password_confirm')}
|
||||
error={errors.passwordConfirm && t(errors.passwordConfirm)}
|
||||
>
|
||||
<PasswordField
|
||||
id="signup-password-confirm"
|
||||
autoComplete="new-password"
|
||||
value={values.passwordConfirm}
|
||||
onChange={field('passwordConfirm')}
|
||||
aria-invalid={Boolean(errors.passwordConfirm)}
|
||||
aria-describedby={fieldDescribedBy('signup-password-confirm', undefined, errors.passwordConfirm)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
{failure && <Notice tone="error">{failure}</Notice>}
|
||||
<Button type="submit" size="lg" className="w-full" disabled={busy}>
|
||||
{busy ? t('auth.signup.submitting') : t('auth.signup.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</AuthLayout>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
@@ -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<T> = Partial<Record<keyof T & string, string>>
|
||||
|
||||
/** First issue per field, as an i18n key. */
|
||||
export function fieldErrors<T>(error: z.ZodError<T>): FieldErrors<T> {
|
||||
const out: Record<string, string> = {}
|
||||
for (const issue of error.issues) {
|
||||
const field = String(issue.path[0] ?? '')
|
||||
if (field && !out[field]) out[field] = issue.message
|
||||
}
|
||||
return out as FieldErrors<T>
|
||||
}
|
||||
@@ -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 (
|
||||
<SectionCard
|
||||
id="personal"
|
||||
title={t('account.personal.title')}
|
||||
description={t('account.personal.description')}
|
||||
>
|
||||
<form onSubmit={form.submit} noValidate className="space-y-4">
|
||||
<FormField id="display_name" label={t('account.personal.display_name')} error={err('display_name')}>
|
||||
<Input
|
||||
id="display_name"
|
||||
value={form.values.display_name}
|
||||
onChange={form.field('display_name')}
|
||||
autoComplete="nickname"
|
||||
maxLength={80}
|
||||
aria-invalid={Boolean(form.errors.display_name)}
|
||||
aria-describedby={fieldDescribedBy('display_name', undefined, form.errors.display_name)}
|
||||
required
|
||||
/>
|
||||
</FormField>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField id="first_name" label={t('account.personal.first_name')} optional={t('account.optional')} error={err('first_name')}>
|
||||
<Input id="first_name" value={form.values.first_name} onChange={form.field('first_name')} autoComplete="given-name" maxLength={80} />
|
||||
</FormField>
|
||||
<FormField id="last_name" label={t('account.personal.last_name')} optional={t('account.optional')} error={err('last_name')}>
|
||||
<Input id="last_name" value={form.values.last_name} onChange={form.field('last_name')} autoComplete="family-name" maxLength={80} />
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField
|
||||
id="phone"
|
||||
label={t('account.personal.phone')}
|
||||
optional={t('account.optional')}
|
||||
hint={t('account.personal.phone_hint')}
|
||||
error={err('phone')}
|
||||
>
|
||||
<Input
|
||||
id="phone"
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
placeholder="+33612345678"
|
||||
value={form.values.phone}
|
||||
onChange={form.field('phone')}
|
||||
aria-invalid={Boolean(form.errors.phone)}
|
||||
aria-describedby={fieldDescribedBy('phone', 'hint', form.errors.phone)}
|
||||
/>
|
||||
</FormField>
|
||||
<SaveRow state={form.state} />
|
||||
</form>
|
||||
</SectionCard>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<SectionCard
|
||||
id="preferences"
|
||||
title={t('account.preferences.title')}
|
||||
description={t('account.preferences.description')}
|
||||
>
|
||||
<form onSubmit={form.submit} noValidate className="space-y-4">
|
||||
<FormField id="locale" label={t('account.preferences.language')}>
|
||||
<Select
|
||||
id="locale"
|
||||
value={locale}
|
||||
onChange={(e) => setLocale(e.target.value as Locale)}
|
||||
>
|
||||
{LOCALES.map((item) => (
|
||||
<option key={item.value} value={item.value}>
|
||||
{t(item.labelKey)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="timezone"
|
||||
label={t('account.preferences.timezone')}
|
||||
hint={t('account.preferences.timezone_hint')}
|
||||
error={translateFieldError(t, form.errors.timezone)}
|
||||
>
|
||||
<Select id="timezone" value={form.values.timezone} onChange={form.field('timezone')}>
|
||||
{timezoneOptions(form.values.timezone).map((tz) => (
|
||||
<option key={tz} value={tz}>
|
||||
{tz}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
<SaveRow state={form.state} />
|
||||
</form>
|
||||
</SectionCard>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<SectionCard
|
||||
id="professional"
|
||||
title={t('account.professional.title')}
|
||||
description={t('account.professional.description')}
|
||||
>
|
||||
<form onSubmit={form.submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="professional_title"
|
||||
label={t('account.professional.professional_title')}
|
||||
optional={t('account.optional')}
|
||||
error={err('professional_title')}
|
||||
>
|
||||
<Input
|
||||
id="professional_title"
|
||||
value={form.values.professional_title}
|
||||
onChange={form.field('professional_title')}
|
||||
placeholder={t('account.professional.professional_title_placeholder')}
|
||||
autoComplete="organization-title"
|
||||
maxLength={80}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="practice_name"
|
||||
label={t('account.professional.practice_name')}
|
||||
optional={t('account.optional')}
|
||||
error={err('practice_name')}
|
||||
>
|
||||
<Input
|
||||
id="practice_name"
|
||||
value={form.values.practice_name}
|
||||
onChange={form.field('practice_name')}
|
||||
autoComplete="organization"
|
||||
maxLength={120}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="siret"
|
||||
label={t('account.professional.siret')}
|
||||
optional={t('account.optional')}
|
||||
hint={t('account.professional.siret_hint')}
|
||||
error={err('siret')}
|
||||
>
|
||||
<Input
|
||||
id="siret"
|
||||
inputMode="numeric"
|
||||
value={form.values.siret}
|
||||
onChange={form.field('siret')}
|
||||
aria-invalid={Boolean(form.errors.siret)}
|
||||
aria-describedby={fieldDescribedBy('siret', 'hint', form.errors.siret)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</FormField>
|
||||
<SaveRow state={form.state} />
|
||||
</form>
|
||||
</SectionCard>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<ul className="flex flex-wrap gap-2" aria-label={t('dashboard.account.roles')}>
|
||||
{roles.map((role) => (
|
||||
<li key={role}>
|
||||
<Badge>{t(`shell.role.${role}`)}</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex flex-wrap items-center gap-3 pt-1">
|
||||
<Button type="submit" disabled={state === 'saving'}>
|
||||
{state === 'saving' ? t('account.saving') : t('account.save')}
|
||||
</Button>
|
||||
{state === 'saved' && <Notice tone="success">{t('account.saved')}</Notice>}
|
||||
{state === 'failed' && (
|
||||
<Notice tone="error">{t('account.error.save_failed')}</Notice>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<Card as="section" aria-labelledby={`${id}-title`} className="p-5 sm:p-6">
|
||||
<div className="grid gap-5 md:grid-cols-[14rem_1fr] md:gap-8">
|
||||
<header className="space-y-1">
|
||||
<h2 id={`${id}-title`} className="font-serif text-xl text-[var(--color-ink)]">
|
||||
{title}
|
||||
</h2>
|
||||
{description && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{description}</p>
|
||||
)}
|
||||
</header>
|
||||
<div className="min-w-0">{children}</div>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -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<Values>({ password: '', passwordConfirm: '' })
|
||||
const [errors, setErrors] = useState<FieldErrors<Values>>({})
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [state, setState] = useState<State>('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 (
|
||||
<form onSubmit={submit} noValidate className="space-y-4">
|
||||
<FormField
|
||||
id="new-password"
|
||||
label={t('account.security.new_password')}
|
||||
hint={t('auth.password_hint').replace('{min}', String(PASSWORD_MIN_LENGTH))}
|
||||
error={errors.password && t(errors.password)}
|
||||
>
|
||||
<PasswordField
|
||||
id="new-password"
|
||||
autoComplete="new-password"
|
||||
value={values.password}
|
||||
onChange={(e) => setValues({ ...values, password: e.target.value })}
|
||||
aria-invalid={Boolean(errors.password)}
|
||||
aria-describedby={fieldDescribedBy('new-password', 'hint', errors.password)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="new-password-confirm"
|
||||
label={t('auth.password_confirm')}
|
||||
error={errors.passwordConfirm && t(errors.passwordConfirm)}
|
||||
>
|
||||
<PasswordField
|
||||
id="new-password-confirm"
|
||||
autoComplete="new-password"
|
||||
value={values.passwordConfirm}
|
||||
onChange={(e) => setValues({ ...values, passwordConfirm: e.target.value })}
|
||||
aria-invalid={Boolean(errors.passwordConfirm)}
|
||||
aria-describedby={fieldDescribedBy('new-password-confirm', undefined, errors.passwordConfirm)}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" variant="secondary" disabled={state === 'saving'}>
|
||||
{state === 'saving'
|
||||
? t('account.security.changing_password')
|
||||
: t('account.security.change_password')}
|
||||
</Button>
|
||||
{state === 'saved' && (
|
||||
<Notice tone="success">{t('account.security.password_changed')}</Notice>
|
||||
)}
|
||||
{failure && <Notice tone="error">{failure}</Notice>}
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SecurityPanel() {
|
||||
const t = useT()
|
||||
const email = useAuthStore((s) => s.user?.email)
|
||||
return (
|
||||
<SectionCard
|
||||
id="security"
|
||||
title={t('account.security.title')}
|
||||
description={t('account.security.description')}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-[var(--color-ink)]">
|
||||
{t('account.security.email_label')}
|
||||
</p>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{email}</p>
|
||||
</div>
|
||||
<ChangePasswordForm />
|
||||
<div className="rounded-lg border border-dashed border-[var(--color-border)] p-4">
|
||||
<p className="text-sm font-medium text-[var(--color-ink)]">
|
||||
{t('account.security.mfa_title')}
|
||||
</p>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('account.security.mfa_note')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2 border-t border-[var(--color-border)] pt-4">
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
{t('account.security.sign_out_everywhere_note')}
|
||||
</p>
|
||||
<SignOutButton className="-ml-3" />
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex min-h-dvh flex-col lg:flex-row">
|
||||
<aside className="hidden lg:flex lg:w-[42%] lg:flex-col lg:justify-between bg-[var(--color-surface-strong)] px-12 py-10">
|
||||
<Link to="/" aria-label={t('common.home')} className="w-fit">
|
||||
<Brand size="lg" />
|
||||
</Link>
|
||||
<div className="max-w-md space-y-4">
|
||||
<p className="font-serif text-3xl leading-tight text-[var(--color-ink)]">
|
||||
{t('auth.brand_claim')}
|
||||
</p>
|
||||
<p className="text-sm leading-relaxed text-[var(--color-ink-muted)]">
|
||||
{t('auth.brand_note')}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">{cfg.tagline}</p>
|
||||
</aside>
|
||||
|
||||
<main className="flex flex-1 flex-col px-4 py-6 sm:px-8 sm:py-10">
|
||||
<div className="flex items-center justify-between lg:justify-end">
|
||||
<Link to="/" aria-label={t('common.home')} className="lg:hidden">
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
<div className="flex flex-1 items-center justify-center py-8">
|
||||
<div className="w-full max-w-md space-y-5">
|
||||
<Card as="section" className="p-6 sm:p-8 space-y-6">
|
||||
<header className="space-y-1">
|
||||
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)] [text-wrap:balance]">
|
||||
{title}
|
||||
</h1>
|
||||
{subtitle && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
{children}
|
||||
</Card>
|
||||
{footer && (
|
||||
<div className="text-center text-sm text-[var(--color-ink-muted)] space-y-1">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<Link
|
||||
className={`font-medium text-[var(--color-accent)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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<OAuthProvider, string> = {
|
||||
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<string | null>(null)
|
||||
const [pending, setPending] = useState<OAuthProvider | null>(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 (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
{authProviders.map((provider) => (
|
||||
<Button
|
||||
key={provider}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => start(provider)}
|
||||
disabled={pending !== null}
|
||||
className="gap-2"
|
||||
>
|
||||
<Icon name={provider} size={18} />
|
||||
{t(LABEL[provider])}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<div className="flex items-center gap-3 text-xs text-[var(--color-ink-muted)]">
|
||||
<span className="h-px flex-1 bg-[var(--color-border)]" />
|
||||
{t('auth.or')}
|
||||
<span className="h-px flex-1 bg-[var(--color-border)]" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<InputHTMLAttributes<HTMLInputElement>, '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 (
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={visible ? 'text' : 'password'}
|
||||
className={`pr-11 ${className}`}
|
||||
{...rest}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setVisible((v) => !v)}
|
||||
aria-label={visible ? t('auth.hide_password') : t('auth.show_password')}
|
||||
aria-pressed={visible}
|
||||
className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-r-lg text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name={visible ? 'eye-off' : 'eye'} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<Notice tone="info">
|
||||
<p className="font-medium">{t('auth.unavailable_title')}</p>
|
||||
<p>{t('auth.unavailable_description')}</p>
|
||||
</Notice>
|
||||
<Button variant="secondary" onClick={() => navigate('/')}>
|
||||
{t('auth.back_to_tool')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<ButtonLink
|
||||
to={signedIn ? '/app' : '/login'}
|
||||
variant={signedIn ? 'primary' : 'secondary'}
|
||||
size="sm"
|
||||
>
|
||||
{signedIn ? t('home.space.open') : t('home.space.signin')}
|
||||
</ButtonLink>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex min-h-dvh bg-[var(--color-bg)]">
|
||||
<aside className="hidden lg:flex lg:w-64 lg:shrink-0 lg:flex-col border-r border-[var(--color-border)] bg-[var(--color-surface)]">
|
||||
<div className="px-5 py-5">
|
||||
<Link to="/app" aria-label={t('shell.nav.dashboard')} className="inline-block">
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex-1 px-3">
|
||||
<SidebarNav />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-3 border-b border-[var(--color-border)] bg-[var(--color-surface)]/95 px-3 backdrop-blur-sm sm:px-6 pt-[env(safe-area-inset-top)]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrawerOpen(true)}
|
||||
aria-label={t('shell.open_menu')}
|
||||
aria-expanded={drawerOpen}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] lg:hidden"
|
||||
>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
<Link to="/app" className="lg:hidden" aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="sm" />
|
||||
</Link>
|
||||
<h1 className="hidden lg:block text-sm font-medium text-[var(--color-ink-muted)]">
|
||||
{t(pageTitleKey(location.pathname))}
|
||||
</h1>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
</header>
|
||||
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8">
|
||||
<div className="mx-auto w-full max-w-4xl">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<MobileDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 lg:hidden">
|
||||
<motion.div
|
||||
data-testid="drawer-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.aside
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t('shell.nav_label')}
|
||||
initial={{ x: '-100%' }}
|
||||
animate={{ x: 0 }}
|
||||
exit={{ x: '-100%' }}
|
||||
transition={{ duration: 0.2, ease: 'easeOut' }}
|
||||
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
|
||||
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('shell.close_menu')}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-4">
|
||||
<SidebarNav onNavigate={onClose} />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</motion.aside>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<nav aria-label={t('shell.nav_label')} className="space-y-1">
|
||||
{NAV_ITEMS.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.end}
|
||||
onClick={onNavigate}
|
||||
className={({ isActive }) => linkClass(isActive)}
|
||||
>
|
||||
<Icon name={item.icon} size={20} className="shrink-0" />
|
||||
<span className="flex min-w-0 flex-col leading-tight">
|
||||
<span className="truncate">{t(item.labelKey)}</span>
|
||||
{item.hintKey && (
|
||||
<span className="truncate text-xs font-normal text-[var(--color-ink-muted)]">
|
||||
{t(item.hintKey)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onClick}
|
||||
disabled={busy}
|
||||
className={`justify-start gap-3 text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] ${className}`}
|
||||
>
|
||||
<Icon name="logout" size={20} />
|
||||
{busy ? t('shell.signing_out') : t('shell.sign_out')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[var(--color-accent)] text-sm font-semibold text-white"
|
||||
>
|
||||
{monogram(profile?.display_name, user?.email)}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-col leading-tight">
|
||||
<span className="truncate text-sm font-medium text-[var(--color-ink)]">
|
||||
{name}
|
||||
</span>
|
||||
{user?.email && profile?.display_name && (
|
||||
<span className="truncate text-xs text-[var(--color-ink-muted)]">
|
||||
{user.email}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -23,6 +23,20 @@ const SIZES: Record<NonNullable<ButtonProps['size']>, 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<ButtonProps['variant']> = 'primary',
|
||||
size: NonNullable<ButtonProps['size']> = '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 (
|
||||
<button
|
||||
className={[
|
||||
'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(' ')}
|
||||
className={buttonClassName(variant, size, className)}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Link, type LinkProps } from 'react-router-dom'
|
||||
import { buttonClassName, type ButtonProps } from './Button'
|
||||
|
||||
export interface ButtonLinkProps extends LinkProps {
|
||||
variant?: ButtonProps['variant']
|
||||
size?: ButtonProps['size']
|
||||
}
|
||||
|
||||
/** A router link that looks like a Button: navigation stays a link for the browser and assistive tech. */
|
||||
export default function ButtonLink({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
className = '',
|
||||
...rest
|
||||
}: ButtonLinkProps) {
|
||||
return <Link className={buttonClassName(variant, size, className)} {...rest} />
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import Label from './Label'
|
||||
|
||||
export interface FormFieldProps {
|
||||
id: string
|
||||
label: string
|
||||
/** Rendered under the control, greyed; the error replaces it when present. */
|
||||
hint?: string
|
||||
error?: string
|
||||
optional?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Describes a field for assistive tech: ids for hint and error, wired through aria-describedby. */
|
||||
export function fieldDescribedBy(id: string, hint?: string, error?: string) {
|
||||
const ids: string[] = []
|
||||
if (error) ids.push(`${id}-error`)
|
||||
else if (hint) ids.push(`${id}-hint`)
|
||||
return ids.length ? ids.join(' ') : undefined
|
||||
}
|
||||
|
||||
export default function FormField({
|
||||
id,
|
||||
label,
|
||||
hint,
|
||||
error,
|
||||
optional,
|
||||
children,
|
||||
}: FormFieldProps) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={id} className="flex items-baseline justify-between">
|
||||
<span>{label}</span>
|
||||
{optional && (
|
||||
<span className="text-xs font-normal text-[var(--color-ink-muted)]">
|
||||
{optional}
|
||||
</span>
|
||||
)}
|
||||
</Label>
|
||||
{children}
|
||||
{error ? (
|
||||
<p id={`${id}-error`} role="alert" className="text-sm text-[var(--color-danger)]">
|
||||
{error}
|
||||
</p>
|
||||
) : (
|
||||
hint && (
|
||||
<p id={`${id}-hint`} className="text-xs text-[var(--color-ink-muted)]">
|
||||
{hint}
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { SVGProps } from 'react'
|
||||
|
||||
export type IconName =
|
||||
| 'menu'
|
||||
| 'close'
|
||||
| 'dashboard'
|
||||
| 'user'
|
||||
| 'tool'
|
||||
| 'logout'
|
||||
| 'eye'
|
||||
| 'eye-off'
|
||||
| 'check'
|
||||
| 'alert'
|
||||
| 'google'
|
||||
| 'apple'
|
||||
|
||||
/** Stroke paths on a 24-unit grid; decorative by default (aria-hidden). */
|
||||
const PATHS: Record<IconName, string> = {
|
||||
menu: 'M4 7h16M4 12h16M4 17h16',
|
||||
close: 'M6 6l12 12M18 6L6 18',
|
||||
dashboard: 'M4 4h7v7H4zM13 4h7v4h-7zM13 11h7v9h-7zM4 14h7v6H4z',
|
||||
user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0',
|
||||
tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3',
|
||||
logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9',
|
||||
eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
|
||||
'eye-off':
|
||||
'M3 3l18 18M10.6 10.6A3 3 0 0 0 13.4 13.4M9.9 5.2A10.5 10.5 0 0 1 12 5c6 0 10 7 10 7a17 17 0 0 1-3.2 3.9M6.1 6.1A17 17 0 0 0 2 12s4 7 10 7a10 10 0 0 0 4-.8',
|
||||
check: 'M5 12l5 5L20 7',
|
||||
alert: 'M12 9v4M12 17h.01M10.3 3.9L2.8 17a2 2 0 0 0 1.7 3h15a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z',
|
||||
google:
|
||||
'M21 12.2c0-.7-.1-1.3-.2-1.9H12v3.6h5.1a4.4 4.4 0 0 1-1.9 2.9v2.4h3.1c1.8-1.7 2.7-4.1 2.7-7zM12 21c2.4 0 4.5-.8 6-2.2l-3.1-2.4c-.8.6-1.8.9-2.9.9-2.3 0-4.2-1.5-4.9-3.6H4v2.5A9 9 0 0 0 12 21zM7.1 13.7a5.4 5.4 0 0 1 0-3.4V7.8H4a9 9 0 0 0 0 8.4zM12 6.6c1.3 0 2.5.5 3.4 1.3l2.6-2.6A9 9 0 0 0 4 7.8l3.1 2.5c.7-2.1 2.6-3.7 4.9-3.7z',
|
||||
apple:
|
||||
'M16.4 12.6c0-2.3 1.9-3.4 2-3.5a4.3 4.3 0 0 0-3.4-1.8c-1.4-.1-2.8.9-3.5.9s-1.9-.8-3.1-.8A4.6 4.6 0 0 0 4.5 9.8c-1.7 2.9-.4 7.2 1.2 9.5.8 1.1 1.7 2.4 3 2.4s1.7-.8 3.2-.8 1.9.8 3.2.8 2.2-1.2 3-2.3a10 10 0 0 0 1.3-2.8 4.1 4.1 0 0 1-3-4zM13.8 5.6A4 4 0 0 0 14.7 2.7a4.1 4.1 0 0 0-2.7 1.4 3.8 3.8 0 0 0-1 2.8 3.4 3.4 0 0 0 2.8-1.3z',
|
||||
}
|
||||
|
||||
const FILLED: ReadonlySet<IconName> = new Set(['google', 'apple'])
|
||||
|
||||
export interface IconProps extends SVGProps<SVGSVGElement> {
|
||||
name: IconName
|
||||
size?: number
|
||||
}
|
||||
|
||||
export default function Icon({ name, size = 20, className, ...rest }: IconProps) {
|
||||
const filled = FILLED.has(name)
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill={filled ? 'currentColor' : 'none'}
|
||||
stroke={filled ? 'none' : 'currentColor'}
|
||||
strokeWidth={1.8}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
className={className}
|
||||
{...rest}
|
||||
>
|
||||
<path d={PATHS[name]} />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import Icon from './Icon'
|
||||
|
||||
export interface NoticeProps {
|
||||
tone: 'success' | 'error' | 'info'
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
const TONE: Record<NoticeProps['tone'], string> = {
|
||||
success: 'border-[var(--severity-mild)]/40 bg-[color-mix(in_srgb,var(--severity-mild)_10%,white)] text-[var(--color-ink)]',
|
||||
error: 'border-[var(--color-danger)]/40 bg-[color-mix(in_srgb,var(--color-danger)_8%,white)] text-[var(--color-danger-strong)]',
|
||||
info: 'border-[var(--color-border)] bg-[var(--color-surface-strong)] text-[var(--color-ink)]',
|
||||
}
|
||||
|
||||
/** Inline status line: icon + text, never colour alone. */
|
||||
export default function Notice({ tone, children, className = '' }: NoticeProps) {
|
||||
return (
|
||||
<div
|
||||
role={tone === 'error' ? 'alert' : 'status'}
|
||||
className={`flex items-start gap-2 rounded-lg border px-3 py-2 text-sm ${TONE[tone]} ${className}`}
|
||||
>
|
||||
<Icon
|
||||
name={tone === 'success' ? 'check' : 'alert'}
|
||||
size={18}
|
||||
className="mt-0.5 shrink-0"
|
||||
/>
|
||||
<div className="min-w-0">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -54,6 +54,9 @@ export const en: Dict = {
|
||||
'home.no_sheet.description':
|
||||
'This build of the application carries no anatomical sheet: no report can be created or imported.',
|
||||
|
||||
'home.space.signin': 'Sign in',
|
||||
'home.space.open': 'My space',
|
||||
|
||||
// footer
|
||||
'footer.all_rights_reserved': 'All rights reserved.',
|
||||
'footer.powered_by': 'Powered by',
|
||||
@@ -177,4 +180,192 @@ export const en: Dict = {
|
||||
'lang.switch_to_en': 'Switch to English',
|
||||
'lang.fr': 'FR',
|
||||
'lang.en': 'EN',
|
||||
|
||||
// auth — shared
|
||||
'auth.brand_claim': 'Your Faunosteo professional space.',
|
||||
'auth.brand_note':
|
||||
'The report tool stays available without an account. An account prepares what comes next: saved reports, animal follow-up, sharing with owners.',
|
||||
'auth.unavailable_title': 'Signed-in space not available',
|
||||
'auth.unavailable_description':
|
||||
'This installation has no authentication server. The local report tool remains usable.',
|
||||
'auth.back_to_tool': 'Back to the report tool',
|
||||
'auth.email': 'Email address',
|
||||
'auth.password': 'Password',
|
||||
'auth.password_confirm': 'Confirm password',
|
||||
'auth.password_hint':
|
||||
'At least {min} characters, with a lowercase letter, an uppercase letter and a digit.',
|
||||
'auth.show_password': 'Show password',
|
||||
'auth.hide_password': 'Hide password',
|
||||
'auth.or': 'or',
|
||||
'auth.continue_with_google': 'Continue with Google',
|
||||
'auth.continue_with_apple': 'Continue with Apple',
|
||||
'auth.loading': 'Loading…',
|
||||
|
||||
// auth — login
|
||||
'auth.login.title': 'Welcome back',
|
||||
'auth.login.subtitle': 'Sign in to your space.',
|
||||
'auth.login.submit': 'Sign in',
|
||||
'auth.login.submitting': 'Signing in…',
|
||||
'auth.login.forgot': 'Forgot your password?',
|
||||
'auth.login.no_account': 'No account yet?',
|
||||
'auth.login.signup_link': 'Create an account',
|
||||
|
||||
// auth — signup
|
||||
'auth.signup.title': 'Create your account',
|
||||
'auth.signup.subtitle': 'A few details, then a confirmation by email.',
|
||||
'auth.signup.display_name': 'Display name',
|
||||
'auth.signup.display_name_hint':
|
||||
'How others will see you. You can change it later.',
|
||||
'auth.signup.submit': 'Create my account',
|
||||
'auth.signup.submitting': 'Creating…',
|
||||
'auth.signup.have_account': 'Already have an account?',
|
||||
'auth.signup.login_link': 'Sign in',
|
||||
'auth.signup.check_inbox_title': 'Check your inbox',
|
||||
'auth.signup.check_inbox_description':
|
||||
'A confirmation link was sent to {email}. Open it to activate your account, then sign in.',
|
||||
'auth.signup.check_inbox_spam':
|
||||
'Nothing after a few minutes? Check your spam folder.',
|
||||
|
||||
// auth — forgot / reset
|
||||
'auth.forgot.title': 'Forgot password',
|
||||
'auth.forgot.subtitle':
|
||||
'Enter your email address: we will send you a link to choose a new password.',
|
||||
'auth.forgot.submit': 'Send the link',
|
||||
'auth.forgot.submitting': 'Sending…',
|
||||
'auth.forgot.sent_title': 'Link sent',
|
||||
'auth.forgot.sent_description':
|
||||
'If an account exists for {email}, an email is on its way. The link stays valid for one hour.',
|
||||
'auth.forgot.back_to_login': 'Back to sign in',
|
||||
'auth.reset.title': 'New password',
|
||||
'auth.reset.subtitle': 'Choose a new password for your account.',
|
||||
'auth.reset.submit': 'Save the password',
|
||||
'auth.reset.submitting': 'Saving…',
|
||||
'auth.reset.no_session_title': 'Invalid or expired link',
|
||||
'auth.reset.no_session_description':
|
||||
'This reset link can no longer be used. Request a new one.',
|
||||
'auth.reset.request_again': 'Request a new link',
|
||||
|
||||
// auth — callback
|
||||
'auth.callback.working': 'Signing you in…',
|
||||
'auth.callback.failed_title': 'Sign-in failed',
|
||||
'auth.callback.failed_description':
|
||||
'No session could be opened: the link expired, was already used, or was opened in a different browser than the one that requested it. If you just confirmed your address, simply sign in.',
|
||||
'auth.callback.retry': 'Try signing in again',
|
||||
|
||||
// auth — field errors (validation)
|
||||
'auth.error.email_required': 'The email address is required.',
|
||||
'auth.error.email_invalid': 'This email address is not valid.',
|
||||
'auth.error.password_required': 'The password is required.',
|
||||
'auth.error.password_rules':
|
||||
'At least 12 characters, with a lowercase letter, an uppercase letter and a digit.',
|
||||
'auth.error.password_mismatch': 'The two passwords do not match.',
|
||||
'auth.error.display_name_required': 'The display name is required.',
|
||||
'auth.error.display_name_too_long': 'The display name exceeds 80 characters.',
|
||||
|
||||
// auth — server failures
|
||||
'auth.failure.invalid_credentials': 'Incorrect email or password.',
|
||||
'auth.failure.email_not_confirmed':
|
||||
'Your email address is not confirmed yet. Open the link you received by email.',
|
||||
'auth.failure.user_exists': 'An account already exists with this email address.',
|
||||
'auth.failure.weak_password':
|
||||
'Password too weak: at least 12 characters, with a lowercase letter, an uppercase letter and a digit.',
|
||||
'auth.failure.same_password': 'The new password must differ from the old one.',
|
||||
'auth.failure.invalid_email': 'This email address is not accepted.',
|
||||
'auth.failure.rate_limited':
|
||||
'Too many attempts. Wait a few minutes before trying again.',
|
||||
'auth.failure.link_expired': 'This link has expired or was already used.',
|
||||
'auth.failure.session_expired': 'Your session has expired. Sign in again.',
|
||||
'auth.failure.provider_disabled': 'This sign-in method is not enabled.',
|
||||
'auth.failure.network': 'Cannot reach the server. Check your network.',
|
||||
'auth.failure.unknown': 'An unexpected error occurred. Try again.',
|
||||
|
||||
// shell
|
||||
'shell.nav_label': 'Main navigation',
|
||||
'shell.open_menu': 'Open menu',
|
||||
'shell.close_menu': 'Close menu',
|
||||
'shell.nav.dashboard': 'Dashboard',
|
||||
'shell.nav.account': 'My account',
|
||||
'shell.nav.local_tool': 'Report tool',
|
||||
'shell.nav.local_tool_hint': 'No account, PDF export',
|
||||
'shell.sign_out': 'Sign out',
|
||||
'shell.signing_out': 'Signing out…',
|
||||
'shell.loading_session': 'Checking your session…',
|
||||
'shell.role.owner': 'Platform owner',
|
||||
'shell.role.admin': 'Administrator',
|
||||
'shell.role.moderator': 'Moderator',
|
||||
'shell.role.support': 'Support',
|
||||
|
||||
// dashboard
|
||||
'dashboard.title': 'Dashboard',
|
||||
'dashboard.greeting': 'Hello {name}',
|
||||
'dashboard.greeting_fallback': 'Hello',
|
||||
'dashboard.intro':
|
||||
'Your Faunosteo space is ready. Online reports will come in a later version; until then the report tool remains available.',
|
||||
'dashboard.profile.title': 'Your profile',
|
||||
'dashboard.profile.incomplete':
|
||||
'Fill in your professional details: they will appear on your future reports.',
|
||||
'dashboard.profile.complete': 'Your details are filled in.',
|
||||
'dashboard.profile.missing_label': 'To complete:',
|
||||
'dashboard.profile.cta_complete': 'Complete my profile',
|
||||
'dashboard.profile.cta_view': 'View my account',
|
||||
'dashboard.tool.title': 'Report tool',
|
||||
'dashboard.tool.description':
|
||||
'Create or resume a report as today: it works without an account and exports a PDF that carries its own data.',
|
||||
'dashboard.tool.cta_new': 'New report',
|
||||
'dashboard.tool.cta_import': 'Import a PDF',
|
||||
'dashboard.account.title': 'Account',
|
||||
'dashboard.account.email': 'Email',
|
||||
'dashboard.account.verified': 'Address confirmed',
|
||||
'dashboard.account.unverified': 'Address not confirmed',
|
||||
'dashboard.account.language': 'Language',
|
||||
'dashboard.account.roles': 'Platform roles',
|
||||
'dashboard.account.no_roles': 'No platform role',
|
||||
'dashboard.account.member_since': 'Account created on {date}',
|
||||
|
||||
// account
|
||||
'account.title': 'My account',
|
||||
'account.save': 'Save',
|
||||
'account.saving': 'Saving…',
|
||||
'account.saved': 'Changes saved.',
|
||||
'account.optional': 'optional',
|
||||
'account.error.save_failed': 'Saving failed. Check the fields and try again.',
|
||||
'account.error.required': 'This field is required.',
|
||||
'account.error.too_long': 'Text too long ({max} characters maximum).',
|
||||
'account.error.phone_format':
|
||||
'International format, for example +33612345678.',
|
||||
'account.error.siret_format': 'A SIRET has exactly 14 digits.',
|
||||
'account.personal.title': 'Personal information',
|
||||
'account.personal.description': 'How you appear in Faunosteo.',
|
||||
'account.personal.display_name': 'Display name',
|
||||
'account.personal.first_name': 'First name',
|
||||
'account.personal.last_name': 'Last name',
|
||||
'account.personal.phone': 'Phone',
|
||||
'account.personal.phone_hint':
|
||||
'International format. SMS verification comes later.',
|
||||
'account.professional.title': 'Professional information',
|
||||
'account.professional.description':
|
||||
'Declarative for now: professional verification comes in a later step.',
|
||||
'account.professional.professional_title': 'Professional title',
|
||||
'account.professional.professional_title_placeholder': 'Animal osteopath',
|
||||
'account.professional.practice_name': 'Practice or organisation',
|
||||
'account.professional.siret': 'SIRET',
|
||||
'account.professional.siret_hint': '14 digits, no spaces.',
|
||||
'account.preferences.title': 'Preferences',
|
||||
'account.preferences.description':
|
||||
'The language is saved on your account and applies on every device.',
|
||||
'account.preferences.language': 'Language',
|
||||
'account.preferences.timezone': 'Time zone',
|
||||
'account.preferences.timezone_hint': 'Used for dates and future appointments.',
|
||||
'account.security.title': 'Security',
|
||||
'account.security.description': 'Password and sessions.',
|
||||
'account.security.email_label': 'Sign-in address',
|
||||
'account.security.new_password': 'New password',
|
||||
'account.security.change_password': 'Change password',
|
||||
'account.security.changing_password': 'Updating…',
|
||||
'account.security.password_changed': 'Password updated.',
|
||||
'account.security.mfa_title': 'Two-factor authentication',
|
||||
'account.security.mfa_note':
|
||||
'Not available in this version yet. It will be offered, then required for platform roles.',
|
||||
'account.security.sign_out_everywhere_note':
|
||||
'Signing out closes the session on this device.',
|
||||
}
|
||||
@@ -56,6 +56,9 @@ export const fr: Dict = {
|
||||
'home.no_sheet.description':
|
||||
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
|
||||
|
||||
'home.space.signin': 'Se connecter',
|
||||
'home.space.open': 'Mon espace',
|
||||
|
||||
// footer
|
||||
'footer.all_rights_reserved': 'Tous droits réservés.',
|
||||
'footer.powered_by': 'Propulsé par',
|
||||
@@ -193,4 +196,194 @@ export const fr: Dict = {
|
||||
'lang.switch_to_en': 'Switch to English',
|
||||
'lang.fr': 'FR',
|
||||
'lang.en': 'EN',
|
||||
|
||||
// auth — shared
|
||||
'auth.brand_claim': 'Votre espace professionnel Faunosteo.',
|
||||
'auth.brand_note':
|
||||
"L'outil de bilan reste accessible sans compte. Un compte prépare la suite : bilans enregistrés, suivi des animaux, partage avec les propriétaires.",
|
||||
'auth.unavailable_title': 'Espace connecté non disponible',
|
||||
'auth.unavailable_description':
|
||||
"Cette installation ne dispose pas de serveur d'authentification. L'outil de bilan local reste utilisable.",
|
||||
'auth.back_to_tool': "Retour à l'outil de bilan",
|
||||
'auth.email': 'Adresse e-mail',
|
||||
'auth.password': 'Mot de passe',
|
||||
'auth.password_confirm': 'Confirmer le mot de passe',
|
||||
'auth.password_hint':
|
||||
'Au moins {min} caractères, avec une minuscule, une majuscule et un chiffre.',
|
||||
'auth.show_password': 'Afficher le mot de passe',
|
||||
'auth.hide_password': 'Masquer le mot de passe',
|
||||
'auth.or': 'ou',
|
||||
'auth.continue_with_google': 'Continuer avec Google',
|
||||
'auth.continue_with_apple': 'Continuer avec Apple',
|
||||
'auth.loading': 'Chargement…',
|
||||
|
||||
// auth — login
|
||||
'auth.login.title': 'Bon retour',
|
||||
'auth.login.subtitle': 'Connectez-vous à votre espace.',
|
||||
'auth.login.submit': 'Se connecter',
|
||||
'auth.login.submitting': 'Connexion…',
|
||||
'auth.login.forgot': 'Mot de passe oublié ?',
|
||||
'auth.login.no_account': 'Pas encore de compte ?',
|
||||
'auth.login.signup_link': 'Créer un compte',
|
||||
|
||||
// auth — signup
|
||||
'auth.signup.title': 'Créer votre compte',
|
||||
'auth.signup.subtitle': "Quelques informations, puis une confirmation par e-mail.",
|
||||
'auth.signup.display_name': 'Nom affiché',
|
||||
'auth.signup.display_name_hint':
|
||||
'Tel que vos interlocuteurs le verront. Modifiable ensuite.',
|
||||
'auth.signup.submit': 'Créer mon compte',
|
||||
'auth.signup.submitting': 'Création…',
|
||||
'auth.signup.have_account': 'Déjà un compte ?',
|
||||
'auth.signup.login_link': 'Se connecter',
|
||||
'auth.signup.check_inbox_title': 'Vérifiez votre boîte mail',
|
||||
'auth.signup.check_inbox_description':
|
||||
'Un lien de confirmation a été envoyé à {email}. Ouvrez-le pour activer votre compte, puis connectez-vous.',
|
||||
'auth.signup.check_inbox_spam':
|
||||
"Rien reçu après quelques minutes ? Vérifiez vos courriers indésirables.",
|
||||
|
||||
// auth — forgot / reset
|
||||
'auth.forgot.title': 'Mot de passe oublié',
|
||||
'auth.forgot.subtitle':
|
||||
'Indiquez votre adresse e-mail : nous vous envoyons un lien pour choisir un nouveau mot de passe.',
|
||||
'auth.forgot.submit': 'Envoyer le lien',
|
||||
'auth.forgot.submitting': 'Envoi…',
|
||||
'auth.forgot.sent_title': 'Lien envoyé',
|
||||
'auth.forgot.sent_description':
|
||||
'Si un compte existe pour {email}, un e-mail vient de partir. Le lien reste valable une heure.',
|
||||
'auth.forgot.back_to_login': 'Retour à la connexion',
|
||||
'auth.reset.title': 'Nouveau mot de passe',
|
||||
'auth.reset.subtitle': 'Choisissez un nouveau mot de passe pour votre compte.',
|
||||
'auth.reset.submit': 'Enregistrer le mot de passe',
|
||||
'auth.reset.submitting': 'Enregistrement…',
|
||||
'auth.reset.no_session_title': 'Lien invalide ou expiré',
|
||||
'auth.reset.no_session_description':
|
||||
'Ce lien de réinitialisation ne peut plus être utilisé. Demandez-en un nouveau.',
|
||||
'auth.reset.request_again': 'Demander un nouveau lien',
|
||||
|
||||
// auth — callback
|
||||
'auth.callback.working': 'Connexion en cours…',
|
||||
'auth.callback.failed_title': 'Connexion impossible',
|
||||
'auth.callback.failed_description':
|
||||
"Aucune session n'a pu être ouverte : lien expiré, déjà utilisé, ou ouvert dans un autre navigateur que celui de la demande. Si vous venez de confirmer votre adresse, connectez-vous simplement.",
|
||||
'auth.callback.retry': 'Réessayer de se connecter',
|
||||
|
||||
// auth — field errors (validation)
|
||||
'auth.error.email_required': "L'adresse e-mail est requise.",
|
||||
'auth.error.email_invalid': "Cette adresse e-mail n'est pas valide.",
|
||||
'auth.error.password_required': 'Le mot de passe est requis.',
|
||||
'auth.error.password_rules':
|
||||
'Au moins 12 caractères, avec une minuscule, une majuscule et un chiffre.',
|
||||
'auth.error.password_mismatch': 'Les deux mots de passe ne correspondent pas.',
|
||||
'auth.error.display_name_required': 'Le nom affiché est requis.',
|
||||
'auth.error.display_name_too_long': 'Le nom affiché dépasse 80 caractères.',
|
||||
|
||||
// auth — server failures
|
||||
'auth.failure.invalid_credentials': 'E-mail ou mot de passe incorrect.',
|
||||
'auth.failure.email_not_confirmed':
|
||||
"Votre adresse e-mail n'est pas encore confirmée. Ouvrez le lien reçu par e-mail.",
|
||||
'auth.failure.user_exists': 'Un compte existe déjà avec cette adresse e-mail.',
|
||||
'auth.failure.weak_password':
|
||||
'Mot de passe trop faible : au moins 12 caractères, avec une minuscule, une majuscule et un chiffre.',
|
||||
'auth.failure.same_password': "Le nouveau mot de passe doit être différent de l'ancien.",
|
||||
'auth.failure.invalid_email': "Cette adresse e-mail n'est pas acceptée.",
|
||||
'auth.failure.rate_limited':
|
||||
'Trop de tentatives. Patientez quelques minutes avant de réessayer.',
|
||||
'auth.failure.link_expired': 'Ce lien a expiré ou a déjà été utilisé.',
|
||||
'auth.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.',
|
||||
'auth.failure.provider_disabled': "Ce mode de connexion n'est pas activé.",
|
||||
'auth.failure.network': 'Connexion au serveur impossible. Vérifiez votre réseau.',
|
||||
'auth.failure.unknown': "Une erreur inattendue s'est produite. Réessayez.",
|
||||
|
||||
// shell
|
||||
'shell.nav_label': 'Navigation principale',
|
||||
'shell.open_menu': 'Ouvrir le menu',
|
||||
'shell.close_menu': 'Fermer le menu',
|
||||
'shell.nav.dashboard': 'Tableau de bord',
|
||||
'shell.nav.account': 'Mon compte',
|
||||
'shell.nav.local_tool': 'Outil de bilan',
|
||||
'shell.nav.local_tool_hint': 'Sans compte, export PDF',
|
||||
'shell.sign_out': 'Se déconnecter',
|
||||
'shell.signing_out': 'Déconnexion…',
|
||||
'shell.loading_session': 'Vérification de la session…',
|
||||
'shell.role.owner': 'Propriétaire plateforme',
|
||||
'shell.role.admin': 'Administrateur',
|
||||
'shell.role.moderator': 'Modérateur',
|
||||
'shell.role.support': 'Support',
|
||||
|
||||
// dashboard
|
||||
'dashboard.title': 'Tableau de bord',
|
||||
'dashboard.greeting': 'Bonjour {name}',
|
||||
'dashboard.greeting_fallback': 'Bonjour',
|
||||
'dashboard.intro':
|
||||
"Votre espace Faunosteo est prêt. Les bilans en ligne arriveront dans une prochaine version ; d'ici là, l'outil de bilan reste disponible.",
|
||||
'dashboard.profile.title': 'Votre profil',
|
||||
'dashboard.profile.incomplete':
|
||||
'Renseignez vos informations professionnelles : elles figureront sur vos futurs bilans.',
|
||||
'dashboard.profile.complete': 'Vos informations sont renseignées.',
|
||||
'dashboard.profile.missing_label': 'À compléter :',
|
||||
'dashboard.profile.cta_complete': 'Compléter mon profil',
|
||||
'dashboard.profile.cta_view': 'Voir mon compte',
|
||||
'dashboard.tool.title': 'Outil de bilan',
|
||||
'dashboard.tool.description':
|
||||
"Créez ou reprenez un bilan comme aujourd'hui : il fonctionne sans compte et exporte un PDF qui contient ses propres données.",
|
||||
'dashboard.tool.cta_new': 'Nouveau bilan',
|
||||
'dashboard.tool.cta_import': 'Importer un PDF',
|
||||
'dashboard.account.title': 'Compte',
|
||||
'dashboard.account.email': 'E-mail',
|
||||
'dashboard.account.verified': 'Adresse confirmée',
|
||||
'dashboard.account.unverified': 'Adresse non confirmée',
|
||||
'dashboard.account.language': 'Langue',
|
||||
'dashboard.account.roles': 'Rôles plateforme',
|
||||
'dashboard.account.no_roles': 'Aucun rôle plateforme',
|
||||
'dashboard.account.member_since': 'Compte créé le {date}',
|
||||
|
||||
// account
|
||||
'account.title': 'Mon compte',
|
||||
'account.save': 'Enregistrer',
|
||||
'account.saving': 'Enregistrement…',
|
||||
'account.saved': 'Modifications enregistrées.',
|
||||
'account.optional': 'facultatif',
|
||||
'account.error.save_failed':
|
||||
"L'enregistrement a échoué. Vérifiez les champs et réessayez.",
|
||||
'account.error.required': 'Ce champ est requis.',
|
||||
'account.error.too_long': 'Texte trop long ({max} caractères maximum).',
|
||||
'account.error.phone_format':
|
||||
'Numéro au format international, par exemple +33612345678.',
|
||||
'account.error.siret_format': 'Le SIRET comporte exactement 14 chiffres.',
|
||||
'account.personal.title': 'Informations personnelles',
|
||||
'account.personal.description': 'Comment vous apparaissez dans Faunosteo.',
|
||||
'account.personal.display_name': 'Nom affiché',
|
||||
'account.personal.first_name': 'Prénom',
|
||||
'account.personal.last_name': 'Nom',
|
||||
'account.personal.phone': 'Téléphone',
|
||||
'account.personal.phone_hint':
|
||||
'Format international. La vérification par SMS viendra plus tard.',
|
||||
'account.professional.title': 'Informations professionnelles',
|
||||
'account.professional.description':
|
||||
'Déclaratives pour le moment : la vérification professionnelle arrivera dans une prochaine étape.',
|
||||
'account.professional.professional_title': 'Titre professionnel',
|
||||
'account.professional.professional_title_placeholder': 'Ostéopathe animalier',
|
||||
'account.professional.practice_name': 'Cabinet ou structure',
|
||||
'account.professional.siret': 'SIRET',
|
||||
'account.professional.siret_hint': '14 chiffres, sans espaces.',
|
||||
'account.preferences.title': 'Préférences',
|
||||
'account.preferences.description':
|
||||
"La langue est enregistrée sur votre compte et s'applique sur tous vos appareils.",
|
||||
'account.preferences.language': 'Langue',
|
||||
'account.preferences.timezone': 'Fuseau horaire',
|
||||
'account.preferences.timezone_hint':
|
||||
'Utilisé pour les dates et les futurs rendez-vous.',
|
||||
'account.security.title': 'Sécurité',
|
||||
'account.security.description': 'Mot de passe et sessions.',
|
||||
'account.security.email_label': 'Adresse de connexion',
|
||||
'account.security.new_password': 'Nouveau mot de passe',
|
||||
'account.security.change_password': 'Changer le mot de passe',
|
||||
'account.security.changing_password': 'Mise à jour…',
|
||||
'account.security.password_changed': 'Mot de passe mis à jour.',
|
||||
'account.security.mfa_title': 'Double authentification',
|
||||
'account.security.mfa_note':
|
||||
'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.',
|
||||
'account.security.sign_out_everywhere_note':
|
||||
'Se déconnecter ferme la session sur cet appareil.',
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
function isLocale(value: string): value is Locale {
|
||||
return value === 'fr' || value === 'en'
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the UI language and profiles.locale together:
|
||||
* - when an account loads, its locale wins over the device choice (once per sign-in);
|
||||
* - while signed in, switching the language is saved to the profile.
|
||||
* Returns the stop function.
|
||||
*/
|
||||
export function startLocaleSync(): () => void {
|
||||
let appliedForUser: string | null = null
|
||||
|
||||
const stopAuth = useAuthStore.subscribe((state, previous) => {
|
||||
if (!state.user) {
|
||||
appliedForUser = null
|
||||
return
|
||||
}
|
||||
const profile = state.profile
|
||||
if (!profile || profile === previous.profile) return
|
||||
if (appliedForUser === state.user.id) return
|
||||
appliedForUser = state.user.id
|
||||
if (isLocale(profile.locale)) {
|
||||
useLocaleStore.getState().setLocale(profile.locale)
|
||||
}
|
||||
})
|
||||
|
||||
const stopLocale = useLocaleStore.subscribe((state) => {
|
||||
const auth = useAuthStore.getState()
|
||||
if (auth.status !== 'signed_in' || !auth.profile) return
|
||||
if (auth.profile.locale === state.locale) return
|
||||
void auth.updateProfile({ locale: state.locale }).catch(() => undefined)
|
||||
})
|
||||
|
||||
return () => {
|
||||
stopAuth()
|
||||
stopLocale()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { create } from 'zustand'
|
||||
import {
|
||||
AuthFailure,
|
||||
type AuthChangeEvent,
|
||||
type Session,
|
||||
type User,
|
||||
classifyAuthError,
|
||||
fetchOwnPlatformRoles,
|
||||
fetchOwnProfile,
|
||||
signOut as signOutRequest,
|
||||
updateOwnProfile,
|
||||
type AuthFailureKind,
|
||||
type FaunosteoClient,
|
||||
type OwnProfilePatch,
|
||||
type PlatformRole,
|
||||
type Profile,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
/**
|
||||
* unavailable = no Supabase configured (local-only deployment); loading until
|
||||
* the client has read the persisted session and the URL (OAuth / email links).
|
||||
*/
|
||||
export type AuthStatus = 'loading' | 'unavailable' | 'signed_out' | 'signed_in'
|
||||
|
||||
export interface AuthState {
|
||||
status: AuthStatus
|
||||
session: Session | null
|
||||
user: User | null
|
||||
/** Null until loaded, or when the profile row is missing. */
|
||||
profile: Profile | null
|
||||
roles: PlatformRole[]
|
||||
/** Set by a password-recovery link until the new password is saved. */
|
||||
recovery: boolean
|
||||
/** Failure while reading the URL (expired link, bad code): shown by the landing routes. */
|
||||
urlFailure: AuthFailureKind | null
|
||||
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
|
||||
start: () => () => void
|
||||
refreshAccount: () => Promise<void>
|
||||
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
|
||||
signOut: () => Promise<void>
|
||||
clearRecovery: () => void
|
||||
}
|
||||
|
||||
type Set = (patch: Partial<AuthState>) => void
|
||||
|
||||
async function loadAccount(client: FaunosteoClient, user: User, set: Set) {
|
||||
const [profile, roles] = await Promise.all([
|
||||
fetchOwnProfile(client, user.id),
|
||||
fetchOwnPlatformRoles(client, user.id),
|
||||
])
|
||||
set({ profile, roles })
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one GoTrue event. The account load runs outside the callback: the
|
||||
* client serialises its callbacks, awaiting a request inside one deadlocks.
|
||||
*/
|
||||
function applyAuthEvent(
|
||||
client: FaunosteoClient,
|
||||
event: AuthChangeEvent,
|
||||
session: Session | null,
|
||||
set: Set,
|
||||
previousUserId: string | undefined,
|
||||
) {
|
||||
if (event === 'SIGNED_OUT' || session === null) {
|
||||
set({
|
||||
status: 'signed_out',
|
||||
session: null,
|
||||
user: null,
|
||||
profile: null,
|
||||
roles: [],
|
||||
recovery: false,
|
||||
})
|
||||
return
|
||||
}
|
||||
const patch: Partial<AuthState> = {
|
||||
status: 'signed_in',
|
||||
session,
|
||||
user: session.user,
|
||||
}
|
||||
if (event === 'PASSWORD_RECOVERY') patch.recovery = true
|
||||
set(patch)
|
||||
if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
|
||||
setTimeout(() => {
|
||||
void loadAccount(client, session.user, set).catch(() => {
|
||||
set({ profile: null, roles: [] })
|
||||
})
|
||||
}, 0)
|
||||
}
|
||||
}
|
||||
|
||||
function requireClient(): FaunosteoClient {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new AuthFailure('unknown')
|
||||
return client
|
||||
}
|
||||
|
||||
function requireUser(user: User | null): User {
|
||||
if (!user) throw new AuthFailure('session_expired')
|
||||
return user
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
status: 'loading',
|
||||
session: null,
|
||||
user: null,
|
||||
profile: null,
|
||||
roles: [],
|
||||
recovery: false,
|
||||
urlFailure: null,
|
||||
|
||||
start: () => {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) {
|
||||
set({ status: 'unavailable' })
|
||||
return () => undefined
|
||||
}
|
||||
void client.auth.initialize().then(({ error }) => {
|
||||
if (error) set({ urlFailure: classifyAuthError(error) })
|
||||
})
|
||||
const { data } = client.auth.onAuthStateChange((event, session) => {
|
||||
applyAuthEvent(client, event, session, set, get().user?.id)
|
||||
})
|
||||
return () => data.subscription.unsubscribe()
|
||||
},
|
||||
|
||||
refreshAccount: async () => {
|
||||
await loadAccount(requireClient(), requireUser(get().user), set)
|
||||
},
|
||||
|
||||
updateProfile: async (patch) => {
|
||||
const user = requireUser(get().user)
|
||||
const profile = await updateOwnProfile(requireClient(), user.id, patch)
|
||||
set({ profile })
|
||||
return profile
|
||||
},
|
||||
|
||||
signOut: async () => {
|
||||
await signOutRequest(requireClient())
|
||||
// SIGNED_OUT also arrives through the subscription; this keeps the UI honest if it does not.
|
||||
set({
|
||||
status: 'signed_out',
|
||||
session: null,
|
||||
user: null,
|
||||
profile: null,
|
||||
roles: [],
|
||||
recovery: false,
|
||||
})
|
||||
},
|
||||
|
||||
clearRecovery: () => set({ recovery: false }),
|
||||
}))
|
||||
@@ -3,6 +3,8 @@ export {
|
||||
type FaunosteoClient,
|
||||
type SupabaseConnection,
|
||||
} from './client'
|
||||
/** Auth types the app needs without depending on supabase-js directly. */
|
||||
export type { AuthChangeEvent, Session, User } from '@supabase/supabase-js'
|
||||
export type {
|
||||
Database,
|
||||
Enums,
|
||||
|
||||
Reference in new issue
Block a user