Access requests

Who gets into a workspace, on a raised page: requests to approve with a role or decline, one by one or in an action bar, invitations to resend or revoke, and the people blocked, each answer undoable from its toast.

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-access-requests

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

Installed with this block
  • action-bar
  • app-shell
  • avatar
  • block-styles
  • breadcrumbs
  • button
  • checkbox
  • divider
  • dropdown-menu
  • form-field
  • icon-button
  • illustration
  • list-item
  • modal
  • popup
  • select
  • sidebar
  • split-button
  • status-badge
  • table
  • tabs
  • text-input
  • toast
  • utils
blocks/wideset/access-requests/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 { Tabs } from '@/components/ui/wideset/tabs/Tabs';
import { Toast } from '@/components/ui/wideset/toast/Toast';
import { ToastProvider, useToast } from '@/components/ui/wideset/toast/Toast.context';
import { useId, useState } from 'react';

import { BlockDialog } from './block-dialog';
import { BlockedTable } from './blocked-table';
import {
  type AccessRequest,
  account,
  blocked as initialBlocked,
  invitations as initialInvitations,
  NOW,
  requests as initialRequests,
  type Role,
  roleLabel,
  workspace,
} from './data';
import { InvitationsTable } from './invitations-table';
import { InviteDialog } from './invite-dialog';
import { PageHeader } from './page-header';
import { RequestsTable } from './requests-table';
import { SelectionBar } from './selection-bar';
import { AccessSidebar } 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 Tab = 'requests' | 'invitations' | 'blocked';

/** "a member", "an admin"; several people take the plural. */
const asRole = (role: Role, count: number) => {
  const label = roleLabel(role).toLowerCase();
  if (count > 1) return `${label}s`;
  return `${role === 'admin' ? 'an' : 'a'} ${label}`;
};

/**
 * The page inside the card, under the toasts: it holds the three lists and the seats taken, so
 * every answer moves a person out of a list and says so in a toast with Undo.
 */
function AccessPage() {
  const { showToast, dismissToast } = useToast();
  const [tab, setTab] = useState<Tab>('requests');
  const [requests, setRequests] = useState(initialRequests);
  const [invitations, setInvitations] = useState(initialInvitations);
  const [blocked, setBlocked] = useState(initialBlocked);
  const [seatsUsed, setSeatsUsed] = useState(workspace.members);
  const [selected, setSelected] = useState<string[]>([]);
  const [inviting, setInviting] = useState(false);
  // The person stays while the dialog closes, so its words do not vanish under the fade.
  const [blocking, setBlocking] = useState<{ person: AccessRequest; open: boolean }>();

  /** A toast whose Undo puts back what the action changed. */
  const toastWithUndo = (content: string, undo: () => void) => {
    const id = showToast({
      content,
      action: (
        <Toast.Action
          preset="ghost"
          onClick={() => {
            undo();
            dismissToast(id);
          }}
        >
          Undo
        </Toast.Action>
      ),
    });
  };

  /** Takes requests out of the list (and the selection); returns how to put them back. */
  const remove = (ids: string[]) => {
    const before = requests;
    const gone = before.filter((request) => ids.includes(request.id));
    setRequests((current) => current.filter((request) => !ids.includes(request.id)));
    setSelected((current) => current.filter((id) => !ids.includes(id)));
    return {
      gone,
      // Puts back only these requests, in their old places; what changed since stays changed.
      restore: () =>
        setRequests((current) =>
          before.filter((request) => current.includes(request) || gone.includes(request)),
        ),
    };
  };

  const approve = (ids: string[], role: Role) => {
    const { gone, restore } = remove(ids);
    setSeatsUsed((seats) => seats + gone.length);
    const who = gone.length === 1 ? gone[0].name : `${gone.length} people`;
    toastWithUndo(`${who} joined as ${asRole(role, gone.length)}`, () => {
      restore();
      setSeatsUsed((seats) => seats - gone.length);
    });
  };

  const decline = (ids: string[]) => {
    const { gone, restore } = remove(ids);
    toastWithUndo(
      gone.length === 1
        ? `Request from ${gone[0].name} declined`
        : `${gone.length} requests declined`,
      restore,
    );
  };

  const block = (person: AccessRequest, reason: string) => {
    const { restore } = remove([person.id]);
    const { id, name, initials, email } = person;
    setBlocked((current) => [
      { id, name, initials, email, reason, blockedBy: account.name, blocked: NOW.toISOString() },
      ...current,
    ]);
    toastWithUndo(`${name} declined and blocked`, () => {
      restore();
      setBlocked((current) => current.filter((entry) => entry.id !== id));
    });
  };

  return (
    <div className={cn(COLUMN, 'gap-ws-12 pt-ws-14 pb-ws-16 flex flex-col')}>
      <PageHeader onInvite={() => setInviting(true)} quiet={inviting || Boolean(blocking?.open)} />

      <Tabs value={tab} onValueChange={(value) => setTab(value as Tab)} className="gap-ws-9">
        <Tabs.List aria-label="Access" className="w-full">
          <Tabs.Item value="requests">
            <Tabs.Label>Requests</Tabs.Label>
          </Tabs.Item>
          <Tabs.Item value="invitations">
            <Tabs.Label>Invitations</Tabs.Label>
          </Tabs.Item>
          <Tabs.Item value="blocked">
            <Tabs.Label>Blocked</Tabs.Label>
          </Tabs.Item>
        </Tabs.List>

        <Tabs.Content value="requests">
          <RequestsTable
            rows={requests}
            seatsUsed={seatsUsed}
            selected={selected}
            onSelectedChange={setSelected}
            onApprove={approve}
            onDecline={decline}
            onBlock={(person) => setBlocking({ person, open: true })}
          />
        </Tabs.Content>
        <Tabs.Content value="invitations">
          <InvitationsTable
            rows={invitations}
            onInvite={() => setInviting(true)}
            onResend={(invitation) => {
              setInvitations(
                invitations.map((i) =>
                  i.id === invitation.id ? { ...i, sent: NOW.toISOString() } : i,
                ),
              );
              showToast({
                status: 'success',
                content: `Invitation sent again to ${invitation.email}`,
              });
            }}
            onRevoke={(invitation) => {
              const before = invitations;
              setInvitations(invitations.filter((i) => i.id !== invitation.id));
              toastWithUndo(`Invitation to ${invitation.email} revoked`, () =>
                setInvitations(before),
              );
            }}
          />
        </Tabs.Content>
        <Tabs.Content value="blocked">
          <BlockedTable
            rows={blocked}
            onUnblock={(person) => {
              const before = blocked;
              setBlocked(blocked.filter((p) => p.id !== person.id));
              toastWithUndo(`${person.name} unblocked`, () => setBlocked(before));
            }}
          />
        </Tabs.Content>
      </Tabs>

      <SelectionBar
        // The bar answers requests, so it shows only on their tab.
        count={tab === 'requests' ? selected.length : 0}
        seatsUsed={seatsUsed}
        onClear={() => setSelected([])}
        onApprove={(role) => approve(selected, role)}
        onDecline={() => decline(selected)}
      />
      <InviteDialog
        open={inviting}
        onOpenChange={setInviting}
        invited={invitations.map((i) => i.email)}
        blocked={blocked.map((p) => p.email)}
        onInvite={(email, role) => {
          setInvitations((invitations) => [
            { id: email, email, role, invitedBy: account.name, sent: NOW.toISOString() },
            ...invitations,
          ]);
          setTab('invitations');
          showToast({ status: 'success', content: `Invitation sent to ${email}` });
        }}
      />
      {blocking && (
        <BlockDialog
          person={blocking.person}
          open={blocking.open}
          onOpenChange={(open) => setBlocking({ ...blocking, open })}
          onBlock={(reason) => block(blocking.person, reason)}
        />
      )}
    </div>
  );
}

/**
 * Access requests (Inset direction): who gets into the workspace, on the raised page beside the
 * workspace sidebar with Members open. Three tabs split the ways in: requests to approve (after
 * picking a role) or decline, one by one or selected together; invitations to resend or revoke;
 * and the people who are blocked. Inviting is the page's one filled button.
 */
export default function AccessRequests() {
  const sidebarId = useId();
  const [collapsed, setCollapsed] = useState(false);

  return (
    <ToastProvider>
      <AppShell className="ws-block-utility" direction="inset">
        <AccessSidebar 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="#settings">Settings</a>
                </Breadcrumbs.Item>
                <Breadcrumbs.Item asChild>
                  <a href="#members">Members</a>
                </Breadcrumbs.Item>
                <Breadcrumbs.Item>Access</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">
            <AccessPage />
          </div>
        </AppShell.Main>
      </AppShell>
    </ToastProvider>
  );
}