Skip to documentation

Design system / Sources & standards

Current repository source

memberManager.tsx

src/components/members/memberManager.tsx

This view contains the escaped source read during the deployment build. Code and policy text are unchanged. Markdown is shown as source, not rendered as a document. A new deployment refreshes the content.

"use client";

import { useCallback, useId, useRef, useState, type ReactNode } from "react";
import { ArrowRight, CircleCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Text } from "@/components/ui/text";
import { Alert } from "@/components/ui/alert";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { MemberCounts } from "./memberCounts";
import { MemberInvitationField } from "./member-invitation-field";
import { MemberDirectorySheet } from "./memberDirectorySheet";
import { useMemberDirectory } from "./use-member-directory";
import type { MemberFilter } from "./member-directory-model";
import type { MemberEntry, MemberManagerConfig } from "./types";
import { permitsMemberRemoval, type MemberManagementCapabilities } from "@/lib/auth/member-management-contract";

type MemberManagerProps = {
  members: MemberEntry[];
  config: MemberManagerConfig;
  capabilities: MemberManagementCapabilities;
  newInput: string;
  saving: boolean;
  error: string | null;
  inputInvalid?: boolean;
  actionError?: string | null;
  actionNotice?: string | null;
  description?: string;
  notice?: string | null;
  /** Increment only when an invitation operation acknowledges new additions. */
  additionVersion?: number;
  loading?: boolean;
  loadError?: string | null;
  onRetryLoad?: () => void;
  renderMemberActions?: (member: MemberEntry, index: number) => ReactNode;
  renderMemberBody?: (member: MemberEntry, index: number) => ReactNode;
  removeLabel?: (member: MemberEntry, index: number) => string;
  children?: ReactNode;
  removeConfirm?: { email: string; affectedEditions?: Array<{ editionId: string; editionTitle: string | null }> } | null;
  setNewInput: (value: string) => void;
  onAdd: () => void | Promise<void>;
  onRemove?: (email: string, index: number) => Promise<void>;
  onConfirmRemove?: () => void;
  onCancelRemove?: () => void;
};

/** Members-owned organism. Product instances retain mutation, identity and access policy. */
export function MemberManager({ members, config, capabilities, newInput, saving, error, inputInvalid = false, actionError, actionNotice, description, notice, additionVersion = 0,
  loading = false, loadError, onRetryLoad, renderMemberActions, renderMemberBody, removeLabel, children,
  removeConfirm, setNewInput, onAdd, onRemove, onConfirmRemove, onCancelRemove }: MemberManagerProps) {
  const id = useId();
  const directory = useMemberDirectory(members);
  const opener = useRef<HTMLElement | null>(null);
  const additionAtOpen = useRef(additionVersion);
  const viewButton = useRef<HTMLButtonElement>(null);
  const directoryHeading = useRef<HTMLHeadingElement>(null);
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
  const setOwner = useCallback((owner: HTMLElement | null) => {
    setPortalContainer(owner?.closest<HTMLElement>("[data-tenant-theme]") ?? null);
  }, []);
  const Heading = config.headingLevel === 2 ? "h2" : "h3";
  const disabled = saving || loading || Boolean(loadError);
  function showDirectory(filter: MemberFilter | null, trigger: HTMLElement) {
    opener.current = trigger;
    additionAtOpen.current = additionVersion;
    if (filter) directory.show(filter);
    else directory.setOpen(true);
  }
  const invite = <section aria-labelledby={`${id}-invite`} className="flex min-w-0 flex-col gap-4">
    <h3 id={`${id}-invite`} className="text-body font-semibold">Invite {config.memberTypeLabelPlural}</h3>
    <MemberInvitationField id={id} config={config} value={newInput} disabled={disabled} saving={saving}
      error={error} inputInvalid={inputInvalid} onChange={setNewInput} onAdd={onAdd}>{children}</MemberInvitationField>
  </section>;
  const invitationFeedback = notice && <Alert role="status" aria-label="Invitation result" className="border-success/40 bg-success-muted text-success-muted-foreground">
      <CircleCheck aria-hidden="true" />
      <Text variant="supporting">{notice}</Text>
    </Alert>;
  const invited = <div className="space-y-2">
    <div data-slot="member-summary" className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">
      <MemberCounts counts={directory.counts} unavailable={loading || Boolean(loadError)} highlightVersion={additionVersion} onSelect={(filter, trigger) => showDirectory(filter, trigger)} />
      <Button ref={viewButton} type="button" variant="outline" size="sm" className="pointer-coarse:min-h-11" onClick={(event) => showDirectory(null, event.currentTarget)}>
        Manage invitees <ArrowRight className="size-4" aria-hidden="true" />
      </Button>
    </div>
    {loading && <Text variant="supporting" role="status">Loading invitees...</Text>}
    {loadError && <div className="space-y-2"><Text variant="supporting" role="alert">{loadError}</Text>
      {onRetryLoad && <Button type="button" variant="outline" onClick={onRetryLoad}>Try again</Button>}
    </div>}
    {!loading && !loadError && !members.length && <Text variant="supporting" className="text-text-muted">{config.emptyMessage}</Text>}
  </div>;

  const confirmation = onConfirmRemove && onCancelRemove && <AlertDialog open={Boolean(removeConfirm)} onOpenChange={(open) => !open && onCancelRemove()}>
      <AlertDialogContent container={portalContainer} onCloseAutoFocus={(event) => {
        if (directory.open) { event.preventDefault(); directoryHeading.current?.focus(); }
      }}>
        <AlertDialogHeader>
          <AlertDialogTitle>Remove {config.memberTypeLabel}</AlertDialogTitle>
          <AlertDialogDescription asChild><div>
            Are you sure you want to remove <strong>{removeConfirm?.email}</strong>?
            {removeConfirm?.affectedEditions && removeConfirm.affectedEditions.length > 0 && <div className="mt-3 space-y-2">
              <p className="font-medium text-destructive">This person is an {config.memberTypeLabel} on {removeConfirm.affectedEditions.length} Edition{removeConfirm.affectedEditions.length === 1 ? "" : "s"}:</p>
              <ul className="list-disc space-y-0.5 pl-5">{removeConfirm.affectedEditions.map((edition) => <li key={edition.editionId}>{edition.editionTitle ?? "Unknown Edition"}</li>)}</ul>
              <p className="pt-1">Removing them will also remove their access to these Editions.</p>
            </div>}
          </div></AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={onCancelRemove}>Cancel</AlertDialogCancel>
          <AlertDialogAction onClick={onConfirmRemove} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Remove</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>;

  if (!capabilities.canRead) return null;
  return <section ref={setOwner} aria-labelledby={`${id}-title`} className="min-w-0 space-y-2">
    <Heading id={`${id}-title`} className="text-supporting font-semibold">{config.title ?? `Invited ${config.memberTypeLabelPlural}`}</Heading>
    {invited}
    <MemberDirectorySheet directory={directory} config={config} saving={saving} loading={loading} loadError={loadError}
      onRetry={onRetryLoad} error={actionError ?? null} notice={actionNotice}
      description={description} invitation={capabilities.canInvite ? invite : undefined} invitationFeedback={invitationFeedback}
      highlightVersion={additionVersion > additionAtOpen.current ? additionVersion : 0}
      renderMemberActions={capabilities.canEditCategories || capabilities.canExclude ? renderMemberActions : undefined}
      renderMemberBody={renderMemberBody}
      onRemove={capabilities.canRemove ? onRemove : undefined} removeLabel={removeLabel}
      canRemoveMember={(member) => member.canRemove !== false && !member.linkageUnknown && permitsMemberRemoval(capabilities, member.userId)}
      headingRef={directoryHeading}
      portalContainer={portalContainer}
      onRestoreFocus={() => (opener.current?.isConnected ? opener.current : viewButton.current)?.focus({ preventScroll: true })}>
      {/* Keep the confirmation inside the Sheet's React event/focus boundary,
          while Radix portals both surfaces into the same owning theme scope. */}
      {capabilities.canRemove && confirmation}
    </MemberDirectorySheet>
    {!directory.open && capabilities.canRemove && confirmation}
  </section>;
}
All sources and standards
Current components and theme tokens. Fictional example data. Source views refresh on deployment; authors maintain contract notes.