Send payment

Sending a payment on a raised page: one narrow card that is the form, then the review before anything moves, then the receipt, with recent transfers beside it and a confirmation only above a stated limit.

Open full screen

Inset · Sidebar. <AppShell direction="inset">, the default: the navigation on the grey app frame, the page a raised white card inside it, scrolling within.

npx wideset add block-send-payment

Import the default export from @/blocks/wideset/send-payment. The files below are relative to your project's source directory.

Installed with this block
  • app-shell
  • avatar
  • block-styles
  • breadcrumbs
  • button
  • card
  • date-picker
  • divider
  • dropdown-menu
  • form-field
  • icon-button
  • list-item
  • radio-button
  • select
  • sidebar
  • status-badge
  • status-modal
  • text-input
  • utils
blocks/wideset/send-payment/index.tsx
'use client';

import '@/styles/wideset-blocks.css';

import { RiSideBarLine } from '@remixicon/react';
import { AppShell } from '@/components/ui/wideset/app-shell/AppShell';
import { Breadcrumbs } from '@/components/ui/wideset/breadcrumbs/Breadcrumbs';
import { cn } from '@/lib/wideset/utils';
import { IconButton } from '@/components/ui/wideset/button/IconButton';
import { StatusBadge } from '@/components/ui/wideset/status-badge/StatusBadge';
import { useEffect, useId, useRef, useState } from 'react';

import { ConfirmDialog } from './confirm-dialog';
import { nextTransferId, recentTransfers, recipientById, type Transfer, workspace } from './data';
import { formatDate, formatUsd } from './format';
import {
  draftPayment,
  emptyPayment,
  type PaymentErrors,
  type PaymentValues,
  summarizePayment,
  validatePaymentForm,
} from './payment';
import { PaymentForm } from './payment-form';
import { PaymentReceipt } from './payment-receipt';
import { PaymentReview } from './payment-review';
import { RecentTransfers } from './recent-transfers';
import { SendPaymentSidebar } from './sidebar';

/** One column of the page: the header and the body share its edges. */
const COLUMN = 'px-ws-14 mx-auto w-full max-w-[80rem]';

type Step = 'form' | 'review' | 'receipt';

/**
 * Send payment (Inset direction): one payment on the raised page beside the workspace sidebar,
 * in three steps that share one narrow card: the form, the review before anything moves, and the
 * receipt the page becomes. The recent transfers stand beside it as text. The screen holds the
 * payment, so going back keeps what was typed. A dialog demonstrates the confirmation step.
 */
export default function SendPayment() {
  const formId = useId();
  const sidebarId = useId();
  const [collapsed, setCollapsed] = useState(false);

  const [step, setStep] = useState<Step>('form');
  const [values, setValues] = useState<PaymentValues>(draftPayment);
  const [errors, setErrors] = useState<PaymentErrors>({});
  const [confirming, setConfirming] = useState(false);
  const [sending, setSending] = useState(false);

  const summary = summarizePayment(values);
  const recipient = recipientById(values.recipientId)?.name ?? '';
  const amount = formatUsd(summary.amount);

  // Each step replaces the last one in place, so focus moves to the title that names it.
  const title = useRef<HTMLHeadingElement>(null);
  const shown = useRef(step);
  useEffect(() => {
    if (shown.current !== step) title.current?.focus();
    shown.current = step;
  }, [step]);

  const change = (patch: Partial<PaymentValues>) => {
    setValues((current) => ({ ...current, ...patch }));
    // A field stops being in error the moment it is changed; it is checked again on submit.
    setErrors((current) => ({
      ...current,
      ...Object.fromEntries(Object.keys(patch).map((field) => [field, undefined])),
    }));
  };

  const review = () => {
    const found = validatePaymentForm(values);
    setErrors(found);
    const [first] = Object.keys(found);
    if (first) document.getElementById(`${formId}-${first}`)?.focus();
    else setStep('review');
  };

  // Cleared on unmount, so the stand-in request never lands on a closed screen.
  const timer = useRef<number>(undefined);
  useEffect(() => () => window.clearTimeout(timer.current), []);

  // A timeout stands in for the transfer; a real screen awaits it and, when it is refused, stays
  // on the review and says why.
  const send = () => {
    setConfirming(false);
    setSending(true);
    timer.current = window.setTimeout(() => {
      setSending(false);
      setStep('receipt');
    }, 1200);
  };

  const status = summary.scheduled ? 'Scheduled' : 'Processing';
  const header = {
    form: {
      title: 'Send payment',
      line: `Pay a saved recipient from ${workspace.name}’s balance.`,
    },
    review: {
      title: 'Review payment',
      line: 'Check it over. Nothing moves until you send it.',
    },
    receipt: summary.scheduled
      ? {
          title: 'Payment scheduled',
          line: `${amount} goes to ${recipient} on ${formatDate(summary.sendDate)}.`,
        }
      : {
          title: 'Payment sent',
          line: `${amount} is on its way to ${recipient}.`,
        },
  }[step];

  const sent: Transfer = {
    id: nextTransferId,
    recipient,
    date: summary.sendDate,
    amount: summary.amount,
    status,
  };

  return (
    <AppShell className="ws-block-utility" direction="inset">
      <SendPaymentSidebar id={sidebarId} collapsed={collapsed} onCollapsedChange={setCollapsed} />
      <AppShell.Main>
        <div className="h-ws-18 border-ws-static-base flex shrink-0 items-center border-b">
          {/* The bar belongs to the surround: it runs edge to edge. The sidebar's toggle is pulled
              left so its glyph, not its box, sits 20px from the edge; the crumbs follow it. */}
          <div className="gap-ws-5 px-ws-11 flex w-full items-center">
            <IconButton
              icon={RiSideBarLine}
              variant="secondary"
              preset="ghost"
              size="sm"
              iconClassName="text-ws-static-subtle size-ws-9"
              aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
              aria-expanded={!collapsed}
              aria-controls={sidebarId}
              onClick={() => setCollapsed((collapsed) => !collapsed)}
              className="-ml-ws-5"
            />
            <Breadcrumbs separator="arrow">
              <Breadcrumbs.Item asChild>
                <a href="#payouts">Payouts</a>
              </Breadcrumbs.Item>
              <Breadcrumbs.Item>Send payment</Breadcrumbs.Item>
            </Breadcrumbs>
          </div>
        </div>

        {/* The page scrolls inside the card, so the card's corners stay put. */}
        <div className="ws-scrollbar min-h-0 flex-1 overflow-y-auto">
          <div className={cn(COLUMN, 'gap-ws-12 pt-ws-14 pb-ws-16 flex flex-col')}>
            <header className="gap-ws-2 flex flex-col">
              <div className="gap-ws-7 flex items-center">
                <h1
                  ref={title}
                  tabIndex={-1}
                  className="typography-title-md text-ws-static-strong outline-none"
                >
                  {header.title}
                </h1>
                {/* Processing and Scheduled are lifecycle states, so the badge stays neutral. */}
                {step === 'receipt' && <StatusBadge size="lg">{status}</StatusBadge>}
              </div>
              <p className="typography-body-md text-ws-static-subtle tabular-nums">{header.line}</p>
            </header>

            <div className="gap-ws-18 grid grid-cols-1 items-start lg:grid-cols-[minmax(0,38rem)_18rem]">
              {step === 'form' && (
                <PaymentForm
                  id={formId}
                  values={values}
                  errors={errors}
                  onChange={change}
                  onSubmit={review}
                />
              )}
              {step === 'review' && (
                <PaymentReview
                  values={values}
                  summary={summary}
                  sending={sending}
                  onBack={() => setStep('form')}
                  onSend={() => setConfirming(true)}
                />
              )}
              {step === 'receipt' && (
                <PaymentReceipt
                  values={values}
                  summary={summary}
                  transferId={nextTransferId}
                  onSendAnother={() => {
                    setValues(emptyPayment);
                    setStep('form');
                  }}
                />
              )}

              <RecentTransfers
                transfers={step === 'receipt' ? [sent, ...recentTransfers] : recentTransfers}
              />
            </div>
          </div>
        </div>
      </AppShell.Main>

      <ConfirmDialog
        open={confirming}
        onOpenChange={setConfirming}
        amount={summary.amount}
        recipient={recipient}
        scheduled={summary.scheduled}
        onConfirm={send}
      />
    </AppShell>
  );
}