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.

Added a profile dialog to the seller panel

Damian Legawiecee3f002feaa7
diff --git a/packages/seller-dashboard/src/components/account-dialog.tsx b/packages/seller-dashboard/src/components/account-dialog.tsx
new file mode 100644
index 0000000000..812fe6e57d
--- /dev/null
+++ b/packages/seller-dashboard/src/components/account-dialog.tsx
@@ -0,0 +1,270 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+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,
+ toastManager,
+} from '@spree/dashboard-ui'
+import type { MeResponse } from '@spree/seller-sdk'
+import { useEffect, useMemo } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useAccount, useUpdateAccount } from '../hooks/use-account'
+import { getAvailableUiLocales } from '../i18n'
+import {
+ type AccountFormValues,
+ accountFormSchema,
+ accountToForm,
+ accountToParams,
+} from '../schemas/account'
+
+// The language the panel is currently displaying — persisted in localStorage
+// and applied by i18next at boot. Used as the fallback when the account has no
+// saved `selected_locale`, so the picker reflects what the person actually
+// sees (and a save persists it) rather than starting empty and matching no
+// option.
+function currentUiLocale(): string {
+ const available = getAvailableUiLocales().map((locale) => locale.code)
+ const active = i18n.resolvedLanguage ?? i18n.language
+ return active && available.includes(active) ? active : 'en'
+}
+
+/**
+ * Edit-account dialog for the signed-in person — their name, photo and the
+ * panel's language. Opened from the sidebar's account menu; it has no page of
+ * its own.
+ *
+ * Not to be confused with the profile page, which is the seller business they
+ * act for. This is theirs, and follows them between sellers.
+ */
+export function AccountDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ // Mounted on every page of the panel; don't fetch until it opens.
+ const { data: me, isLoading, error, refetch } = useAccount(open)
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('account.title')}</DialogTitle>
+ <DialogDescription>{t('account.subtitle')}</DialogDescription>
+ </DialogHeader>
+ {error ? (
+ <DialogBody>
+ <ErrorState
+ title={t('account.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 the account has loaded, so `useForm`
+ // initializes with concrete string defaults — that keeps the inputs
+ // and the Select controlled from their first render.
+ <AccountForm me={me} onOpenChange={onOpenChange} />
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function AccountForm({
+ me,
+ onOpenChange,
+}: {
+ me: MeResponse
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { updateUser } = useAuth()
+ const updateMutation = useUpdateAccount()
+
+ const form = useForm<AccountFormValues>({
+ resolver: zodResolver(accountFormSchema),
+ defaultValues: accountToForm(me, currentUiLocale()),
+ })
+
+ // Re-baseline from the refetched account after a save (to surface the
+ // newly-persisted photo as the server image), unless there are unsaved
+ // edits in flight.
+ useEffect(() => {
+ if (form.formState.isDirty) return
+ form.reset(accountToForm(me, currentUiLocale()))
+ }, [me, form])
+
+ // Release the picked photo's object URL when it is replaced or the dialog
+ // unmounts. `ImageUploadField` hands the blob URL to the form, so the form
+ // owns revoking it — otherwise a `reset` (the re-baseline above) or a close
+ // drops the reference without freeing the blob. Double revokes are harmless.
+ const avatarPreviewUrl = form.watch('avatar_preview_url')
+ useEffect(() => {
+ if (!avatarPreviewUrl) return
+ return () => URL.revokeObjectURL(avatarPreviewUrl)
+ }, [avatarPreviewUrl])
+
+ const onSubmit = async (values: AccountFormValues) => {
+ try {
+ const updated = await updateMutation.mutateAsync(accountToParams(values))
+ // Reflect the new name and photo in the auth context (the sidebar's
+ // account row) straight away, rather than waiting for a token refresh.
+ updateUser(updated.user)
+ toastManager.add({ type: 'success', title: t('account.saved') })
+ // Closing unmounts the form, so the avatar state needs no preserving
+ // across the save — reopening re-hydrates from the mutation response
+ // that `useUpdateAccount` writes into the cache.
+ form.reset({ ...values, avatar_signed_id: null })
+ onOpenChange(false)
+ // A changed language takes effect by reloading in it.
+ const code = values.selected_locale
+ if (code && code !== i18n.language) switchLocale(code)
+ } catch (err) {
+ // Anything that is not a field error has already been toasted by the
+ // mutation hook.
+ mapSpreeErrorsToForm(err, form.setError)
+ }
+ }
+
+ // The panel's own shipped locale bundles, not the backend — those are what
+ // it can actually display. Hidden when fewer than two are installed, since
+ // there is then nothing to choose.
+ const localeOptions = useMemo(
+ () => getAvailableUiLocales().map((locale) => ({ value: locale.code, label: locale.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-destructive text-sm" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <ImageUploadField
+ square
+ serverUrl={me.user.avatar_url}
+ label={t('account.avatar')}
+ help={t('account.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="account-email">{t('account.email')}</FieldLabel>
+ {/* Email is identity-bound; PATCH /me does not accept it. */}
+ <Input id="account-email" type="email" value={me.user.email} disabled />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="account-first-name">{t('account.first_name')}</FieldLabel>
+ <Input
+ id="account-first-name"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="account-last-name">{t('account.last_name')}</FieldLabel>
+ <Input
+ id="account-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="account-language">{t('account.language')}</FieldLabel>
+ <Select
+ items={localeOptions as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger
+ id="account-language"
+ aria-invalid={!!fieldState.error || undefined}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {localeOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldError errors={[fieldState.error]} />
+ </Field>
+ )}
+ />
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isSubmitting}
+ >
+ {t('common.cancel')}
+ </Button>
+ {/* Gated on `isDirty`: without it a pristine Save sends a PATCH and
+ toasts success having changed nothing. */}
+ <Button type="submit" disabled={!isDirty || isSubmitting}>
+ {isSubmitting ? t('account.saving') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ )
+}
diff --git a/packages/seller-dashboard/src/hooks/use-account.ts b/packages/seller-dashboard/src/hooks/use-account.ts
new file mode 100644
index 0000000000..a0de9eb231
--- /dev/null
+++ b/packages/seller-dashboard/src/hooks/use-account.ts
@@ -0,0 +1,49 @@
+import { useResourceMutation } from '@spree/dashboard-core'
+import type { AccountUpdateParams, MeResponse } from '@spree/seller-sdk'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { sellerClient } from '../api-client'
+
+/**
+ * The signed-in person's own account.
+ *
+ * Keyed without the seller, unlike almost everything else in this panel: the
+ * account is the same record whichever seller they are acting for, so scoping
+ * it per seller would refetch it on every switch and cache the same answer
+ * several times over.
+ *
+ * @param enabled Defer the request until it is needed. The dialog is mounted
+ * on every page of the panel but only fetches once it opens.
+ */
+export function useAccount(enabled = true) {
+ return useQuery({
+ queryKey: ACCOUNT_KEY,
+ queryFn: () => sellerClient().me.get(),
+ enabled,
+ })
+}
+
+export function useUpdateAccount() {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+
+ return useResourceMutation<MeResponse, Error, AccountUpdateParams>({
+ mutationFn: (params) => sellerClient().me.update(params),
+ // The person is also a row on the team page, so their own name and photo
+ // there go stale on a self-edit unless that list is refetched. The hook
+ // injects the seller at position 1, which is what the team page keys on.
+ invalidate: [['seller', 'team']],
+ successMessage: false, // the dialog toasts success itself
+ // Field-level 422s never toast — the dialog shows them inline — so this
+ // covers everything else: a refusal, a server error, a lost connection.
+ errorMessage: t('account.save_failed'),
+ // Write the response into the cache rather than leaning on invalidation
+ // alone: the query is disabled while the dialog is closed, and an
+ // invalidated query with no enabled observer goes stale without
+ // refetching — so reopening would render the pre-save account, flashing
+ // back a photo that was just removed.
+ onSuccess: (updated) => queryClient.setQueryData(ACCOUNT_KEY, updated),
+ })
+}
+
+const ACCOUNT_KEY = ['seller-account'] as const
diff --git a/packages/seller-dashboard/src/i18n.ts b/packages/seller-dashboard/src/i18n.ts
index 0f7a2f52a5..000028947a 100644
--- a/packages/seller-dashboard/src/i18n.ts
+++ b/packages/seller-dashboard/src/i18n.ts
@@ -10,7 +10,7 @@ import '@spree/dashboard-core/lib/i18n'
// The instance comes from core too, not a bare `i18next` import: a bundled
// build can resolve a second copy of the package, and `addResourceBundle` on
// that one throws. Core re-exports the object it initialised for exactly this.
-import { i18n } from '@spree/dashboard-core'
+import { i18n, localesFromBundlePaths, setUiLocales } from '@spree/dashboard-core'
import en from './locales/en.json'
/**
@@ -23,4 +23,31 @@ import en from './locales/en.json'
*/
i18n.addResourceBundle('en', 'translation', en, true, true)
+// Every other language, imported EAGERLY so the active one registers
+// synchronously at module load — before any table or registry module
+// evaluates its `i18n.t(...)` labels. Switching language reloads the page, so
+// only the booted language's strings are ever resolved; eager keeps that
+// resolution synchronous and flash-free.
+const panelLocales = import.meta.glob<{ default: Record<string, unknown> }>(
+ ['./locales/*.json', '!./locales/en.json'],
+ { eager: true },
+)
+
+for (const [path, mod] of Object.entries(panelLocales)) {
+ const code = path.replace('./locales/', '').replace('.json', '')
+ i18n.addResourceBundle(code, 'translation', mod.default, true, true)
+}
+
+setUiLocales(getAvailableUiLocales().map(({ code }) => code))
+
+/**
+ * The languages this panel can display, as `{ code, name }` pairs for the
+ * account menu and the account dialog. Derived from the locale bundles the
+ * panel ships — not from the API, which knows nothing about what the client
+ * can render.
+ */
+export function getAvailableUiLocales(): Array<{ code: string; name: string }> {
+ return localesFromBundlePaths(Object.keys(panelLocales))
+}
+
export default i18n
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 9b5893d204..3ec506315d 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -12,6 +12,20 @@
"subtitle": "You were invited as {{email}}. Set a password to finish.",
"title": "Join the team"
},
+ "account": {
+ "avatar": "Photo",
+ "avatar_help": "Shown next to your name across the panel. Square images look best.",
+ "email": "Email",
+ "first_name": "First name",
+ "language": "Language",
+ "last_name": "Last name",
+ "load_failed_title": "Couldn't load your profile",
+ "save_failed": "Couldn't save your profile",
+ "saved": "Profile updated",
+ "saving": "Saving…",
+ "subtitle": "Manage your personal details and panel language.",
+ "title": "Profile"
+ },
"admin": {
"actions": {
"actions_menu": "Actions",
diff --git a/packages/seller-dashboard/src/panel-chrome.tsx b/packages/seller-dashboard/src/panel-chrome.tsx
index b30ad86a1e..5635aafff0 100644
--- a/packages/seller-dashboard/src/panel-chrome.tsx
+++ b/packages/seller-dashboard/src/panel-chrome.tsx
@@ -1,7 +1,12 @@
import { AppShell, AppShellProvider, TenantProvider } from '@spree/dashboard-core'
import { useParams, useRouterState } from '@tanstack/react-router'
-import type { ReactNode } from 'react'
+import { type ReactNode, useState } from 'react'
+import { AccountDialog } from './components/account-dialog'
import { SellerSwitcher } from './components/seller-switcher'
+import { getAvailableUiLocales } from './i18n'
+
+// Derived once from the shipped locale bundles — stable for the panel's life.
+const UI_LOCALES = getAvailableUiLocales()
/**
* The panel's frame: the nav rail, and the page as a sheet beside it.
@@ -20,6 +25,10 @@ export function PanelChrome({ children }: { children: ReactNode }) {
const inSettings = useRouterState({
select: (state) => state.location.pathname.startsWith(`/${sellerId}/settings`),
})
+ // The account is edited in a dialog rather than on a page, so the frame owns
+ // its open state — the trigger sits in the sidebar's account menu, which is
+ // mounted here and stays put across route changes.
+ const [accountOpen, setAccountOpen] = useState(false)
return (
// Scopes every shared query key to this seller, the way `StoreProvider`
@@ -27,7 +36,14 @@ export function PanelChrome({ children }: { children: ReactNode }) {
// survive a switch and be shown under the next seller.
<TenantProvider id={sellerId}>
<AppShellProvider>
- <AppShell tenantId={sellerId} sidebarHeader={<SellerSwitcher />} inSettings={inSettings}>
+ <AppShell
+ tenantId={sellerId}
+ sidebarHeader={<SellerSwitcher />}
+ inSettings={inSettings}
+ uiLocales={UI_LOCALES}
+ onEditProfile={() => setAccountOpen(true)}
+ >
+ <AccountDialog open={accountOpen} onOpenChange={setAccountOpen} />
{children}
</AppShell>
</AppShellProvider>
diff --git a/packages/seller-dashboard/src/schemas/account.ts b/packages/seller-dashboard/src/schemas/account.ts
new file mode 100644
index 0000000000..9b983b0ec5
--- /dev/null
+++ b/packages/seller-dashboard/src/schemas/account.ts
@@ -0,0 +1,49 @@
+import { accountFormToParams, isUiLocale } from '@spree/dashboard-core'
+import type { AccountUpdateParams, MeResponse } from '@spree/seller-sdk'
+import { z } from 'zod/v4'
+
+// The signed-in person's own account (PATCH /me) — not the seller business
+// they act for, which is `pages/profile.tsx`. Every field is optional: the
+// panel asks for a name but does not require one.
+//
+// The panel's languages are NOT listed here. They are derived at render time
+// from the locale bundles the panel ships (see `getAvailableUiLocales`), which
+// is what it can actually display — the API knows nothing about that.
+//
+// The avatar is a small state machine: untouched (omit on save), uploaded
+// (send the signed id), or cleared (send null to purge). `avatar_signed_id`
+// carries a freshly direct-uploaded blob, `avatar_preview_url` a transient
+// object URL for the just-picked file, and `avatar_cleared` flags a removal of
+// the persisted photo.
+export const accountFormSchema = z.object({
+ first_name: z.string().nullable().optional(),
+ last_name: z.string().nullable().optional(),
+ selected_locale: z.string().nullable().optional(),
+ avatar_signed_id: z.string().nullable(),
+ avatar_preview_url: z.string().nullable(),
+ avatar_cleared: z.boolean(),
+})
+
+export type AccountFormValues = z.infer<typeof accountFormSchema>
+
+/** Hydrate the form from the current account (the `/me` response). */
+export function accountToForm(me: MeResponse, fallbackLocale: string): AccountFormValues {
+ return {
+ first_name: me.user.first_name ?? '',
+ last_name: me.user.last_name ?? '',
+ // A language saved from another panel may not be one this panel ships;
+ // preselecting it would show a raw code and save it straight back.
+ selected_locale:
+ me.user.selected_locale && isUiLocale(me.user.selected_locale)
+ ? me.user.selected_locale
+ : fallbackLocale,
+ avatar_signed_id: null,
+ avatar_preview_url: null,
+ avatar_cleared: false,
+ }
+}
+
+/** Map the form to the PATCH /me params (drops the frontend-only fields). */
+export function accountToParams(values: AccountFormValues): AccountUpdateParams {
+ return accountFormToParams(values)
+}