Device sessions

A settings card listing every device signed in to an account, with this device pinned first, an 'Online' dot or a live relative 'Seen' time, and the approximate place. Each row signs out on its own: a spinner appears only if the request takes longer than 150ms, the row collapses and fades on success, and stays with an inline error and Retry on failure. 'Sign out other devices' opens a small confirm popover (focus on Confirm, Escape to cancel) and the rows fold away in a quick stagger. Sessions from a new place or first seen today carry a 'New' or 'Unrecognised' tag with a 'Not you?' link, and a footer sums up the device count and the latest sign-in. Includes skeleton rows, per-device button names, focus that moves to the next row after a removal and polite announcements.

AuthenticationBlockTailwind v4

Source

import * as React from "react";
import { AlertTriangle, Laptop, Loader2, LogOut, Monitor, RotateCcw, ShieldAlert, Smartphone, Tablet } from "lucide-react";
import { cn } from "@/lib/utils";

export type DeviceKind = "laptop" | "phone" | "tablet" | "desktop";

export type DeviceSession = {
  id: string;
  kind: DeviceKind;
  /** Browser or app, e.g. "Firefox". */
  client: string;
  os: string;
  /** Approximate place, e.g. "Pune, India". */
  place: string;
  lastActive: Date | "now";
  /** The device viewing this page: pinned first, cannot be signed out here. */
  current?: boolean;
  /** "new": first seen today. "unrecognised": a place this account has not used before. */
  flagged?: "new" | "unrecognised";
};

export type DeviceSessionsProps = {
  sessions: DeviceSession[];
  onSignOut: (id: string) => Promise<unknown> | void;
  onSignOutOthers: () => Promise<unknown> | void;
  /** Shows a "Not you?" link on flagged sessions. */
  onReport?: (id: string) => void;
  loading?: boolean;
  title?: string;
  className?: string;
};

const ICONS: Record<DeviceKind, typeof Laptop> = { laptop: Laptop, phone: Smartphone, tablet: Tablet, desktop: Monitor };
const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card";
const LEAVE_MS = 320;
const SPINNER_DELAY = 150;

function useNow(interval = 45_000) {
  const [now, setNow] = React.useState(() => Date.now());
  React.useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), interval);
    return () => clearInterval(timer);
  }, [interval]);
  return now;
}

function since(date: Date, now: number) {
  const minutes = Math.max(0, Math.round((now - date.getTime()) / 60_000));
  if (minutes < 1) return "just now";
  if (minutes < 60) return `${minutes} min ago`;
  const hours = Math.round(minutes / 60);
  if (hours < 24) return `${hours} h ago`;
  const days = Math.round(hours / 24);
  if (days < 30) return `${days} d ago`;
  return date.toLocaleDateString(undefined, { day: "numeric", month: "short" });
}

const label = (session: DeviceSession) => `${session.client} on ${session.os}`;
const stamp = (session: DeviceSession) => (session.lastActive === "now" ? Number.MAX_SAFE_INTEGER : session.lastActive.getTime());

type RowState = { pending?: boolean; spinner?: boolean; error?: boolean; leaving?: boolean };

export function DeviceSessions({ sessions, onSignOut, onSignOutOthers, onReport, loading = false, title = "Signed-in devices", className }: DeviceSessionsProps) {
  const now = useNow();
  const headingId = React.useId();
  const confirmId = React.useId();
  const [rows, setRows] = React.useState<Record<string, RowState>>({});
  const [gone, setGone] = React.useState<Set<string>>(() => new Set());
  const [confirming, setConfirming] = React.useState(false);
  const [othersBusy, setOthersBusy] = React.useState(false);
  const [othersError, setOthersError] = React.useState(false);
  const [message, setMessage] = React.useState("");
  const buttons = React.useRef(new Map<string, HTMLButtonElement>());
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const confirmRef = React.useRef<HTMLButtonElement>(null);
  const popoverRef = React.useRef<HTMLDivElement>(null);
  const reduced = React.useRef(false);

  React.useEffect(() => {
    reduced.current = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  }, []);

  const visible = React.useMemo(
    () => sessions.filter((s) => !gone.has(s.id)).sort((a, b) => Number(!!b.current) - Number(!!a.current) || stamp(b) - stamp(a)),
    [sessions, gone],
  );
  const others = visible.filter((s) => !s.current);

  const patch = (id: string, next: RowState | null) =>
    setRows((prev) => {
      const copy = { ...prev };
      if (next) copy[id] = { ...copy[id], ...next };
      else delete copy[id];
      return copy;
    });

  /* After a row leaves, focus the next row's button (or the previous one, or the header action). */
  const moveFocusFrom = (id: string) => {
    const signable = visible.filter((s) => !s.current);
    const index = signable.findIndex((s) => s.id === id);
    const target = signable[index + 1] || signable[index - 1];
    const element = target && buttons.current.get(target.id);
    (element || triggerRef.current)?.focus();
  };

  const signOut = async (session: DeviceSession) => {
    if (rows[session.id]?.pending) return;
    const hadFocus = document.activeElement === buttons.current.get(session.id);
    patch(session.id, { pending: true, error: false });
    const timer = setTimeout(() => patch(session.id, { spinner: true }), SPINNER_DELAY);
    try {
      await onSignOut(session.id);
      clearTimeout(timer);
      if (hadFocus) moveFocusFrom(session.id);
      patch(session.id, { pending: false, spinner: false, leaving: true });
      setMessage(`Signed out ${label(session)}.`);
      setTimeout(() => {
        setGone((prev) => new Set(prev).add(session.id));
        patch(session.id, null);
      }, LEAVE_MS);
    } catch {
      clearTimeout(timer);
      patch(session.id, { pending: false, spinner: false, error: true });
      setMessage(`Could not sign out ${label(session)}.`);
    }
  };

  const closeConfirm = (restore = true) => {
    setConfirming(false);
    if (restore) requestAnimationFrame(() => triggerRef.current?.focus());
  };

  const signOutOthers = async () => {
    setOthersBusy(true);
    setOthersError(false);
    try {
      await onSignOutOthers();
      const leaving = others.map((s) => s.id);
      const step = reduced.current ? 0 : 55;
      leaving.forEach((id, index) => setTimeout(() => patch(id, { leaving: true, error: false }), index * step));
      setTimeout(() => {
        setGone((prev) => new Set([...prev, ...leaving]));
        setRows({});
      }, leaving.length * step + LEAVE_MS);
      setMessage(`Signed out ${leaving.length} other ${leaving.length === 1 ? "device" : "devices"}.`);
      closeConfirm();
    } catch {
      setOthersError(true);
      setMessage("Could not sign out the other devices.");
    } finally {
      setOthersBusy(false);
    }
  };

  React.useEffect(() => {
    if (!confirming) return;
    confirmRef.current?.focus();
    const onDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!popoverRef.current?.contains(target) && !triggerRef.current?.contains(target)) closeConfirm(false);
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [confirming]);

  const latest = [...others].sort((a, b) => stamp(b) - stamp(a))[0];

  return (
    <section aria-labelledby={headingId} className={cn("@container rounded-xl border border-border bg-card text-card-foreground shadow-sm", className)}>
      <header className="flex flex-col gap-3 border-b border-border px-4 py-4 @md:flex-row @md:items-center @md:justify-between sm:px-5">
        <h2 id={headingId} className="text-base font-semibold tracking-tight">{title}</h2>
        <div className="relative self-start @md:self-auto">
          <button
            ref={triggerRef}
            type="button"
            disabled={loading || others.length === 0}
            aria-haspopup="dialog"
            aria-expanded={confirming}
            aria-controls={confirming ? confirmId : undefined}
            onClick={() => (confirming ? closeConfirm() : setConfirming(true))}
            className={cn(
              "inline-flex h-9 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm font-medium transition-colors hover:bg-accent disabled:pointer-events-none disabled:opacity-50",
              ring,
            )}
          >
            <LogOut className="size-4" aria-hidden="true" />
            Sign out other devices
          </button>
          {confirming && (
            <div
              ref={popoverRef}
              id={confirmId}
              role="alertdialog"
              aria-labelledby={`${confirmId}-t`}
              aria-describedby={`${confirmId}-d`}
              onKeyDown={(event) => {
                if (event.key === "Escape") {
                  event.stopPropagation();
                  closeConfirm();
                }
                if (event.key === "Tab") {
                  const items = popoverRef.current?.querySelectorAll<HTMLButtonElement>("button");
                  if (!items?.length) return;
                  const first = items[0];
                  const last = items[items.length - 1];
                  if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
                  else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
                }
              }}
              className="absolute left-0 top-full z-20 mt-2 w-72 origin-top-left rounded-lg border border-border bg-popover p-4 text-popover-foreground shadow-lg motion-safe:animate-[chm-ds-pop_.16s_ease-out] @md:left-auto @md:right-0 @md:origin-top-right"
            >
              <p id={`${confirmId}-t`} className="text-sm font-semibold">Sign out {others.length} other {others.length === 1 ? "device" : "devices"}?</p>
              <p id={`${confirmId}-d`} className="mt-1 text-sm text-muted-foreground">This device stays signed in.</p>
              {othersError && <p className="mt-2 text-sm text-destructive">That did not work. Try again.</p>}
              <div className="mt-4 flex justify-end gap-2">
                <button type="button" onClick={() => closeConfirm()} className={cn("h-8 rounded-md px-3 text-sm font-medium hover:bg-accent", ring)}>
                  Cancel
                </button>
                <button
                  ref={confirmRef}
                  type="button"
                  onClick={signOutOthers}
                  aria-busy={othersBusy}
                  className={cn("inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground hover:opacity-90", ring)}
                >
                  {othersBusy && <Loader2 className="size-3.5 motion-safe:animate-spin" aria-hidden="true" />}
                  Confirm
                </button>
              </div>
            </div>
          )}
        </div>
      </header>

      {loading ? (
        <ul aria-label="Loading devices" aria-busy="true" className="divide-y divide-border">
          {[0, 1, 2].map((i) => (
            <li key={i} className="flex h-[76px] items-center gap-3 px-4 sm:px-5">
              <span className="size-10 shrink-0 rounded-lg bg-muted motion-safe:animate-pulse" />
              <span className="flex-1 space-y-2">
                <span className="block h-3.5 w-40 max-w-[60%] rounded bg-muted motion-safe:animate-pulse" />
                <span className="block h-3 w-56 max-w-[80%] rounded bg-muted/70 motion-safe:animate-pulse" />
              </span>
            </li>
          ))}
        </ul>
      ) : (
        <ul aria-labelledby={headingId}>
          {visible.map((session, index) => {
            const state = rows[session.id] || {};
            const Icon = ICONS[session.kind];
            const name = label(session);
            const active = session.lastActive === "now";
            return (
              <li
                key={session.id}
                aria-label={`${name}${session.current ? ", this device" : ""}`}
                className={cn(
                  "grid grid-rows-[1fr] transition-[grid-template-rows,opacity] duration-300 ease-out motion-reduce:transition-opacity",
                  state.leaving && "pointer-events-none opacity-0 motion-safe:grid-rows-[0fr]",
                )}
              >
                <div className="min-h-0 overflow-hidden">
                  <div className={cn("flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-4 sm:px-5", index > 0 && "border-t border-border")}>
                    <span className={cn("grid size-10 shrink-0 place-items-center rounded-lg bg-muted text-foreground/80", session.current && "bg-primary text-primary-foreground")}>
                      <Icon className="size-5" aria-hidden="true" />
                    </span>
                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                        <span className="truncate text-sm font-medium">{name}</span>
                        {session.current && <span className="rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground">This device</span>}
                        {session.flagged && (
                          <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/12 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300">
                            <ShieldAlert className="size-3" aria-hidden="true" />
                            {session.flagged === "new" ? "New" : "Unrecognised"}
                          </span>
                        )}
                      </div>
                      <p className="mt-0.5 flex flex-col items-start gap-x-1.5 text-[13px] text-muted-foreground @lg:flex-row @lg:flex-wrap @lg:items-center">
                        <span>{session.place}</span>
                        <span aria-hidden="true" className="hidden @lg:inline">·</span>
                        {active ? (
                          <span className="inline-flex items-center gap-1.5 text-emerald-700 dark:text-emerald-400">
                            <span className="size-1.5 rounded-full bg-emerald-500" aria-hidden="true" />
                            Online
                          </span>
                        ) : (
                          <span>Seen {since(session.lastActive as Date, now)}</span>
                        )}
                        {session.flagged && onReport && (
                          <>
                            <span aria-hidden="true" className="hidden @lg:inline">·</span>
                            <button
                              type="button"
                              onClick={() => onReport(session.id)}
                              aria-label={`Not you? Report ${name}`}
                              className={cn("rounded-sm font-medium text-foreground underline decoration-border underline-offset-2 hover:decoration-foreground", ring)}
                            >
                              Not you?
                            </button>
                          </>
                        )}
                      </p>
                      {state.error && (
                        <p className="mt-1.5 flex flex-wrap items-center gap-x-2 text-[13px] text-destructive">
                          <AlertTriangle className="size-3.5" aria-hidden="true" />
                          Sign-out failed.
                          <button
                            type="button"
                            onClick={() => signOut(session)}
                            className={cn("inline-flex items-center gap-1 rounded-sm font-medium underline underline-offset-2", ring)}
                          >
                            <RotateCcw className="size-3" aria-hidden="true" />
                            Retry
                          </button>
                        </p>
                      )}
                    </div>
                    {!session.current && (
                      <button
                        ref={(element) => {
                          if (element) buttons.current.set(session.id, element);
                          else buttons.current.delete(session.id);
                        }}
                        type="button"
                        onClick={() => signOut(session)}
                        aria-label={`Sign out ${name}`}
                        aria-busy={state.pending}
                        className={cn(
                          "ml-auto inline-flex h-8 min-w-[5.5rem] items-center justify-center gap-1.5 rounded-md px-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
                          ring,
                        )}
                      >
                        {state.spinner ? <Loader2 className="size-4 motion-safe:animate-spin" aria-hidden="true" /> : "Sign out"}
                      </button>
                    )}
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      )}

      {!loading && (
        <footer className="border-t border-border px-4 py-3 text-[13px] text-muted-foreground sm:px-5">
          {visible.length} {visible.length === 1 ? "device" : "devices"}
          {latest && <> · last sign-in from {latest.place.split(",")[0]}</>}
        </footer>
      )}
      <p className="sr-only" aria-live="polite" role="status">{message}</p>
      <style href="chm-device-sessions" precedence="default">{`@keyframes chm-ds-pop{from{opacity:0;transform:translateY(-4px) scale(.97)}to{opacity:1;transform:none}}`}</style>
    </section>
  );
}