Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Edit the admin profile in a dialog (#14413)

Damian Legawiec99573b0c7172
diff --git a/.changeset/dashboard-edit-profile-dialog.md b/.changeset/dashboard-edit-profile-dialog.md
new file mode 100644
index 0000000000..37eec4421e
--- /dev/null
+++ b/.changeset/dashboard-edit-profile-dialog.md
@@ -0,0 +1,6 @@
+---
+"@spree/dashboard": patch
+"@spree/dashboard-core": patch
+---
+
+Edit the admin profile in a dialog opened from the user menu instead of a settings page. The `/settings/profile` route is removed; `TopBar` takes an `onEditProfile` handler and hides the menu item when none is supplied.
diff --git a/packages/dashboard-core/src/components/top-bar.tsx b/packages/dashboard-core/src/components/top-bar.tsx
index 50385701f0..ba9588d710 100644
--- a/packages/dashboard-core/src/components/top-bar.tsx
+++ b/packages/dashboard-core/src/components/top-bar.tsx
@@ -15,7 +15,6 @@ import {
ThemeMenuItems,
usePrefersReducedMotion,
} from '@spree/dashboard-ui'
-import { Link } from '@tanstack/react-router'
import {
BookOpenIcon,
ExternalLinkIcon,
@@ -49,11 +48,17 @@ const IS_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(naviga
* @param uiLocales Admin UI languages for the in-menu switcher. The app owns
* which locale bundles ship (see the dashboard's `getAvailableUiLocales`) and
* injects them here, so this core component stays free of bundle knowledge.
+ * @param onEditProfile Opens the app's edit-profile dialog. Injected the same
+ * way as `uiLocales` — the profile form lives in the app package (its hooks,
+ * schema and locale list do), so core only offers the menu entry. The item is
+ * hidden when no handler is supplied.
*/
export function TopBar({
uiLocales = [],
+ onEditProfile,
}: {
uiLocales?: ReadonlyArray<{ code: string; name: string }>
+ onEditProfile?: () => void
}) {
// Give the vertical space back to the page: once the user scrolls a detail
// page, the PageHeader below carries the title and the primary actions, so
@@ -88,7 +93,7 @@ export function TopBar({
<div className="flex items-center gap-2">
<ViewStoreLink />
- <TopBarUser uiLocales={uiLocales} />
+ <TopBarUser uiLocales={uiLocales} onEditProfile={onEditProfile} />
</div>
</header>
)
@@ -141,10 +146,15 @@ function ViewStoreLink() {
// User menu
// ---------------------------------------------------------------------------
-function TopBarUser({ uiLocales }: { uiLocales: ReadonlyArray<{ code: string; name: string }> }) {
+function TopBarUser({
+ uiLocales,
+ onEditProfile,
+}: {
+ uiLocales: ReadonlyArray<{ code: string; name: string }>
+ onEditProfile?: () => void
+}) {
const { t } = useTranslation()
const { user, logout } = useAuth()
- const { store } = useStore()
const switchAdminLocale = useSwitchAdminLocale()
if (!user) return null
@@ -203,19 +213,15 @@ function TopBarUser({ uiLocales }: { uiLocales: ReadonlyArray<{ code: string; na
onSelect={handleSelectLocale}
/>
<DropdownMenuSeparator />
- {store && (
- <DropdownMenuItem asChild>
- <Link
- to="/$storeId/settings/profile"
- params={{ storeId: store.id }}
- className="no-underline"
- >
+ {onEditProfile && (
+ <>
+ <DropdownMenuItem onClick={onEditProfile}>
<UserIcon className="size-4" />
{t('admin.account.edit_profile')}
- </Link>
- </DropdownMenuItem>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
)}
- <DropdownMenuSeparator />
<DropdownMenuItem>
<BookOpenIcon className="size-4" />
{t('admin.account.documentation')}
diff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.ts
index db8d61a7da..2419b9aa6d 100644
--- a/packages/dashboard-starter/src/routeTree.gen.ts
+++ b/packages/dashboard-starter/src/routeTree.gen.ts
@@ -34,7 +34,6 @@ import { Route as SettingsStoreRouteImport } from './../../dashboard/src/routes/
import { Route as SettingsStockLocationsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/stock-locations'
import { Route as SettingsStaffRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/staff'
import { Route as SettingsReasonsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/reasons'
-import { Route as SettingsProfileRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/profile'
import { Route as SettingsProductTypesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/product-types'
import { Route as SettingsPaymentMethodsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/payment-methods'
import { Route as SettingsMarketsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/markets'
@@ -196,11 +195,6 @@ const SettingsReasonsRoute = SettingsReasonsRouteImport.update({
path: '/reasons',
getParentRoute: () => SettingsRoute,
} as any)
-const SettingsProfileRoute = SettingsProfileRouteImport.update({
- id: '/profile',
- path: '/profile',
- getParentRoute: () => SettingsRoute,
-} as any)
const SettingsProductTypesRoute = SettingsProductTypesRouteImport.update({
id: '/product-types',
path: '/product-types',
@@ -420,7 +414,6 @@ export interface FileRoutesByFullPath {
'/$storeId/settings/markets': typeof SettingsMarketsRoute
'/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/$storeId/settings/profile': typeof SettingsProfileRoute
'/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/$storeId/settings/staff': typeof SettingsStaffRoute
'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -480,7 +473,6 @@ export interface FileRoutesByTo {
'/$storeId/settings/markets': typeof SettingsMarketsRoute
'/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/$storeId/settings/profile': typeof SettingsProfileRoute
'/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/$storeId/settings/staff': typeof SettingsStaffRoute
'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -544,7 +536,6 @@ export interface FileRoutesById {
'/_authenticated/$storeId/settings/markets': typeof SettingsMarketsRoute
'/_authenticated/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/_authenticated/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/_authenticated/$storeId/settings/profile': typeof SettingsProfileRoute
'/_authenticated/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/_authenticated/$storeId/settings/staff': typeof SettingsStaffRoute
'/_authenticated/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -608,7 +599,6 @@ export interface FileRouteTypes {
| '/$storeId/settings/markets'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/product-types'
- | '/$storeId/settings/profile'
| '/$storeId/settings/reasons'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -668,7 +658,6 @@ export interface FileRouteTypes {
| '/$storeId/settings/markets'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/product-types'
- | '/$storeId/settings/profile'
| '/$storeId/settings/reasons'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -731,7 +720,6 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/settings/markets'
| '/_authenticated/$storeId/settings/payment-methods'
| '/_authenticated/$storeId/settings/product-types'
- | '/_authenticated/$storeId/settings/profile'
| '/_authenticated/$storeId/settings/reasons'
| '/_authenticated/$storeId/settings/staff'
| '/_authenticated/$storeId/settings/stock-locations'
@@ -942,13 +930,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsReasonsRouteImport
parentRoute: typeof SettingsRoute
}
- '/_authenticated/$storeId/settings/profile': {
- id: '/_authenticated/$storeId/settings/profile'
- path: '/profile'
- fullPath: '/$storeId/settings/profile'
- preLoaderRoute: typeof SettingsProfileRouteImport
- parentRoute: typeof SettingsRoute
- }
'/_authenticated/$storeId/settings/product-types': {
id: '/_authenticated/$storeId/settings/product-types'
path: '/product-types'
@@ -1208,7 +1189,6 @@ interface SettingsRouteChildren {
SettingsMarketsRoute: typeof SettingsMarketsRoute
SettingsPaymentMethodsRoute: typeof SettingsPaymentMethodsRoute
SettingsProductTypesRoute: typeof SettingsProductTypesRoute
- SettingsProfileRoute: typeof SettingsProfileRoute
SettingsReasonsRoute: typeof SettingsReasonsRoute
SettingsStaffRoute: typeof SettingsStaffRoute
SettingsStockLocationsRoute: typeof SettingsStockLocationsRoute
@@ -1231,7 +1211,6 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsMarketsRoute: SettingsMarketsRoute,
SettingsPaymentMethodsRoute: SettingsPaymentMethodsRoute,
SettingsProductTypesRoute: SettingsProductTypesRoute,
- SettingsProfileRoute: SettingsProfileRoute,
SettingsReasonsRoute: SettingsReasonsRoute,
SettingsStaffRoute: SettingsStaffRoute,
SettingsStockLocationsRoute: SettingsStockLocationsRoute,
diff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.ts
index bc1d541192..2989d056ed 100644
--- a/packages/dashboard/e2e/helpers.ts
+++ b/packages/dashboard/e2e/helpers.ts
@@ -109,6 +109,24 @@ export async function gotoIndex(page: Page, path: string, ctaButtonName: RegExp)
await expect(page.getByRole('button', { name: ctaButtonName })).toBeVisible({ timeout: 15_000 })
}
+/**
+ * Open the edit-profile dialog from the top-bar user menu. The profile has no
+ * page of its own, so every profile assertion starts here.
+ *
+ * @param menuLabel Accessible name of the user-menu button — pass a translated
+ * pattern when the dashboard is running in another language.
+ * @param itemLabel Accessible name of the "Edit profile" menu item.
+ */
+export async function openProfileDialog(
+ page: Page,
+ menuLabel: RegExp = /user menu/i,
+ itemLabel: RegExp = /edit profile/i,
+) {
+ await page.getByRole('button', { name: menuLabel }).click()
+ await page.getByRole('menuitem', { name: itemLabel }).click()
+ await expect(page.locator('#profile-first-name')).toBeVisible({ timeout: 15_000 })
+}
+
/**
* Open the row-action kebab menu for the row whose cell text contains
* `rowText`. Mirrors the universal `admin.row_actions.menu_label` aria-label
diff --git a/packages/dashboard/e2e/profile.spec.ts b/packages/dashboard/e2e/profile.spec.ts
index 55dcf81794..9143dd429f 100644
--- a/packages/dashboard/e2e/profile.spec.ts
+++ b/packages/dashboard/e2e/profile.spec.ts
@@ -1,86 +1,86 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
-
-const PROFILE_PATH = (storeId: string) => `/${storeId}/settings/profile`
+import { login, openProfileDialog } from './helpers'
// Serial: these tests mutate the shared admin user (name + selected_locale).
// The language test resets back to English so later tests/specs see English.
test.describe.configure({ mode: 'serial' })
test.describe('profile', () => {
- test('opens the profile page from the user menu', async ({ page }) => {
+ test('opens the profile dialog from the user menu', async ({ page }) => {
await login(page)
+ await openProfileDialog(page)
- await page.getByRole('button', { name: /user menu/i }).click()
- await page.getByRole('menuitem', { name: /edit profile/i }).click()
-
- // The PageHeader title renders as an <h1>; the "Personal Details" CardTitle
- // is a <div>, so assert it as text rather than a heading role.
- await expect(page.getByRole('heading', { name: /^profile$/i })).toBeVisible({ timeout: 15_000 })
- await expect(page.getByText('Personal Details', { exact: true })).toBeVisible()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog.getByText('Profile', { exact: true })).toBeVisible()
// Email is identity-bound and not editable via PATCH /me.
await expect(page.locator('#profile-email')).toBeDisabled()
})
test('edits personal details and persists across reload', async ({ page }) => {
- const creds = await login(page)
- await page.goto(PROFILE_PATH(creds.store_id))
- await expect(page.locator('#profile-first-name')).toBeVisible({ timeout: 15_000 })
+ await login(page)
+ await openProfileDialog(page)
const firstName = `E2E${Date.now()}`
await page.locator('#profile-first-name').fill(firstName)
await page.locator('#profile-last-name').fill('Admin')
- await page.getByRole('button', { name: /^save$/i }).click()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^save$/i })
+ .click()
await expect(page.getByText(/profile updated/i)).toBeVisible({ timeout: 15_000 })
+ // Saving closes the dialog.
+ await expect(page.getByRole('dialog')).toBeHidden({ timeout: 15_000 })
await page.reload()
+ await openProfileDialog(page)
await expect(page.locator('#profile-first-name')).toHaveValue(firstName, { timeout: 15_000 })
})
test('switching the language translates the admin UI', async ({ page }) => {
- const creds = await login(page)
- await page.goto(PROFILE_PATH(creds.store_id))
- await expect(page.locator('#profile-language')).toBeVisible({ timeout: 15_000 })
+ await login(page)
+ await openProfileDialog(page)
// Select Polish (endonym shown in the picker) and save. The save triggers a
// reload into Polish, so we assert on stable translated chrome that's always
- // present (not the dirty-only Save button).
+ // present.
await page.locator('#profile-language').click()
await page.getByRole('option', { name: /polski/i }).click()
- await page.getByRole('button', { name: /^save$/i }).click()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^save$/i })
+ .click()
- // Whole UI re-renders in Polish: card title "Personal Details" → "Dane
- // osobowe", and the nav "Products" → "Produkty" (proves table/nav labels
- // resolved at boot, not just live-subscribed components).
- await expect(page.getByText('Dane osobowe', { exact: true })).toBeVisible({ timeout: 15_000 })
- await expect(page.getByRole('link', { name: /produkty/i })).toBeVisible()
+ // Whole UI re-renders in Polish: the nav "Products" → "Produkty" (proves
+ // table/nav labels resolved at boot, not just live-subscribed components).
+ await expect(page.getByRole('link', { name: /produkty/i })).toBeVisible({ timeout: 15_000 })
// Survives a reload (locale persisted in localStorage + bundle loaded eagerly
// at boot).
await page.reload()
- await expect(page.getByText('Dane osobowe', { exact: true })).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByRole('link', { name: /produkty/i })).toBeVisible({ timeout: 15_000 })
// Table-driven pages also translate: the Customers list column headers are
// resolved from `i18n.t()` at module load, so they only render in Polish if
// the bundle is registered before the table module evaluates (the reload +
// eager-bundle path). "Total spent" → "Łączne wydatki".
+ const creds = await login(page)
await page.goto(`/${creds.store_id}/customers`)
await expect(page.getByRole('columnheader', { name: /łączne wydatki/i })).toBeVisible({
timeout: 15_000,
})
// Back to the profile to reset to English so later tests/specs run against
- // English chrome. The language field label is now "Język".
- await page.goto(PROFILE_PATH(creds.store_id))
- await expect(page.locator('#profile-language')).toBeVisible({ timeout: 15_000 })
- await page.getByLabel(/^język$/i).click()
+ // English chrome. The menu and its item are now Polish.
+ await openProfileDialog(page, /menu użytkownika/i, /edytuj profil/i)
+ await page.locator('#profile-language').click()
await page.getByRole('option', { name: /english/i }).click()
- await page.getByRole('button', { name: /^zapisz$/i }).click()
- await expect(page.getByText('Personal Details', { exact: true })).toBeVisible({
- timeout: 15_000,
- })
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^zapisz$/i })
+ .click()
+ await expect(page.getByRole('link', { name: /^products$/i })).toBeVisible({ timeout: 15_000 })
})
test('switches the language from the top-bar menu and persists it', async ({ page }) => {
diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.ts
index 5dd1b394c4..9f91a7b5ca 100644
--- a/packages/dashboard/e2e/store-settings.spec.ts
+++ b/packages/dashboard/e2e/store-settings.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { login, openProfileDialog } from './helpers'
const STORE_PATH = (storeId: string) => `/${storeId}/settings/store`
const EMAILS_PATH = (storeId: string) => `/${storeId}/settings/emails`
@@ -72,18 +72,20 @@ test.describe('store settings — general', () => {
// provider reverts a localStorage-only switch back to the saved language on
// the next session bootstrap. German here; the store switch to Polish below
// must win over it and survive a reload.
- await page.goto(`/${creds.store_id}/settings/profile`)
- await expect(page.locator('#profile-language')).toBeVisible({ timeout: 15_000 })
+ // A prior run may have already left the account on German, so the dialog
+ // may open in either language — match both, here and on the buttons below.
+ await openProfileDialog(page, /user menu|benutzermenü/i, /edit profile|profil bearbeiten/i)
await page.locator('#profile-language').click()
await page.getByRole('option', { name: /^deutsch$/i }).click()
- // Save only if the selection dirtied the form — a prior run may have already
- // left the account on German, in which case the button stays disabled.
- const saveProfile = page.getByRole('button', { name: /^(save|speichern)$/i })
+ // Save only if the selection dirtied the form; when it didn't, the account
+ // is already German and the button stays disabled, so just close.
+ const dialog = page.getByRole('dialog')
+ const saveProfile = dialog.getByRole('button', { name: /^(save|speichern)$/i })
if (await saveProfile.isEnabled()) await saveProfile.click()
- // Saving a new language reloads into it; the profile heading is now German.
- await expect(page.getByText('Persönliche Daten', { exact: true })).toBeVisible({
- timeout: 15_000,
- })
+ else await dialog.getByRole('button', { name: /^(cancel|abbrechen)$/i }).click()
+ // Either way the dialog closes and the admin is on German: saving reloads
+ // into it, and the disabled branch means it was already German.
+ await expect(page.getByRole('link', { name: /^produkte$/i })).toBeVisible({ timeout: 15_000 })
await page.goto(STORE_PATH(creds.store_id))
await expect(page.locator('#store-admin-locale')).toBeVisible({ timeout: 15_000 })
diff --git a/packages/dashboard/src/components/spree/profile-dialog.tsx b/packages/dashboard/src/components/spree/profile-dialog.tsx
new file mode 100644
index 0000000000..a133045ea7
--- /dev/null
+++ b/packages/dashboard/src/components/spree/profile-dialog.tsx
@@ -0,0 +1,271 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { type MeResponse, SpreeError } from '@spree/admin-sdk'
+import {
+ ImageUploadField,
+ i18n,
+ mapSpreeErrorsToForm,
+ switchLocale,
+ useAuth,
+} from '@spree/dashboard-core'
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ ErrorState,
+ Field,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Skeleton,
+} from '@spree/dashboard-ui'
+import { useEffect, useMemo } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { useProfile, useUpdateProfile } from '../../hooks/use-profile'
+import { getAvailableUiLocales } from '../../i18n-setup'
+import { type MeFormValues, meFormSchema, meToForm, meToParams } from '../../schemas/me'
+
+// The language the dashboard is currently displaying — persisted in
+// localStorage and applied by i18next at boot. Used as the profile language
+// fallback when the account has no saved `selected_locale`, so the picker
+// reflects what the user actually sees (and a save persists it) instead of
+// initializing to an empty value that matches no option and renders blank.
+function currentUiLocale(): string {
+ const available = getAvailableUiLocales().map((l) => l.code)
+ const active = i18n.resolvedLanguage ?? i18n.language
+ return active && available.includes(active) ? active : 'en'
+}
+
+/**
+ * Edit-profile dialog for the signed-in admin. Opened from the top-bar user
+ * menu — the profile has no page of its own.
+ */
+export function ProfileDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ // The dialog is mounted on every store page; don't fetch until it opens.
+ const { data: me, isLoading, error, refetch } = useProfile(open)
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.profile.title')}</DialogTitle>
+ <DialogDescription>{t('admin.pages.profile.subtitle')}</DialogDescription>
+ </DialogHeader>
+ {error ? (
+ <DialogBody>
+ <ErrorState
+ title={t('admin.pages.profile.load_failed_title')}
+ description={error instanceof Error ? error.message : undefined}
+ onRetry={() => refetch()}
+ />
+ </DialogBody>
+ ) : isLoading || !me ? (
+ <DialogBody className="flex flex-col gap-4">
+ <Skeleton className="h-16 w-16 rounded-md" />
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-9 w-full" />
+ </DialogBody>
+ ) : (
+ // Mount the form only once `me` is loaded so `useForm` initializes
+ // with concrete string defaults — keeps the inputs/Select controlled
+ // from the first render.
+ <ProfileForm me={me} onOpenChange={onOpenChange} />
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function ProfileForm({
+ me,
+ onOpenChange,
+}: {
+ me: MeResponse
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { updateUser } = useAuth()
+ const updateMutation = useUpdateProfile()
+
+ const form = useForm<MeFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(meFormSchema) as any,
+ defaultValues: meToForm(me, currentUiLocale()),
+ })
+
+ // Re-baseline from the refetched profile after a save (e.g. to surface the
+ // newly-persisted avatar_url as the server image), unless the admin has
+ // unsaved edits in flight.
+ useEffect(() => {
+ if (form.formState.isDirty) return
+ form.reset(meToForm(me, currentUiLocale()))
+ }, [me, form])
+
+ // Release the picked avatar's object URL when it's replaced or the dialog
+ // unmounts. ImageUploadField hands the blob URL to the form (its caller), so
+ // the form owns revoking it — otherwise form.reset() (re-baseline above) or a
+ // close drops it without freeing the blob. Double-revokes (the field also
+ // revokes on replace/remove) are harmless no-ops.
+ const avatarPreviewUrl = form.watch('avatar_preview_url')
+ useEffect(() => {
+ if (!avatarPreviewUrl) return
+ return () => URL.revokeObjectURL(avatarPreviewUrl)
+ }, [avatarPreviewUrl])
+
+ const onSubmit = async (values: MeFormValues) => {
+ try {
+ const updated = await updateMutation.mutateAsync(meToParams(values))
+ // Reflect the new name/locale/avatar in the auth context (top-bar, etc.)
+ // immediately instead of waiting for the next token refresh.
+ updateUser(updated.user)
+ toast.success(t('admin.messages.profile_updated'))
+ // Closing unmounts the form, so the avatar state doesn't need preserving
+ // across the save — the reopened dialog re-hydrates from the mutation
+ // response that `useUpdateProfile` writes into the cache.
+ form.reset({ ...values, avatar_signed_id: null })
+ onOpenChange(false)
+ // Apply a changed admin language by reloading in the new language.
+ const code = values.selected_locale
+ if (code && code !== i18n.language) switchLocale(code)
+ } catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
+ toast.error(err instanceof Error ? err.message : t('admin.errors.failed_to_update_profile'))
+ }
+ }
+
+ // Admin-UI language options come from the dashboard's own shipped locale
+ // bundles (see getAvailableUiLocales) — NOT the backend. The picker is hidden
+ // when fewer than two languages are installed (nothing to choose).
+ const localeOptions = useMemo(
+ () => getAvailableUiLocales().map((l) => ({ value: l.code, label: l.name })),
+ [],
+ )
+ const showLanguagePicker = localeOptions.length >= 2
+
+ const { errors, isDirty, isSubmitting } = form.formState
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)} className="contents">
+ <DialogBody className="flex flex-col gap-4">
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <ImageUploadField
+ square
+ serverUrl={me.user.avatar_url}
+ label={t('admin.fields.profile.avatar.label')}
+ help={t('admin.fields.profile.avatar.help')}
+ value={{
+ signedId: form.watch('avatar_signed_id'),
+ previewUrl: form.watch('avatar_preview_url'),
+ cleared: form.watch('avatar_cleared'),
+ }}
+ onChange={(next) => {
+ form.setValue('avatar_signed_id', next.signedId, { shouldDirty: true })
+ form.setValue('avatar_preview_url', next.previewUrl, { shouldDirty: true })
+ form.setValue('avatar_cleared', next.cleared, { shouldDirty: true })
+ }}
+ />
+ <Field>
+ <FieldLabel htmlFor="profile-email">{t('admin.fields.profile.email.label')}</FieldLabel>
+ {/* Email is identity-bound; PATCH /me does not accept it. */}
+ <Input id="profile-email" type="email" value={me.user.email} disabled />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="profile-first-name">
+ {t('admin.fields.profile.first_name.label')}
+ </FieldLabel>
+ <Input
+ id="profile-first-name"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="profile-last-name">
+ {t('admin.fields.profile.last_name.label')}
+ </FieldLabel>
+ <Input
+ id="profile-last-name"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[errors.last_name]} />
+ </Field>
+ {showLanguagePicker && (
+ <Controller
+ name="selected_locale"
+ control={form.control}
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel htmlFor="profile-language">
+ {t('admin.fields.profile.selected_locale.label')}
+ </FieldLabel>
+ <Select
+ items={localeOptions as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger
+ id="profile-language"
+ aria-invalid={!!fieldState.error || undefined}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {localeOptions.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError errors={[fieldState.error]} />
+ </Field>
+ )}
+ />
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ {/* Gated on `isDirty` to match `FormActions` (what the page this
+ replaced used) — without it a pristine Save PATCHes and toasts
+ success having changed nothing. */}
+ <Button type="submit" size="sm" disabled={!isDirty || isSubmitting}>
+ {isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ )
+}
diff --git a/packages/dashboard/src/hooks/use-profile.ts b/packages/dashboard/src/hooks/use-profile.ts
index 95954007a5..368d66a7ae 100644
--- a/packages/dashboard/src/hooks/use-profile.ts
+++ b/packages/dashboard/src/hooks/use-profile.ts
@@ -1,19 +1,33 @@
import type { MeResponse, MeUpdateParams } from '@spree/admin-sdk'
import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
-import { useQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
-export function useProfile() {
+/**
+ * @param enabled Defer the request until it's needed. The edit-profile dialog
+ * is mounted on every store page but only fetches once it opens.
+ */
+export function useProfile(enabled = true) {
return useQuery({
queryKey: useResourceKey('profile'),
queryFn: () => adminClient.me.get(),
+ enabled,
})
}
export function useUpdateProfile() {
+ const queryClient = useQueryClient()
+ const profileKey = useResourceKey('profile')
+
return useResourceMutation<MeResponse, Error, MeUpdateParams>({
mutationFn: (params) => adminClient.me.update(params),
invalidate: [['profile']],
- successMessage: false, // the page toasts success itself
- errorMessage: false, // the page maps 422s inline via mapSpreeErrorsToForm
+ successMessage: false, // the dialog toasts success itself
+ errorMessage: false, // the dialog maps 422s inline via mapSpreeErrorsToForm
+ // Write the response into the cache instead of leaning on the invalidation
+ // alone. The dialog disables the profile query while closed, and an
+ // invalidated query with no enabled observer goes stale without refetching
+ // — so a reopen would otherwise render the pre-save profile (flashing back
+ // an avatar the admin just removed).
+ onSuccess: (updated) => queryClient.setQueryData(profileKey, updated),
})
}
diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.ts
index 2e9b272f52..3dc1cf6478 100644
--- a/packages/dashboard/src/routeTree.gen.ts
+++ b/packages/dashboard/src/routeTree.gen.ts
@@ -33,7 +33,6 @@ import { Route as SettingsStoreRouteImport } from './routes/_authenticated/$stor
import { Route as SettingsStockLocationsRouteImport } from './routes/_authenticated/$storeId/settings/stock-locations'
import { Route as SettingsStaffRouteImport } from './routes/_authenticated/$storeId/settings/staff'
import { Route as SettingsReasonsRouteImport } from './routes/_authenticated/$storeId/settings/reasons'
-import { Route as SettingsProfileRouteImport } from './routes/_authenticated/$storeId/settings/profile'
import { Route as SettingsProductTypesRouteImport } from './routes/_authenticated/$storeId/settings/product-types'
import { Route as SettingsPaymentMethodsRouteImport } from './routes/_authenticated/$storeId/settings/payment-methods'
import { Route as SettingsMarketsRouteImport } from './routes/_authenticated/$storeId/settings/markets'
@@ -189,11 +188,6 @@ const SettingsReasonsRoute = SettingsReasonsRouteImport.update({
path: '/reasons',
getParentRoute: () => SettingsRoute,
} as any)
-const SettingsProfileRoute = SettingsProfileRouteImport.update({
- id: '/profile',
- path: '/profile',
- getParentRoute: () => SettingsRoute,
-} as any)
const SettingsProductTypesRoute = SettingsProductTypesRouteImport.update({
id: '/product-types',
path: '/product-types',
@@ -407,7 +401,6 @@ export interface FileRoutesByFullPath {
'/$storeId/settings/markets': typeof SettingsMarketsRoute
'/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/$storeId/settings/profile': typeof SettingsProfileRoute
'/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/$storeId/settings/staff': typeof SettingsStaffRoute
'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -465,7 +458,6 @@ export interface FileRoutesByTo {
'/$storeId/settings/markets': typeof SettingsMarketsRoute
'/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/$storeId/settings/profile': typeof SettingsProfileRoute
'/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/$storeId/settings/staff': typeof SettingsStaffRoute
'/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -527,7 +519,6 @@ export interface FileRoutesById {
'/_authenticated/$storeId/settings/markets': typeof SettingsMarketsRoute
'/_authenticated/$storeId/settings/payment-methods': typeof SettingsPaymentMethodsRoute
'/_authenticated/$storeId/settings/product-types': typeof SettingsProductTypesRoute
- '/_authenticated/$storeId/settings/profile': typeof SettingsProfileRoute
'/_authenticated/$storeId/settings/reasons': typeof SettingsReasonsRoute
'/_authenticated/$storeId/settings/staff': typeof SettingsStaffRoute
'/_authenticated/$storeId/settings/stock-locations': typeof SettingsStockLocationsRoute
@@ -589,7 +580,6 @@ export interface FileRouteTypes {
| '/$storeId/settings/markets'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/product-types'
- | '/$storeId/settings/profile'
| '/$storeId/settings/reasons'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -647,7 +637,6 @@ export interface FileRouteTypes {
| '/$storeId/settings/markets'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/product-types'
- | '/$storeId/settings/profile'
| '/$storeId/settings/reasons'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -708,7 +697,6 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/settings/markets'
| '/_authenticated/$storeId/settings/payment-methods'
| '/_authenticated/$storeId/settings/product-types'
- | '/_authenticated/$storeId/settings/profile'
| '/_authenticated/$storeId/settings/reasons'
| '/_authenticated/$storeId/settings/staff'
| '/_authenticated/$storeId/settings/stock-locations'
@@ -911,13 +899,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsReasonsRouteImport
parentRoute: typeof SettingsRoute
}
- '/_authenticated/$storeId/settings/profile': {
- id: '/_authenticated/$storeId/settings/profile'
- path: '/profile'
- fullPath: '/$storeId/settings/profile'
- preLoaderRoute: typeof SettingsProfileRouteImport
- parentRoute: typeof SettingsRoute
- }
'/_authenticated/$storeId/settings/product-types': {
id: '/_authenticated/$storeId/settings/product-types'
path: '/product-types'
@@ -1170,7 +1151,6 @@ interface SettingsRouteChildren {
SettingsMarketsRoute: typeof SettingsMarketsRoute
SettingsPaymentMethodsRoute: typeof SettingsPaymentMethodsRoute
SettingsProductTypesRoute: typeof SettingsProductTypesRoute
- SettingsProfileRoute: typeof SettingsProfileRoute
SettingsReasonsRoute: typeof SettingsReasonsRoute
SettingsStaffRoute: typeof SettingsStaffRoute
SettingsStockLocationsRoute: typeof SettingsStockLocationsRoute
@@ -1193,7 +1173,6 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsMarketsRoute: SettingsMarketsRoute,
SettingsPaymentMethodsRoute: SettingsPaymentMethodsRoute,
SettingsProductTypesRoute: SettingsProductTypesRoute,
- SettingsProfileRoute: SettingsProfileRoute,
SettingsReasonsRoute: SettingsReasonsRoute,
SettingsStaffRoute: SettingsStaffRoute,
SettingsStockLocationsRoute: SettingsStockLocationsRoute,
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId.tsx
index 6a76b9da40..eaba875c96 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId.tsx
@@ -10,8 +10,9 @@ import {
} from '@spree/dashboard-core'
import { SidebarInset, SidebarProvider } from '@spree/dashboard-ui'
import { createFileRoute, Outlet, useRouterState } from '@tanstack/react-router'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { CommandPalette } from '../../components/spree/command-palette/command-palette'
+import { ProfileDialog } from '../../components/spree/profile-dialog'
import { getAvailableUiLocales } from '../../i18n-setup'
// Derived once from the shipped locale bundles — stable for the app lifetime.
@@ -51,6 +52,10 @@ function StoreLayout() {
*/
function StoreShell({ inSettings }: { inSettings: boolean }) {
useAutoCollapseSidebar(inSettings)
+ // The profile is edited in a dialog rather than a page, so the shell owns its
+ // open state — the trigger sits in the TopBar's user menu, which is mounted
+ // here and stays put across route changes.
+ const [profileOpen, setProfileOpen] = useState(false)
return (
<>
@@ -61,7 +66,8 @@ function StoreShell({ inSettings }: { inSettings: boolean }) {
<SidebarInset className="flex-row">
<SettingsSidebar open={inSettings} />
<div className="flex min-w-0 flex-1 flex-col">
- <TopBar uiLocales={UI_LOCALES} />
+ <TopBar uiLocales={UI_LOCALES} onEditProfile={() => setProfileOpen(true)} />
+ <ProfileDialog open={profileOpen} onOpenChange={setProfileOpen} />
{inSettings ? (
<Outlet />
) : (
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx
deleted file mode 100644
index 6810f12420..0000000000
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/profile.tsx
+++ /dev/null
@@ -1,289 +0,0 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { type MeResponse, SpreeError } from '@spree/admin-sdk'
-import {
- ImageUploadField,
- i18n,
- mapSpreeErrorsToForm,
- PageHeader,
- switchLocale,
- useAuth,
-} from '@spree/dashboard-core'
-import {
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- ErrorState,
- Field,
- FieldError,
- FieldGroup,
- FieldLabel,
- FormActions,
- Input,
- ResourceLayout,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Skeleton,
- useFormSubmitShortcut,
-} from '@spree/dashboard-ui'
-import { createFileRoute } from '@tanstack/react-router'
-import { useEffect, useMemo } from 'react'
-import {
- type Control,
- Controller,
- type FieldPath,
- type FieldValues,
- useForm,
-} from 'react-hook-form'
-import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
-import { useProfile, useUpdateProfile } from '../../../../hooks/use-profile'
-import { getAvailableUiLocales } from '../../../../i18n-setup'
-import { type MeFormValues, meFormSchema, meToForm, meToParams } from '../../../../schemas/me'
-
-export const Route = createFileRoute('/_authenticated/$storeId/settings/profile')({
- component: ProfilePage,
-})
-
-// The language the dashboard is currently displaying — persisted in
-// localStorage and applied by i18next at boot. Used as the profile language
-// fallback when the account has no saved `selected_locale`, so the picker
-// reflects what the user actually sees (and a save persists it) instead of
-// initializing to an empty value that matches no option and renders blank.
-function currentUiLocale(): string {
- const available = getAvailableUiLocales().map((l) => l.code)
- const active = i18n.resolvedLanguage ?? i18n.language
- return active && available.includes(active) ? active : 'en'
-}
-
-function ProfilePage() {
- const { t } = useTranslation()
- const { data: me, isLoading, error, refetch } = useProfile()
-
- // Check error first: a failed fetch leaves `me` undefined, which would
- // otherwise render the skeleton forever instead of the error state.
- if (error) {
- return (
- <ErrorState
- title={t('admin.pages.profile.load_failed_title')}
- description={error instanceof Error ? error.message : undefined}
- onRetry={() => refetch()}
- />
- )
- }
-
- if (isLoading || !me) {
- return (
- <div className="flex flex-col gap-6">
- <Skeleton className="h-8 w-48" />
- <Skeleton className="h-64 w-full" />
- </div>
- )
- }
-
- // Mount the form only once `me` is loaded so `useForm` initializes with
- // concrete string defaults — keeps the inputs/Select controlled from the
- // first render.
- return <ProfileForm me={me} />
-}
-
-function ProfileForm({ me }: { me: MeResponse }) {
- const { t } = useTranslation()
- const { updateUser } = useAuth()
- const updateMutation = useUpdateProfile()
-
- const form = useForm<MeFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(meFormSchema) as any,
- defaultValues: meToForm(me, currentUiLocale()),
- })
-
- // Re-baseline from the refetched profile after a save (e.g. to surface the
- // newly-persisted avatar_url as the server image), unless the admin has
- // unsaved edits in flight.
- useEffect(() => {
- if (form.formState.isDirty) return
- form.reset(meToForm(me, currentUiLocale()))
- }, [me, form])
-
- // Release the picked avatar's object URL when it's replaced or the page
- // unmounts. ImageUploadField hands the blob URL to the form (its caller), so
- // the form owns revoking it — otherwise form.reset() (re-baseline above) or a
- // navigate-away drops it without freeing the blob. Double-revokes (the field
- // also revokes on replace/remove) are harmless no-ops.
- const avatarPreviewUrl = form.watch('avatar_preview_url')
- useEffect(() => {
- if (!avatarPreviewUrl) return
- return () => URL.revokeObjectURL(avatarPreviewUrl)
- }, [avatarPreviewUrl])
-
- const onSubmit = async (values: MeFormValues) => {
- try {
- const updated = await updateMutation.mutateAsync(meToParams(values))
- // Reflect the new name/locale/avatar in the auth context (top-bar, etc.)
- // immediately instead of waiting for the next token refresh.
- updateUser(updated.user)
- toast.success(t('admin.messages.profile_updated'))
- // Reset FIRST so the form is no longer dirty — otherwise the language
- // switch below reloads the page while the `beforeunload` dirty-guard is
- // still armed, triggering the browser's "unsaved changes" prompt. Drop the
- // consumed signed_id so a second save can't re-attach it, but KEEP
- // avatar_cleared: forcing it false here would make the field fall back to
- // the still-cached (stale) avatar_url and briefly re-show a just-removed
- // photo. The re-hydrate effect resets it once the profile refetch lands.
- form.reset({ ...values, avatar_signed_id: null })
- // Apply a changed admin language by reloading in the new language.
- const code = values.selected_locale
- if (code && code !== i18n.language) switchLocale(code)
- } catch (err) {
- if (mapSpreeErrorsToForm(err, form.setError)) return
- if (err instanceof SpreeError) throw err
- toast.error(err instanceof Error ? err.message : t('admin.errors.failed_to_update_profile'))
- }
- }
-
- useFormSubmitShortcut(form, onSubmit)
-
- // Admin-UI language options come from the dashboard's own shipped locale
- // bundles (see getAvailableUiLocales) — NOT the backend. The picker is hidden
- // when fewer than two languages are installed (nothing to choose).
- const localeOptions = useMemo(
- () => getAvailableUiLocales().map((l) => ({ value: l.code, label: l.name })),
- [],
- )
- const showLanguagePicker = localeOptions.length >= 2
-
- const { errors } = form.formState
-
- return (
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <ResourceLayout
- header={
- <PageHeader
- title={t('admin.pages.profile.title')}
- subtitle={t('admin.pages.profile.subtitle')}
- actions={<FormActions form={form} />}
- />
- }
- main={
- <>
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.pages.profile.personal_details')}</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <ImageUploadField
- square
- serverUrl={me.user.avatar_url}
- label={t('admin.fields.profile.avatar.label')}
- help={t('admin.fields.profile.avatar.help')}
- value={{
- signedId: form.watch('avatar_signed_id'),
- previewUrl: form.watch('avatar_preview_url'),
- cleared: form.watch('avatar_cleared'),
- }}
- onChange={(next) => {
- form.setValue('avatar_signed_id', next.signedId, { shouldDirty: true })
- form.setValue('avatar_preview_url', next.previewUrl, { shouldDirty: true })
- form.setValue('avatar_cleared', next.cleared, { shouldDirty: true })
- }}
- />
- <Field>
- <FieldLabel htmlFor="profile-email">
- {t('admin.fields.profile.email.label')}
- </FieldLabel>
- {/* Email is identity-bound; PATCH /me does not accept it. */}
- <Input id="profile-email" type="email" value={me.user.email} disabled />
- </Field>
- <Field>
- <FieldLabel htmlFor="profile-first-name">
- {t('admin.fields.profile.first_name.label')}
- </FieldLabel>
- <Input
- id="profile-first-name"
- aria-invalid={!!errors.first_name || undefined}
- {...form.register('first_name')}
- />
- <FieldError errors={[errors.first_name]} />
- </Field>
- <Field>
- <FieldLabel htmlFor="profile-last-name">
- {t('admin.fields.profile.last_name.label')}
- </FieldLabel>
- <Input
- id="profile-last-name"
- aria-invalid={!!errors.last_name || undefined}
- {...form.register('last_name')}
- />
- <FieldError errors={[errors.last_name]} />
- </Field>
- {showLanguagePicker && (
- <SelectField
- id="profile-language"
- label={t('admin.fields.profile.selected_locale.label')}
- name="selected_locale"
- control={form.control}
- options={localeOptions}
- />
- )}
- </FieldGroup>
- </CardContent>
- </Card>
- </>
- }
- />
- </form>
- )
-}
-
-interface SelectFieldProps<TValues extends FieldValues> {
- id: string
- label: string
- placeholder?: string
- name: FieldPath<TValues>
- control: Control<TValues>
- options: ReadonlyArray<{ value: string; label: string }>
-}
-
-function SelectField<TValues extends FieldValues>({
- id,
- label,
- placeholder,
- name,
- control,
- options,
-}: SelectFieldProps<TValues>) {
- return (
- <Controller
- name={name}
- control={control}
- render={({ field, fieldState }) => (
- <Field>
- <FieldLabel htmlFor={id}>{label}</FieldLabel>
- <Select items={options as never} value={field.value} onValueChange={field.onChange}>
- <SelectTrigger id={id} aria-invalid={!!fieldState.error || undefined}>
- <SelectValue placeholder={placeholder} />
- </SelectTrigger>
- <SelectContent>
- {options.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FieldError errors={[fieldState.error]} />
- </Field>
- )}
- />
- )
-}