Skip to content

Invite people

Emails as chips, a role with what it allows, and a seat count, in one dialog.

344 lines · React · Tailwind 4

Install

$ bunx shadcn@latest add @blocco/invite-people

Code

blocks/free/invite-people.tsx344 lines
import {
  forwardRef,
  useId,
  useRef,
  useState,
  type ClipboardEvent,
  type FormEvent,
  type KeyboardEvent,
} from "react";
import { Button } from "@/registry/blocco/ui/button";
import { Dialog } from "@/registry/blocco/ui/dialog";
import { NO_AUTOFILL } from "@/registry/blocco/ui/field";
import { Link, UserPlus, X } from "@/registry/blocco/ui/icons";
import { MenuSelect } from "@/registry/blocco/ui/menu";
import { OverflowTip } from "@/registry/blocco/ui/overflow-tip";
import { BusyContent } from "@/registry/blocco/ui/spinner";
import { Tooltip } from "@/registry/blocco/ui/tooltip";
import { useToast } from "@/registry/blocco/ui/toast";
import { cn } from "@/registry/blocco/ui/cn";

const ROLES = ["viewer", "member", "admin"] as const;
type Role = (typeof ROLES)[number];

const ROLE_OPTIONS = [
  { value: "viewer", label: "Viewer" },
  { value: "member", label: "Member" },
  { value: "admin", label: "Admin" },
];

/** What each role can do, said once, where the role is chosen. Without it
 * "viewer" and "member" look like the same word twice. */
const ROLE_HINT = {
  viewer: "Viewers see links and analytics, and change nothing.",
  member: "Members create and edit links and see analytics.",
  admin: "Admins manage links, domains and members.",
} satisfies Record<Role, string>;

const SEATS_LEFT: number = 3;

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isEmail = (text: string) => EMAIL_RE.test(text);
const splitEmails = (text: string) =>
  text
    .split(/[\s,;]+/)
    .map((e) => e.trim())
    .filter(Boolean);

function unique(list: string[]): string[] {
  const seen = new Set<string>();
  return list.filter((e) => {
    const key = e.toLowerCase();
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

function Chip({ email, bad, onRemove }: { email: string; bad: boolean; onRemove: () => void }) {
  return (
    <span
      className={cn(
        "inline-flex h-7 max-w-full items-center gap-1 rounded-md bg-surface-2 pr-0.5 pl-2",
        bad && "text-danger shadow-[inset_0_0_0_1px_var(--danger)]",
      )}
    >
      <OverflowTip content={email}>
        <span className="truncate font-mono text-xs">{email}</span>
      </OverflowTip>
      <button
        type="button"
        aria-label={`Remove ${email}`}
        onClick={onRemove}
        className="relative grid size-6 shrink-0 cursor-pointer place-items-center rounded-[5px] text-muted transition-[background-color,color] duration-150 [@media(hover:hover)]:hover:bg-surface [@media(hover:hover)]:hover:text-text"
      >
        <X size={12} />
      </button>
    </span>
  );
}

/**
 * Several addresses in one box: each becomes a chip as soon as a comma, a
 * space or Enter ends it, and a pasted list splits into chips at once.
 * Backspace in the empty input takes the last chip back out to edit.
 *
 * Built to sit where a Field would: the label row carries the reason on the
 * right when something is wrong, and nothing below the box moves.
 */
const EmailChips = forwardRef<
  HTMLInputElement,
  {
    label: string;
    emails: string[];
    onChange: (emails: string[]) => void;
    /** The text not yet turned into a chip, owned by the caller so a submit can count it too. */
    draft: string;
    onDraftChange: (draft: string) => void;
    error?: string;
    placeholder?: string;
  }
>(({ label, emails, onChange, draft, onDraftChange, error, placeholder }, ref) => {
  const inputId = useId();
  const reasonId = useId();
  const [focused, setFocused] = useState(false);

  const commit = (text: string) => {
    const next = splitEmails(text);
    if (next.length === 0) return;
    onChange(unique([...emails, ...next]));
    onDraftChange("");
  };

  const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if ((e.key === "," || e.key === ";" || e.key === " " || e.key === "Enter") && draft.trim()) {
      e.preventDefault();
      commit(draft);
      return;
    }
    if (e.key === "Backspace" && !draft && emails.length > 0) {
      e.preventDefault();
      onChange(emails.slice(0, -1));
      onDraftChange(emails[emails.length - 1]);
    }
  };

  const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
    const text = e.clipboardData.getData("text");
    if (splitEmails(text).length < 2) return;
    e.preventDefault();
    commit(`${draft} ${text}`);
  };

  return (
    <div className="min-w-0">
      <span className="mb-1.5 flex h-4 items-center gap-1.5 text-xs text-muted">
        <label htmlFor={inputId}>{label}</label>
        {error && (
          <OverflowTip content={error}>
            <span id={reasonId} className="ml-auto truncate text-danger">
              {error}
            </span>
          </OverflowTip>
        )}
      </span>
      {/* Clicking anywhere in the box puts the caret in the input, as a real field would. */}
      <div
        role="presentation"
        onClick={(e) => {
          if (e.target === e.currentTarget)
            document.getElementById(inputId)?.focus({ preventScroll: true });
        }}
        className={cn(
          "flex min-h-[76px] w-full cursor-text flex-wrap content-start items-center gap-1.5 rounded-lg bg-surface p-2 transition-[box-shadow] duration-150",
          focused
            ? "shadow-[0_0_0_1.5px_var(--accent),0_0_0_4px_color-mix(in_oklab,var(--accent)_25%,transparent)]"
            : error
              ? "shadow-[0_0_0_1.5px_var(--danger)]"
              : "smooth-shadow-ring-xs",
        )}
      >
        {emails.map((email) => (
          <Chip
            key={email}
            email={email}
            bad={Boolean(error) && !isEmail(email)}
            onRemove={() => onChange(emails.filter((e) => e !== email))}
          />
        ))}
        <input
          ref={ref}
          id={inputId}
          type="text"
          inputMode="email"
          autoComplete="off"
          // Teammates' addresses, not the user's own.
          {...NO_AUTOFILL}
          autoCapitalize="none"
          spellCheck={false}
          autoFocus
          value={draft}
          onChange={(e) => {
            const value = e.target.value;
            // A comma typed on a phone keyboard arrives here, not as a key.
            if (/[,;\s]$/.test(value)) commit(value);
            else onDraftChange(value);
          }}
          onKeyDown={onKeyDown}
          onPaste={onPaste}
          onFocus={() => setFocused(true)}
          onBlur={() => {
            setFocused(false);
            commit(draft);
          }}
          aria-invalid={error ? true : undefined}
          aria-describedby={error ? reasonId : undefined}
          placeholder={emails.length === 0 ? placeholder : "Add more, separated by commas"}
          className="h-7 min-w-[12rem] flex-1 bg-transparent px-1 font-mono text-[13px] text-text outline-none! placeholder:font-sans placeholder:text-sm placeholder:text-placeholder"
        />
      </div>
    </div>
  );
});
EmailChips.displayName = "EmailChips";

const sendLabel = (count: number) => (count > 1 ? `Send ${count} invites` : "Send invite");

/** Why the addresses cannot go yet, or undefined when they can. Short, for the label row. */
function emailsError(emails: string[]): string | undefined {
  if (emails.length === 0) return "Add an email";
  const bad = emails.filter((e) => !isEmail(e));
  if (bad.length === 1) return `Not an email: ${bad[0]}`;
  if (bad.length > 1) return `${bad.length} are not emails`;
  if (emails.length > SEATS_LEFT)
    return SEATS_LEFT === 1 ? "Only 1 seat free" : `Only ${SEATS_LEFT} seats free`;
  return undefined;
}

function seatsLine(count: number): string {
  const seats = SEATS_LEFT === 1 ? "seat" : "seats";
  return count === 0
    ? `${SEATS_LEFT} free ${seats} on your plan.`
    : `${count} of ${SEATS_LEFT} free ${seats} on your plan.`;
}

/** Any number of addresses at once, or a single-use link for the same role. */
export function InvitePeopleDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const toast = useToast();
  const input = useRef<HTMLInputElement>(null);
  const [emails, setEmails] = useState<string[]>([]);
  const [draft, setDraft] = useState("");
  const [role, setRole] = useState<Role>("member");
  const [error, setError] = useState<string | undefined>();
  const [sending, setSending] = useState(false);
  const all = [...emails, ...splitEmails(draft)];

  const close = (next: boolean) => {
    onOpenChange(next);
    if (!next) {
      setEmails([]);
      setDraft("");
      setError(undefined);
    }
  };

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (sending) return;
    const reason = emailsError(all);
    setEmails(all);
    setDraft("");
    setError(reason);
    if (reason) {
      input.current?.focus();
      return;
    }
    setSending(true);
    await new Promise((r) => setTimeout(r, 600));
    setSending(false);
    toast(all.length > 1 ? `${all.length} invites sent` : "Invite sent");
    close(false);
  };

  return (
    <Dialog open={open} onOpenChange={close} title="Invite people" size="lg">
      <form onSubmit={submit} noValidate className="flex flex-col gap-4">
        <EmailChips
          ref={input}
          label="Emails"
          emails={emails}
          onChange={(next) => {
            setEmails(next);
            setError(undefined);
          }}
          draft={draft}
          onDraftChange={(next) => {
            setDraft(next);
            setError(undefined);
          }}
          error={error}
          placeholder="teammate@company.com"
        />
        <div className="grid items-center gap-x-4 gap-y-1.5 sm:grid-cols-2">
          <div>
            <span className="mb-1.5 block text-xs text-muted">Role</span>
            <MenuSelect
              label="Role"
              value={role}
              onChange={(next) => setRole(ROLES.find((r) => r === next) ?? role)}
              options={ROLE_OPTIONS}
            />
          </div>
          <p className="text-xs text-pretty text-muted sm:pt-5">{ROLE_HINT[role]}</p>
        </div>
        <p className="tnum text-xs text-muted">{seatsLine(all.length)}</p>
        <div className="flex flex-wrap items-center gap-2 pt-1">
          <Tooltip content="Makes a single-use link, valid 7 days, and copies it">
            <Button
              type="button"
              variant="ghost"
              className="mr-auto pl-2.5"
              onClick={() => {
                void navigator.clipboard?.writeText(
                  `https://acme.test/invite/${crypto.randomUUID().slice(0, 12)}`,
                );
                toast("Invite link copied");
              }}
            >
              <span className="inline-flex items-center gap-1.5">
                <Link size={15} aria-hidden /> Copy invite link
              </span>
            </Button>
          </Tooltip>
          <Button type="button" variant="ghost" onClick={() => close(false)}>
            Cancel
          </Button>
          <Button type="submit" variant="primary" disabled={sending}>
            <BusyContent busy={sending}>{sendLabel(all.length)}</BusyContent>
          </Button>
        </div>
      </form>
    </Dialog>
  );
}

/** A button that opens the invite dialog. */
export default function InvitePeople() {
  const [open, setOpen] = useState(false);
  return (
    <section className="mx-auto flex min-h-[20rem] max-w-md flex-col items-center justify-center gap-4 px-6 py-16 text-center">
      <p className="text-sm text-muted">7 of 10 seats used on the Pro plan.</p>
      <Button variant="primary" onClick={() => setOpen(true)}>
        <UserPlus size={15} aria-hidden /> Invite people
      </Button>
      <InvitePeopleDialog open={open} onOpenChange={setOpen} />
    </section>
  );
}