# Store settings (店铺设置)

Settings page for a small online shop: store details, currency and tax, shipping zones and order notifications, with a save bar that appears on change.

- Ref: `component/store-settings` (component · forms)
- Page: https://uifino.com/en/components/forms/store-settings
- Markdown: https://uifino.com/md/components/store-settings.md
- Preview image: https://uifino.com/blocks/covers/store-settings-dark.webp

## Install

- shadcn: `npx shadcn@latest add "https://uifino.com/r/blocks/store-settings.json"`
- UIFino CLI: `npx uifino@latest add component/store-settings`

## Dependencies

`lucide-react`

## shadcn/ui components it builds on

- `button`, `card`, `field`, `input`, `radio-group`, `select`, `separator`, `skeleton`, `spinner`, `switch`, `textarea`. The shadcn CLI installs them together with the block.

## Theme

The block reads the project's shadcn theme variables, so it follows whatever DESIGN.md the project uses and needs no options of its own.
To give the project the look of a UIFino brand or style, install its theme: `npx shadcn@latest add "https://uifino.com/r/themes/medusa.json"`.

## Usage

The files under `examples/` show the block wired with content, including its loading, empty and error states where it has them.

## Files

| Path | Role | Size |
| :--- | :--- | ---: |
| components/blocks/store-settings/examples/content.ts | demo | 8.3 KB |
| components/blocks/store-settings/examples/default.tsx | demo | 495 B |
| components/blocks/store-settings/examples/error.tsx | demo | 549 B |
| components/blocks/store-settings/examples/loading.tsx | demo | 520 B |
| components/blocks/store-settings/examples/saving.tsx | demo | 637 B |
| components/blocks/store-settings/store-settings.tsx | source | 18.1 KB |

### components/blocks/store-settings/store-settings.tsx

```tsx
"use client";

import { type FormEvent, type ReactNode, useId, useRef, useState } from "react";
import { CircleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldContent, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";

export type StoreSettingsStatus = "ready" | "loading" | "saving" | "error";

export interface ShippingZoneValue {
  readonly id: string;
  readonly name: string;
  readonly price: string;
  readonly estimate: string;
}

export interface NotificationValue {
  readonly id: string;
  readonly label: string;
  readonly description: string;
  readonly enabled: boolean;
}

export interface StoreSettingsValues {
  readonly name: string;
  readonly email: string;
  readonly address: string;
  readonly currency: string;
  readonly taxInclusive: boolean;
  readonly zones: readonly ShippingZoneValue[];
  readonly processing: string;
  readonly notifications: readonly NotificationValue[];
}

export interface CurrencyOption {
  readonly code: string;
  readonly label: string;
}

export interface ProcessingOption {
  readonly value: string;
  readonly label: string;
  readonly description: string;
}

export interface StoreSettingsLabels {
  readonly title: string;
  readonly storeTitle: string;
  readonly storeDescription: string;
  readonly name: string;
  readonly email: string;
  readonly emailHelp: string;
  readonly address: string;
  readonly currencyTitle: string;
  readonly currencyDescription: string;
  readonly currency: string;
  readonly taxInclusive: string;
  readonly taxInclusiveHelp: string;
  readonly shippingTitle: string;
  readonly shippingDescription: string;
  readonly zonePrice: string;
  readonly zoneEstimate: string;
  readonly processing: string;
  readonly notificationsTitle: string;
  readonly notificationsDescription: string;
  readonly required: string;
  readonly emailInvalid: string;
  readonly priceInvalid: string;
  readonly unsaved: string;
  readonly discard: string;
  readonly save: string;
  readonly saving: string;
  readonly saveFailedTitle: (count: number) => string;
  readonly saveFailedDescription: string;
}

export interface StoreSettingsProps {
  readonly values: StoreSettingsValues;
  readonly currencies: readonly CurrencyOption[];
  readonly processingOptions: readonly ProcessingOption[];
  readonly labels: StoreSettingsLabels;
  readonly defaultDraft?: StoreSettingsValues;
  readonly status?: StoreSettingsStatus;
  readonly onSave?: (values: StoreSettingsValues) => void;
  readonly className?: string;
}

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PRICE_PATTERN = /^\d+(\.\d{1,2})?$/;

function validate(values: StoreSettingsValues, labels: StoreSettingsLabels): Record<string, string> {
  const errors: Record<string, string> = {};
  if (!values.name.trim()) errors.name = labels.required;
  if (!values.email.trim()) errors.email = labels.required;
  else if (!EMAIL_PATTERN.test(values.email.trim())) errors.email = labels.emailInvalid;
  if (!values.address.trim()) errors.address = labels.required;
  for (const zone of values.zones) {
    if (!PRICE_PATTERN.test(zone.price.trim())) errors[`price-${zone.id}`] = labels.priceInvalid;
    if (!zone.estimate.trim()) errors[`estimate-${zone.id}`] = labels.required;
  }
  return errors;
}

function serialize(values: StoreSettingsValues): string {
  return JSON.stringify(values);
}

const SKELETON_TONE = "bg-muted-foreground/15";

function FieldSkeleton({ className }: { className?: string }) {
  return (
    <div className={cn("flex flex-col gap-2", className)}>
      <Skeleton className={cn(SKELETON_TONE, "h-4 w-28")} />
      <Skeleton className={cn(SKELETON_TONE, "h-9 w-full")} />
    </div>
  );
}

function SwitchRowSkeleton() {
  return (
    <div className="flex items-center justify-between gap-4">
      <div className="flex flex-1 flex-col gap-2">
        <Skeleton className={cn(SKELETON_TONE, "h-4 w-32")} />
        <Skeleton className={cn(SKELETON_TONE, "h-4 w-3/4")} />
      </div>
      <Skeleton className={cn(SKELETON_TONE, "h-5 w-9 rounded-full")} />
    </div>
  );
}

function LoadingSettings({ className }: { className?: string }) {
  return (
    <div className={cn("@container flex w-full max-w-2xl flex-col gap-4", className)} aria-busy="true">
      <div className="flex items-center rounded-xl border bg-card px-4 py-3">
        <Skeleton className={cn(SKELETON_TONE, "h-6 w-24")} />
      </div>
      <Card>
        <CardHeader className="gap-2">
          <Skeleton className={cn(SKELETON_TONE, "h-5 w-32")} />
          <Skeleton className={cn(SKELETON_TONE, "h-4 w-64 max-w-full")} />
        </CardHeader>
        <CardContent className="flex flex-col gap-5">
          <div className="grid gap-5 @lg:grid-cols-2">
            <FieldSkeleton />
            <FieldSkeleton />
          </div>
          <Skeleton className={cn(SKELETON_TONE, "h-20 w-full")} />
        </CardContent>
      </Card>
      <Card>
        <CardHeader className="gap-2">
          <Skeleton className={cn(SKELETON_TONE, "h-5 w-24")} />
          <Skeleton className={cn(SKELETON_TONE, "h-4 w-72 max-w-full")} />
        </CardHeader>
        <CardContent className="flex flex-col gap-5">
          {Array.from({ length: 2 }, (_, index) => (
            <div key={index} className="grid gap-4 @lg:grid-cols-2">
              <FieldSkeleton />
              <FieldSkeleton />
            </div>
          ))}
        </CardContent>
      </Card>
      <div className="flex flex-col gap-5 px-1 pt-2">
        <Skeleton className={cn(SKELETON_TONE, "h-5 w-36")} />
        <SwitchRowSkeleton />
        <SwitchRowSkeleton />
      </div>
    </div>
  );
}

function PlainSection({
  title,
  description,
  children
}: {
  readonly title: string;
  readonly description: string;
  readonly children: ReactNode;
}) {
  return (
    <section className="flex flex-col gap-5 px-1">
      <div className="flex flex-col gap-1">
        <h2 className="font-heading text-base font-medium">{title}</h2>
        <p className="text-sm text-muted-foreground">{description}</p>
      </div>
      {children}
    </section>
  );
}

export function StoreSettings({
  values,
  currencies,
  processingOptions,
  labels,
  defaultDraft,
  status = "ready",
  onSave,
  className
}: StoreSettingsProps) {
  const id = useId();
  const [saved, setSaved] = useState(values);
  const [current, setCurrent] = useState(defaultDraft ?? values);
  const [attempted, setAttempted] = useState(false);
  const serializedValues = serialize(values);
  const [syncedValues, setSyncedValues] = useState(serializedValues);
  const formRef = useRef<HTMLFormElement>(null);

  if (serializedValues !== syncedValues) {
    setSyncedValues(serializedValues);
    setSaved(values);
    setCurrent(values);
    setAttempted(false);
  }

  if (status === "loading") {
    return <LoadingSettings className={className} />;
  }

  const saving = status === "saving";
  const dirty = serialize(current) !== serialize(saved);
  const showErrors = attempted || status === "error";
  const errors = showErrors ? validate(current, labels) : {};
  const errorCount = Object.keys(errors).length;
  const saveFailed = status === "error" || (attempted && errorCount > 0);

  const patch = (next: Partial<StoreSettingsValues>) => setCurrent((prev) => ({ ...prev, ...next }));
  const patchZone = (zoneId: string, next: Partial<ShippingZoneValue>) =>
    patch({ zones: current.zones.map((zone) => (zone.id === zoneId ? { ...zone, ...next } : zone)) });
  const patchNotification = (notificationId: string, enabled: boolean) =>
    patch({
      notifications: current.notifications.map((item) => (item.id === notificationId ? { ...item, enabled } : item))
    });

  const submit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (saving) return;
    setAttempted(true);
    if (Object.keys(validate(current, labels)).length > 0) {
      requestAnimationFrame(() => {
        const firstInvalid = formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]');
        firstInvalid?.scrollIntoView({ block: "center" });
        firstInvalid?.focus({ preventScroll: true });
      });
      return;
    }
    setSaved(current);
    onSave?.(current);
  };

  const discard = () => {
    setCurrent(saved);
    setAttempted(false);
  };

  return (
    <form ref={formRef} onSubmit={submit} noValidate className={cn("@container flex w-full max-w-2xl flex-col gap-4", className)}>
      <div className="sticky top-0 z-10 flex flex-col gap-3 rounded-xl border bg-card px-4 py-3 @lg:flex-row @lg:items-center @lg:justify-between">
        <div className="flex min-w-0 flex-col gap-1">
          <h1 className="truncate font-heading text-2xl font-medium">{labels.title}</h1>
          {saveFailed && (
            <div role="alert" className="flex gap-2 text-sm">
              <CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" aria-hidden="true" />
              <p className="text-pretty">
                <span className="font-medium text-destructive">{labels.saveFailedTitle(errorCount)}</span>{" "}
                <span className="text-muted-foreground">{labels.saveFailedDescription}</span>
              </p>
            </div>
          )}
        </div>
        {(dirty || saving || saveFailed) && (
          <div className="flex min-w-0 shrink-0 flex-wrap items-center gap-2 @lg:flex-nowrap">
            {!saveFailed && (
              <p className="basis-full text-sm text-pretty text-muted-foreground @lg:basis-auto">{labels.unsaved}</p>
            )}
            <Button type="button" variant="ghost" disabled={saving} onClick={discard} className="ml-auto">
              {labels.discard}
            </Button>
            <Button type="submit" disabled={saving} aria-busy={saving}>
              {saving && <Spinner />}
              {saving ? labels.saving : labels.save}
            </Button>
          </div>
        )}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{labels.storeTitle}</CardTitle>
          <CardDescription>{labels.storeDescription}</CardDescription>
        </CardHeader>
        <CardContent>
          <FieldGroup className="gap-5">
            <div className="grid gap-5 @lg:grid-cols-2">
              <Field data-invalid={Boolean(errors.name)}>
                <FieldLabel htmlFor={`${id}-name`}>{labels.name}</FieldLabel>
                <Input
                  id={`${id}-name`}
                  value={current.name}
                  aria-invalid={Boolean(errors.name)}
                  onChange={(event) => patch({ name: event.target.value })}
                />
                {errors.name && <FieldError>{errors.name}</FieldError>}
              </Field>
              <Field data-invalid={Boolean(errors.email)}>
                <FieldLabel htmlFor={`${id}-email`}>{labels.email}</FieldLabel>
                <Input
                  id={`${id}-email`}
                  type="email"
                  autoComplete="email"
                  value={current.email}
                  aria-invalid={Boolean(errors.email)}
                  onChange={(event) => patch({ email: event.target.value })}
                />
                {errors.email ? <FieldError>{errors.email}</FieldError> : <FieldDescription className="text-balance">{labels.emailHelp}</FieldDescription>}
              </Field>
            </div>
            <Field data-invalid={Boolean(errors.address)}>
              <FieldLabel htmlFor={`${id}-address`}>{labels.address}</FieldLabel>
              <Textarea
                id={`${id}-address`}
                rows={3}
                value={current.address}
                aria-invalid={Boolean(errors.address)}
                onChange={(event) => patch({ address: event.target.value })}
              />
              {errors.address && <FieldError>{errors.address}</FieldError>}
            </Field>
          </FieldGroup>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{labels.shippingTitle}</CardTitle>
          <CardDescription>{labels.shippingDescription}</CardDescription>
        </CardHeader>
        <CardContent>
          <FieldGroup className="gap-5">
            {current.zones.map((zone, index) => (
              <div key={zone.id} className="flex flex-col gap-5">
                {index > 0 && <Separator />}
                <div className="flex flex-col gap-4">
                  <p className="truncate font-heading text-base font-medium">{zone.name}</p>
                  <div className="grid gap-4 @lg:grid-cols-2">
                    <Field data-invalid={Boolean(errors[`price-${zone.id}`])}>
                      <FieldLabel htmlFor={`${id}-price-${zone.id}`} className="font-normal text-muted-foreground">{labels.zonePrice}</FieldLabel>
                      <div className="relative">
                        <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-muted-foreground">
                          {current.currency}
                        </span>
                        <Input
                          id={`${id}-price-${zone.id}`}
                          inputMode="decimal"
                          className="pl-12"
                          value={zone.price}
                          aria-invalid={Boolean(errors[`price-${zone.id}`])}
                          onChange={(event) => patchZone(zone.id, { price: event.target.value })}
                        />
                      </div>
                      {errors[`price-${zone.id}`] && <FieldError>{errors[`price-${zone.id}`]}</FieldError>}
                    </Field>
                    <Field data-invalid={Boolean(errors[`estimate-${zone.id}`])}>
                      <FieldLabel htmlFor={`${id}-estimate-${zone.id}`} className="font-normal text-muted-foreground">{labels.zoneEstimate}</FieldLabel>
                      <Input
                        id={`${id}-estimate-${zone.id}`}
                        value={zone.estimate}
                        aria-invalid={Boolean(errors[`estimate-${zone.id}`])}
                        onChange={(event) => patchZone(zone.id, { estimate: event.target.value })}
                      />
                      {errors[`estimate-${zone.id}`] && <FieldError>{errors[`estimate-${zone.id}`]}</FieldError>}
                    </Field>
                  </div>
                </div>
              </div>
            ))}
            <Separator />
            <Field>
              <FieldLabel>{labels.processing}</FieldLabel>
              <RadioGroup value={current.processing} onValueChange={(processing) => patch({ processing })} className="gap-3">
                {processingOptions.map((option) => (
                  <Field key={option.value} orientation="horizontal" className="items-start">
                    <RadioGroupItem value={option.value} id={`${id}-processing-${option.value}`} className="mt-0.5" />
                    <FieldContent>
                      <FieldLabel htmlFor={`${id}-processing-${option.value}`} className="font-medium">
                        {option.label}
                      </FieldLabel>
                      <FieldDescription className="text-balance">{option.description}</FieldDescription>
                    </FieldContent>
                  </Field>
                ))}
              </RadioGroup>
            </Field>
          </FieldGroup>
        </CardContent>
      </Card>

      <Separator />

      <PlainSection title={labels.currencyTitle} description={labels.currencyDescription}>
        <FieldGroup className="gap-5">
          <Field className="@lg:max-w-xs">
            <FieldLabel htmlFor={`${id}-currency`}>{labels.currency}</FieldLabel>
            <Select value={current.currency} onValueChange={(currency) => patch({ currency })}>
              <SelectTrigger id={`${id}-currency`} className="w-full">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {currencies.map((currency) => (
                  <SelectItem key={currency.code} value={currency.code}>
                    {currency.code} · {currency.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </Field>
          <Separator />
          <Field orientation="horizontal">
            <FieldContent>
              <FieldLabel htmlFor={`${id}-tax`}>{labels.taxInclusive}</FieldLabel>
              <FieldDescription className="text-balance">{labels.taxInclusiveHelp}</FieldDescription>
            </FieldContent>
            <Switch
              id={`${id}-tax`}
              checked={current.taxInclusive}
              onCheckedChange={(taxInclusive) => patch({ taxInclusive })}
            />
          </Field>
        </FieldGroup>
      </PlainSection>

      <Separator />

      <PlainSection title={labels.notificationsTitle} description={labels.notificationsDescription}>
        <FieldGroup className="gap-4">
          {current.notifications.map((item, index) => (
            <div key={item.id} className="flex flex-col gap-4">
              {index > 0 && <Separator />}
              <Field orientation="horizontal">
                <FieldContent>
                  <FieldLabel htmlFor={`${id}-notify-${item.id}`}>{item.label}</FieldLabel>
                  <FieldDescription className="text-balance">{item.description}</FieldDescription>
                </FieldContent>
                <Switch
                  id={`${id}-notify-${item.id}`}
                  checked={item.enabled}
                  onCheckedChange={(enabled) => patchNotification(item.id, enabled)}
                />
              </Field>
            </div>
          ))}
        </FieldGroup>
      </PlainSection>

    </form>
  );
}
```

Not inlined (5 files, 10.5 KB). Full sources: https://uifino.com/r/blocks/store-settings.json
