@extantape/payload-plugin-hats 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Linked accounts and role hats for Payload. One person links their accounts and switches between them, and an account with several roles acts in one at a time. Switching up into a sensitive role asks for a second factor.
4
4
 
5
- **Status:** early, 0.x. The server side passes 30 tests against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The two React components were tried in a browser on a local copy of a real site (2026-11-09) with made-up accounts: keyboard, a real authenticator code, the approval form, and axe with 0 findings on the switch, the code prompt and the linking section in light and dark. It isn't in use on any site yet.
5
+ **Status:** early, 0.x. The server side passes 30 tests against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The redesigned switch (unreleased) has unit tests for its order, gating, button markup, code screen and focus targets, and was run in a browser at 390 and 1280 px wide on a local copy of a site with made-up accounts: keyboard open, Escape, the focus trap, Cancel back to the hat, a one-tap switch and the note after it (that browser run was before the button and note changes below, and wasn't repeated). A real authenticator code wasn't tried with the new switch; the server refused the made-up code, as it should. It isn't in use on any site yet.
6
6
 
7
7
  ## What it does
8
8
 
@@ -62,9 +62,23 @@ Endpoints, under the API route:
62
62
 
63
63
  Approvers approve in the admin, under Accounts → Linked accounts.
64
64
 
65
- The switch goes in the admin header (turn it off with `adminSwitch: false`). For a site's own pages, `@extantape/payload-plugin-hats/client` has `HatSwitcher` for the header and `LinkedAccounts` for the account page. They need no Payload UI package. By default they take the surrounding text color, and they follow `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-muted` and `--hats-focus` if you set them.
65
+ The switch goes in the admin header (turn it off with `adminSwitch: false`). The plugin doesn't pass options such as `accountTitle` or `hatHelp` to the header switch, so a site that needs them sets `adminSwitch: false` and registers its own wrapper around `HatSwitcher`. For a site's own pages, `@extantape/payload-plugin-hats/client` has `HatSwitcher` for the header, `HatsSwitchedNote` for pages without a switch (mount it once in your layout, as `import { HatsSwitchedNote } from '@extantape/payload-plugin-hats/client'`, so a switch that lands on one of your own pages still shows its note), and `LinkedAccounts` for the account page. They need no Payload UI package.
66
66
 
67
- Every word is replaceable for translation: pass `text` (see `defaultText`). Server answers carry a stable `reason` (for example `wrongCode`), and `text.reasons` gives your words for each; anything you leave out shows the English.
67
+ **The switch.** A pill, "Acting as Author" (24 characters at most, never the email), opens a panel titled Switch role: a popover 360 px wide under the trigger, or a bottom sheet below 640 px (85% of the screen at most, scrolling inside, with a scrim and room for the phone's safe area). It shows the hat worn now, then one group per account, the current account first. Each group is a fieldset with a button per hat: safe hats first, then hats that ask for a code, tagged with a lock and Needs a code. The hat worn now is marked Current and does nothing. A safe hat switches in one tap (the hat worn is marked with `aria-current`, so a screen reader says which one it is). A hat that asks for a code opens a code screen, Confirm it's you, with Switch and Cancel; Cancel puts focus back on that hat. Escape on the code screen goes back to the list too, and keeps what was typed. Spaces and dashes in a pasted code are dropped. When the hat worn is above the narrowest one, a Back to Member row stays at the bottom. Escape, the close button and the scrim close it and return focus to the trigger; focus stays inside while it's open.
68
+
69
+ After a switch the page reloads (or your `onSwitched` runs) and a note says "Now acting as Curator. Switch back to Member." in a status region with a dismiss button. A note with a Switch back link stays until it's dismissed, and focus stays where it was. A note without one goes after 5 seconds (longer while hovered or focused), and focus moves to the new page's heading. It's kept in sessionStorage across the reload.
70
+
71
+ Site options on `HatSwitcher`, all optional:
72
+
73
+ - `accountTitle(account)`: each group's heading, for example its job ("Maintainer account"). Default: This account, Linked account. The email sits under it, small.
74
+ - `hatHelp`: a helper line under each hat, as `{ [hatId]: line }` or `(hat, account) => line`.
75
+ - `orderHats(hats)`: the order inside a group. Default: as `hatsOf` gives them, with hats that ask for a code last.
76
+ - `anotherWay`: text shown under Use another way on the code screen (recovery codes, say). Left out, the link isn't shown.
77
+ - `noteMs`: how long the note stays. Default 5000.
78
+
79
+ Colors and sizes come from `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-muted`, `--hats-hover`, `--hats-selected`, `--hats-error`, `--hats-focus` (an outline value), `--hats-row` and the rest in `src/client/styles.ts`. Unset, they follow the Payload admin's theme variables, so the switch matches the admin in light and dark, and then the surrounding text. There are no fixed colors.
80
+
81
+ Every word is replaceable for translation: pass `text` (see `defaultText`) to `HatSwitcher`, `HatsSwitchedNote` and `LinkedAccounts`. Each visible or spoken string has a key with an English default: the switch (`title`, `close`, `trigger`, `switchHint`, `actingNow`, `current`, `needsCode`, `switching`, `backTo`, `accountThis`, `accountLinked`), the code screen (`confirmTitle`, `confirmBody`, `codeField`, `confirmButton`, `cancel`, `anotherWay`, `enterCode`), the note (`nowActing`, `switchBack`, `dismiss`) and the account page (`linkedHeading`, `linkedIntro`, `thisAccount`, `status`, `unlinkAsk`, `unlink`, `unlinkNamed`, `keep`, `setFull`, `emailLabel`, `send`, `youUnlinked`, `unlinked`). Keys that are functions take the hat, account or number they speak about. `accountThis` and `accountLinked` are the default group headings; `accountTitle` still overrides them. Server answers carry a stable `reason` (for example `wrongCode`), and `text.reasons` gives your words for each; anything you leave out shows the English.
68
82
 
69
83
  ## Commands
70
84
 
@@ -1,10 +1,54 @@
1
- import { type HatsText } from './api.js';
2
- /**
3
- * The switch: which account and hat you're acting as, and the others you can switch to. Renders nothing for an
4
- * account with nothing to switch to. A sensitive choice asks for that account's code inline. Reloads after a switch.
5
- */
6
- export declare function HatSwitcher({ apiRoute, onSwitched, text }: {
1
+ import { type HatsText, type MenuHat } from './api.js';
2
+ import { type Group, type HatHelp, type SignedInMenu, type SwitcherOptions } from './model.js';
3
+ export type HatSwitcherProps = SwitcherOptions & {
7
4
  apiRoute?: string;
5
+ /** Called after a switch instead of reloading the page (for example, to go where the new hat belongs). */
8
6
  onSwitched?: () => void;
9
7
  text?: Partial<HatsText>;
10
- }): import("react").JSX.Element | null;
8
+ /**
9
+ * Help shown on the code screen under "Use another way", for the site's other ways to give a code (a recovery
10
+ * code, say). Leave it out and the link isn't shown.
11
+ */
12
+ anotherWay?: string;
13
+ /** How long the "Now acting as" note stays, in milliseconds. Default 5000; it waits while hovered or focused. */
14
+ noteMs?: number;
15
+ };
16
+ type Asking = {
17
+ group: Group;
18
+ hat: MenuHat;
19
+ };
20
+ type Text = HatsText;
21
+ /** The props the panel needs to draw itself. Exported for tests; sites use `HatSwitcher`. */
22
+ export type SwitcherViewProps = {
23
+ t: Text;
24
+ base: string;
25
+ menu: SignedInMenu;
26
+ groups: Group[];
27
+ current: MenuHat | undefined;
28
+ back: MenuHat | null;
29
+ busy: string | null;
30
+ error: string;
31
+ asking: Asking | null;
32
+ code: string;
33
+ codeError: string;
34
+ otherWay: boolean;
35
+ anotherWay?: string;
36
+ hatHelp?: HatHelp;
37
+ onRowClick?: (group: Group, hat: MenuHat) => void;
38
+ onBack?: () => void;
39
+ onClose?: () => void;
40
+ onCode?: (code: string) => void;
41
+ onSubmitCode?: () => void;
42
+ onCancelCode?: () => void;
43
+ onOtherWay?: () => void;
44
+ };
45
+ /** The panel: the hat worn now, a group per account with a button per hat, or the code screen. */
46
+ export declare function SwitcherView(p: SwitcherViewProps): import("react").JSX.Element;
47
+ /**
48
+ * The switch: the hat you're acting in, the others you can switch to, grouped by account. Safe hats switch in one
49
+ * tap (a button per hat, `aria-current` on the one worn); a hat that asks for a code opens a code screen first. After the switch the page reloads (or `onSwitched`
50
+ * runs) and a short note says what you're acting as now, with a way back. Renders nothing for an account with
51
+ * nothing to switch to. Below 640px wide the panel is a bottom sheet.
52
+ */
53
+ export declare function HatSwitcher({ apiRoute, onSwitched, text, anotherWay, noteMs, ...opts }: HatSwitcherProps): import("react").JSX.Element;
54
+ export {};
@@ -1,101 +1,239 @@
1
1
  'use client';
2
- import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { useCallback, useEffect, useId, useRef, useState } from 'react';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
4
4
  import { defaultText, hatsApi } from './api.js';
5
- const v = (name, fallback) => `var(--hats-${name}, ${fallback})`;
6
- const ink = v('ink', 'currentColor');
7
- const paper = v('paper', 'var(--theme-elevation-0, Canvas)');
8
- const line = v('line', 'color-mix(in srgb, currentColor 45%, transparent)');
9
- // Muted text is the surrounding text color, slightly faded, so it keeps its contrast on light and dark pages.
10
- const muted = v('muted', 'color-mix(in srgb, currentColor 78%, transparent)');
11
- const focus = v('focus', '#b85c00');
12
- const s = {
13
- wrap: { position: 'relative', display: 'inline-block', font: 'inherit', color: ink },
14
- button: { font: 'inherit', color: ink, background: paper, border: `1px solid ${line}`, borderRadius: 6, minHeight: 32, padding: '4px 10px', cursor: 'pointer' },
15
- panel: { position: 'absolute', insetInlineEnd: 0, top: 'calc(100% + 6px)', zIndex: 50, minWidth: 'min(90vw, 320px)', maxWidth: 'min(90vw, 380px)', background: paper, color: ink, border: `1px solid ${line}`, borderRadius: 8, padding: 12, boxShadow: '0 6px 24px rgb(0 0 0 / 0.18)', whiteSpace: 'normal', overflowWrap: 'anywhere', textAlign: 'start' },
16
- heading: { fontSize: '0.85em', fontWeight: 600, margin: '8px 0 4px', color: muted },
17
- list: { listStyle: 'none', margin: 0, padding: 0 },
18
- item: { font: 'inherit', whiteSpace: 'normal', overflowWrap: 'anywhere', color: ink, background: 'transparent', border: 0, borderRadius: 4, width: '100%', textAlign: 'start', padding: '6px 8px', minHeight: 32, cursor: 'pointer' },
19
- note: { fontSize: '0.85em', color: muted },
20
- input: { font: 'inherit', color: ink, background: paper, border: `1px solid ${line}`, borderRadius: 4, padding: '4px 8px', minHeight: 32, width: '9em', letterSpacing: '0.1em' },
21
- error: { color: v('error', '#b00020'), fontSize: '0.9em', margin: '6px 0 0' },
22
- };
23
- const focusRing = `.hats-switcher :focus-visible{outline:3px solid ${focus};outline-offset:2px}.hats-switcher [aria-current="true"]{font-weight:600}`;
5
+ import { actionFor, backHat, cleanCode, clip, currentHatOf, focusAfter, groupsOf, helpLine, radioId, saveNote, session } from './model.js';
6
+ import { css } from './styles.js';
7
+ import { HatsSwitchedNote } from './SwitchedNote.js';
8
+ const PHONE = '(max-width: 639.98px)';
9
+ const Lock = () => (_jsxs("svg", { "aria-hidden": "true", focusable: "false", width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", children: [_jsx("rect", { x: "3", y: "7", width: "10", height: "7", rx: "1.5" }), _jsx("path", { d: "M5.5 7V5a2.5 2.5 0 0 1 5 0v2" })] }));
10
+ /** The panel: the hat worn now, a group per account with a button per hat, or the code screen. */
11
+ export function SwitcherView(p) {
12
+ const { t, base, groups, current, back, busy, asking } = p;
13
+ const currentGroup = groups[0];
14
+ const ids = { title: `${base}-title`, code: `${base}-code`, close: `${base}-close`, codeHelp: `${base}-code-help`, codeErr: `${base}-code-err`, other: `${base}-other` };
15
+ const help = (h, g = currentGroup) => helpLine(p.hatHelp, h, g);
16
+ if (asking) {
17
+ const { group, hat } = asking;
18
+ const working = busy === 'code';
19
+ return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "hats-sw-head", children: [_jsx("h2", { className: "hats-sw-title", id: ids.title, children: t.confirmTitle }), _jsx("button", { type: "button", id: ids.close, className: "hats-sw-close", "aria-label": t.close, onClick: p.onClose, children: _jsx("span", { "aria-hidden": "true", children: "\u00D7" }) })] }), _jsxs("form", { className: "hats-sw-body hats-sw-code", noValidate: true, onSubmit: (e) => {
20
+ e.preventDefault();
21
+ p.onSubmitCode?.();
22
+ }, children: [_jsx("p", { id: ids.codeHelp, children: t.confirmBody(hat.label, group.title) }), _jsx("label", { htmlFor: ids.code, children: t.codeField }), _jsx("input", { id: ids.code, className: "hats-sw-input", value: p.code, onChange: (e) => p.onCode?.(e.target.value), autoComplete: "one-time-code", inputMode: p.otherWay ? 'text' : 'numeric', autoCapitalize: "characters", spellCheck: false, "aria-invalid": p.codeError ? true : undefined, "aria-describedby": [ids.codeHelp, p.codeError ? ids.codeErr : null, p.otherWay && p.anotherWay ? ids.other : null].filter(Boolean).join(' ') }), _jsx("p", { id: ids.codeErr, className: "hats-sw-error", role: "alert", children: p.codeError }), p.anotherWay ? (p.otherWay ? (_jsx("p", { id: ids.other, className: "hats-sw-help hats-sw-more", children: p.anotherWay })) : (_jsx("p", { className: "hats-sw-more", children: _jsx("button", { type: "button", className: "hats-sw-link", onClick: p.onOtherWay, children: t.anotherWay }) }))) : null, _jsxs("div", { className: "hats-sw-actions", children: [_jsx("button", { type: "submit", className: "hats-sw-btn", "data-primary": "true", "aria-disabled": working || undefined, children: working ? t.switching : t.confirmButton(hat.label) }), _jsx("button", { type: "button", className: "hats-sw-btn", onClick: p.onCancelCode, children: t.cancel })] })] })] }));
23
+ }
24
+ return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "hats-sw-head", children: [_jsx("h2", { className: "hats-sw-title", id: ids.title, children: t.title }), _jsx("button", { type: "button", id: ids.close, className: "hats-sw-close", "aria-label": t.close, onClick: p.onClose, children: _jsx("span", { "aria-hidden": "true", children: "\u00D7" }) })] }), _jsxs("div", { className: "hats-sw-body", children: [current ? (_jsxs("div", { className: "hats-sw-now", children: [_jsx("p", { className: "hats-sw-now-label", children: t.actingNow }), _jsxs("p", { className: "hats-sw-now-hat", children: [_jsx("span", { children: current.label }), _jsx("span", { className: "hats-sw-tag", children: t.current })] }), _jsx("p", { className: "hats-sw-help", children: currentGroup.title }), help(current) ? _jsx("p", { className: "hats-sw-help", children: help(current) }) : null] })) : null, groups.map((g) => (_jsxs("fieldset", { className: "hats-sw-group", children: [_jsxs("legend", { children: [_jsx("span", { className: "hats-sw-acct", children: g.title }), _jsx("span", { className: "hats-sw-email", children: g.email })] }), _jsx("div", { className: "hats-sw-rows", "aria-busy": busy ? true : undefined, children: g.hats.map((h) => {
25
+ const rid = radioId(base, g.account, h.id);
26
+ const isCurrent = actionFor(g, h, current) === 'none';
27
+ const line = help(h, g);
28
+ return (_jsxs("button", { type: "button", id: rid, className: "hats-sw-row", "data-current": isCurrent || undefined, "aria-current": isCurrent ? 'true' : undefined, "aria-disabled": busy ? true : undefined, onClick: () => p.onRowClick?.(g, h), children: [_jsxs("span", { className: "hats-sw-row-text", children: [_jsx("span", { className: "hats-sw-row-name", children: h.label }), line ? _jsx("span", { className: "hats-sw-help", children: line }) : null] }), busy === rid ? (_jsx("span", { className: "hats-sw-tag", children: t.switching })) : isCurrent ? (_jsx("span", { className: "hats-sw-tag", children: t.current })) : h.needsCode ? (_jsxs("span", { className: "hats-sw-tag", children: [_jsx(Lock, {}), t.needsCode] })) : null] }, h.id));
29
+ }) })] }, String(g.id)))), _jsx("p", { className: "hats-sw-error", role: "alert", children: p.error }), _jsx("p", { className: "hats-sw-vh", role: "status", children: busy ? t.switching : '' })] }), back ? (_jsx("div", { className: "hats-sw-foot", children: _jsx("button", { type: "button", className: "hats-sw-btn hats-sw-wide", "aria-disabled": busy === 'back' || undefined, onClick: p.onBack, children: busy === 'back' ? t.switching : t.backTo(back.label) }) })) : null] }));
30
+ }
24
31
  /**
25
- * The switch: which account and hat you're acting as, and the others you can switch to. Renders nothing for an
26
- * account with nothing to switch to. A sensitive choice asks for that account's code inline. Reloads after a switch.
32
+ * The switch: the hat you're acting in, the others you can switch to, grouped by account. Safe hats switch in one
33
+ * tap (a button per hat, `aria-current` on the one worn); a hat that asks for a code opens a code screen first. After the switch the page reloads (or `onSwitched`
34
+ * runs) and a short note says what you're acting as now, with a way back. Renders nothing for an account with
35
+ * nothing to switch to. Below 640px wide the panel is a bottom sheet.
27
36
  */
28
- export function HatSwitcher({ apiRoute = '/api', onSwitched, text }) {
37
+ export function HatSwitcher({ apiRoute = '/api', onSwitched, text, anotherWay, noteMs = 5000, ...opts }) {
29
38
  const t = { ...defaultText, ...text };
30
39
  const api = hatsApi(apiRoute, t);
40
+ const base = `hats${useId().replace(/[^A-Za-z0-9_-]/g, '')}`;
31
41
  const [menu, setMenu] = useState(null);
32
42
  const [open, setOpen] = useState(false);
33
43
  const [asking, setAsking] = useState(null);
34
44
  const [code, setCode] = useState('');
45
+ const [codeError, setCodeError] = useState('');
46
+ const [otherWay, setOtherWay] = useState(false);
35
47
  const [error, setError] = useState('');
36
- const [busy, setBusy] = useState(false);
37
- const button = useRef(null);
48
+ const [busy, setBusy] = useState(null);
49
+ const trigger = useRef(null);
38
50
  const wrap = useRef(null);
39
- const codeBox = useRef(null);
40
- const panelId = useId();
51
+ const panel = useRef(null);
52
+ const draft = useRef(null);
53
+ const focusNext = useRef(null);
54
+ const triggerId = `${base}-trigger`;
41
55
  useEffect(() => {
42
56
  void api.menu().then(setMenu);
43
57
  // eslint-disable-next-line react-hooks/exhaustive-deps
44
58
  }, [apiRoute]);
45
- const close = useCallback(() => {
59
+ useLayoutEffect(() => {
60
+ if (!focusNext.current)
61
+ return;
62
+ const el = document.getElementById(focusNext.current);
63
+ focusNext.current = null;
64
+ el?.focus();
65
+ });
66
+ const signedIn = menu?.signedIn ? menu : null;
67
+ const groups = signedIn ? groupsOf(signedIn, opts, t) : [];
68
+ const current = signedIn ? currentHatOf(signedIn) : undefined;
69
+ const back = signedIn ? backHat(signedIn) : null;
70
+ const currentRadio = current ? radioId(base, undefined, current.id) : '';
71
+ const firstGroup = groups[0];
72
+ const firstRow = firstGroup?.hats[0] ? radioId(base, firstGroup.account, firstGroup.hats[0].id) : '';
73
+ const close = useCallback((returnFocus = true) => {
46
74
  setOpen(false);
47
75
  setAsking(null);
48
- setError('');
49
76
  setCode('');
50
- button.current?.focus();
77
+ setCodeError('');
78
+ setOtherWay(false);
79
+ setError('');
80
+ draft.current = null;
81
+ if (returnFocus)
82
+ trigger.current?.focus();
51
83
  }, []);
84
+ const show = () => {
85
+ setOpen(true);
86
+ // The hat worn, else the first hat, else Close: focus always lands inside the panel.
87
+ focusNext.current = currentRadio || firstRow || `${base}-close`;
88
+ };
52
89
  useEffect(() => {
53
90
  if (!open)
54
91
  return;
55
- const onKey = (e) => e.key === 'Escape' && close();
56
- const onClick = (e) => !wrap.current?.contains(e.target) && close();
57
- document.addEventListener('keydown', onKey);
58
- document.addEventListener('mousedown', onClick);
92
+ // A tap outside the wrapper closes. The scrim is inside it and closes on click (below), so the tap ends on the
93
+ // scrim and never reaches the page underneath.
94
+ const onDown = (e) => {
95
+ if (!wrap.current?.contains(e.target))
96
+ close(false);
97
+ };
98
+ document.addEventListener('pointerdown', onDown);
99
+ // On a phone the sheet covers the page: keep the page behind it from scrolling.
100
+ const phone = window.matchMedia?.(PHONE).matches;
101
+ const root = document.documentElement;
102
+ const before = root.style.overflow;
103
+ if (phone)
104
+ root.style.overflow = 'hidden';
59
105
  return () => {
60
- document.removeEventListener('keydown', onKey);
61
- document.removeEventListener('mousedown', onClick);
106
+ document.removeEventListener('pointerdown', onDown);
107
+ if (phone)
108
+ root.style.overflow = before;
62
109
  };
63
110
  }, [open, close]);
64
- useEffect(() => {
65
- if (asking)
66
- codeBox.current?.focus();
67
- }, [asking]);
68
- if (!menu?.signedIn || !menu.showSwitch)
69
- return null;
70
- const current = menu.hats.find((h) => h.id === menu.hat) ?? menu.hats.at(-1);
71
- const signedInAs = String(menu.signedInAs) === String(menu.account.id) ? null : menu.linked.find((l) => String(l.id) === String(menu.signedInAs));
72
- async function go(choice, withCode) {
73
- setBusy(true);
111
+ const finish = (note) => {
112
+ saveNote(session(), note);
113
+ if (onSwitched)
114
+ onSwitched();
115
+ else
116
+ window.location.reload();
117
+ };
118
+ async function go(group, hat, key, withCode) {
119
+ if (busy)
120
+ return;
121
+ setBusy(key);
74
122
  setError('');
75
- const res = await api.switchTo({ account: choice.account, hat: choice.hat.id, code: withCode });
76
- setBusy(false);
123
+ setCodeError('');
124
+ const res = await api.switchTo({ account: group.account, hat: hat.id, code: withCode });
77
125
  if (res.ok) {
78
- if (onSwitched)
79
- onSwitched();
80
- else
81
- window.location.reload();
126
+ const first = group.first;
127
+ finish({ hat: hat.label, back: first && first.id !== hat.id && !first.needsCode ? { id: first.id, label: first.label } : null });
82
128
  return;
83
129
  }
130
+ setBusy(null);
84
131
  if (res.needsCode) {
85
- setAsking(choice);
86
- if (withCode)
87
- setError(t.enterCode);
132
+ if (!asking)
133
+ openCode(group, hat);
134
+ else
135
+ setCodeError(withCode ? res.message || t.enterCode : t.enterCode);
88
136
  return;
89
137
  }
90
- setError(res.message);
138
+ if (asking)
139
+ setCodeError(res.message);
140
+ else
141
+ setError(res.message);
91
142
  }
92
- const choose = (choice) => (choice.hat.needsCode ? (setAsking(choice), setError('')) : void go(choice));
93
- const hatList = (account, accountLabel, hats, isCurrent) => (_jsx("ul", { style: s.list, children: hats.map((h) => {
94
- const on = isCurrent && h.id === current?.id;
95
- return (_jsx("li", { children: _jsxs("button", { type: "button", style: s.item, "aria-current": on ? 'true' : undefined, disabled: busy || on, onClick: () => choose({ account, accountLabel, hat: h }), children: [on ? '✓ ' : '', h.label, h.needsCode && !on ? _jsxs("span", { style: s.note, children: [" \u00B7 ", t.asksForCode] }) : null] }) }, h.id));
96
- }) }));
97
- return (_jsxs("div", { className: "hats-switcher", style: s.wrap, ref: wrap, children: [_jsx("style", { children: focusRing }), _jsxs("button", { ref: button, type: "button", style: s.button, "aria-expanded": open, "aria-controls": panelId, onClick: () => (open ? close() : setOpen(true)), children: [menu.linked.length ? `${menu.account.label} · ` : '', current?.label ?? t.switchFallback, _jsx("span", { "aria-hidden": "true", children: " \u25BE" }), _jsxs("span", { style: { position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)' }, children: [": ", t.switchHint] })] }), open ? (_jsxs("div", { id: panelId, style: s.panel, role: "group", "aria-label": t.switchGroup, children: [signedInAs ? (_jsx("p", { style: s.note, children: t.signedInAs(signedInAs.label, menu.account.label) })) : null, asking ? (_jsxs("form", { onSubmit: (e) => {
143
+ function openCode(group, hat) {
144
+ setAsking({ group, hat });
145
+ const kept = draft.current?.key === radioId(base, group.account, hat.id) ? draft.current.code : '';
146
+ draft.current = null;
147
+ setCode(kept);
148
+ setCodeError('');
149
+ setOtherWay(false);
150
+ setError('');
151
+ focusNext.current = focusAfter('open-code', { trigger: triggerId, radio: '', code: `${base}-code` });
152
+ }
153
+ function activate(group, hat) {
154
+ if (busy)
155
+ return;
156
+ const what = actionFor(group, hat, current);
157
+ if (what === 'none')
158
+ return;
159
+ if (what === 'code')
160
+ openCode(group, hat);
161
+ else
162
+ void go(group, hat, radioId(base, group.account, hat.id));
163
+ }
164
+ const onPanelKey = (e) => {
165
+ if (e.key === 'Escape') {
166
+ e.stopPropagation();
167
+ if (asking) {
168
+ // Step back to the list and keep what was typed: reopening the code screen for the same hat has it.
169
+ const rid = radioId(base, asking.group.account, asking.hat.id);
170
+ draft.current = { key: rid, code };
171
+ setAsking(null);
172
+ setCodeError('');
173
+ setCode('');
174
+ focusNext.current = focusAfter('cancel-code', { trigger: triggerId, radio: rid, code: `${base}-code` });
175
+ return;
176
+ }
177
+ close();
178
+ return;
179
+ }
180
+ if (e.key !== 'Tab' || !panel.current)
181
+ return;
182
+ const stops = tabStops(panel.current);
183
+ if (!stops.length)
184
+ return;
185
+ const first = stops[0];
186
+ const last = stops.at(-1);
187
+ if (e.shiftKey && document.activeElement === first) {
188
+ e.preventDefault();
189
+ last.focus();
190
+ }
191
+ else if (!e.shiftKey && document.activeElement === last) {
192
+ e.preventDefault();
193
+ first.focus();
194
+ }
195
+ };
196
+ const live = _jsx(HatsSwitchedNote, { apiRoute: apiRoute, text: text, onSwitched: onSwitched, noteMs: noteMs });
197
+ if (!signedIn || !signedIn.showSwitch)
198
+ return (_jsx("div", { className: "hats-sw", children: live }));
199
+ const words = t.trigger(current?.label ?? t.switchFallback);
200
+ return (_jsxs("div", { className: "hats-sw", ref: wrap, children: [live, _jsx("style", { children: css }), _jsxs("button", { ref: trigger, id: triggerId, type: "button", className: "hats-sw-trigger", "aria-expanded": open, "aria-haspopup": "dialog", "aria-controls": open ? `${base}-panel` : undefined, onClick: () => (open ? close() : show()), children: [_jsx("span", { "aria-hidden": "true", children: clip(words) }), _jsxs("span", { className: "hats-sw-vh", children: [words, ". ", t.switchHint] }), _jsx("span", { "aria-hidden": "true", children: "\u25BE" })] }), open ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "hats-sw-scrim", "aria-hidden": "true", onClick: (e) => {
98
201
  e.preventDefault();
99
- void go(asking, code.trim());
100
- }, children: [_jsx("label", { htmlFor: `${panelId}-code`, style: { display: 'block', marginBottom: 6 }, children: t.codeLabel(asking.hat.label, asking.account !== undefined || signedInAs ? asking.accountLabel : null) }), _jsx("input", { ref: codeBox, id: `${panelId}-code`, style: s.input, value: code, onChange: (e) => setCode(e.target.value), autoComplete: "one-time-code", inputMode: "numeric", required: true }), ' ', _jsx("button", { type: "submit", style: s.button, disabled: busy, children: t.switchButton }), ' ', _jsx("button", { type: "button", style: s.button, onClick: () => (setAsking(null), setError('')), children: t.back })] })) : (_jsxs(_Fragment, { children: [_jsx("p", { style: s.heading, children: menu.linked.length ? menu.account.label : t.actAs }), hatList(undefined, menu.account.label, menu.hats, true), menu.linked.map((l) => (_jsxs("div", { children: [_jsx("p", { style: s.heading, children: l.label }), hatList(l.id, l.label, l.hats, false)] }, String(l.id))))] })), _jsx("p", { role: "alert", style: s.error, children: error })] })) : null] }));
202
+ e.stopPropagation();
203
+ close();
204
+ } }), _jsx("div", { ref: panel, id: `${base}-panel`, className: "hats-sw-panel", role: "dialog", "aria-modal": "true", "aria-labelledby": `${base}-title`, onKeyDown: onPanelKey, children: _jsx(SwitcherView, { t: t, base: base, menu: signedIn, groups: groups, current: current, back: back, busy: busy, error: error, asking: asking, code: code, codeError: codeError, otherWay: otherWay, anotherWay: anotherWay, hatHelp: opts.hatHelp, onRowClick: (g, h) => activate(g, h), onBack: () => {
205
+ const g = groups[0];
206
+ if (back && g)
207
+ void go(g, back, 'back');
208
+ }, onClose: () => close(), onCode: (c) => {
209
+ setCode(cleanCode(c, otherWay));
210
+ if (codeError)
211
+ setCodeError('');
212
+ }, onSubmitCode: () => {
213
+ if (!asking)
214
+ return;
215
+ const c = cleanCode(code, otherWay);
216
+ if (!c) {
217
+ setCodeError(t.enterCode);
218
+ focusNext.current = `${base}-code`;
219
+ return;
220
+ }
221
+ void go(asking.group, asking.hat, 'code', c);
222
+ }, onCancelCode: () => {
223
+ if (!asking)
224
+ return;
225
+ const rid = radioId(base, asking.group.account, asking.hat.id);
226
+ setAsking(null);
227
+ setCodeError('');
228
+ setCode('');
229
+ draft.current = null;
230
+ focusNext.current = focusAfter('cancel-code', { trigger: triggerId, radio: rid, code: `${base}-code` });
231
+ }, onOtherWay: () => {
232
+ setOtherWay(true);
233
+ focusNext.current = `${base}-code`;
234
+ } }) })] })) : null] }));
235
+ }
236
+ /** The panel's tab stops in order: every enabled control. */
237
+ function tabStops(root) {
238
+ return [...root.querySelectorAll('button, input, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')].filter((el) => !el.disabled && el.getAttribute('tabindex') !== '-1');
101
239
  }
@@ -1,7 +1,8 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useEffect, useId, useState } from 'react';
3
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
4
4
  import { defaultText, hatsApi } from './api.js';
5
+ import { linkedCss } from './styles.js';
5
6
  const v = (name, fallback) => `var(--hats-${name}, ${fallback})`;
6
7
  const ink = v('ink', 'currentColor');
7
8
  const line = v('line', 'color-mix(in srgb, currentColor 45%, transparent)');
@@ -26,8 +27,20 @@ export function LinkedAccounts({ apiRoute = '/api', text, headingClassName }) {
26
27
  const [said, setSaid] = useState('');
27
28
  const [busy, setBusy] = useState(false);
28
29
  const [unlinking, setUnlinking] = useState(null);
29
- const id = useId();
30
+ const id = useId().replace(/[^A-Za-z0-9_-]/g, '');
31
+ const focusNext = useRef(null);
30
32
  const reload = () => api.menu().then(setMenu);
33
+ // Focus moves after the render that makes its target (WCAG 2.4.3): a pressed button that goes away or
34
+ // is replaced would otherwise drop focus to the page.
35
+ useLayoutEffect(() => {
36
+ if (!focusNext.current)
37
+ return;
38
+ const el = document.getElementById(focusNext.current);
39
+ if (!el)
40
+ return;
41
+ focusNext.current = null;
42
+ el.focus();
43
+ });
31
44
  useEffect(() => {
32
45
  void reload();
33
46
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -52,8 +65,16 @@ export function LinkedAccounts({ apiRoute = '/api', text, headingClassName }) {
52
65
  setUnlinking(null);
53
66
  if (res.ok && res.body.signedOut)
54
67
  return window.location.reload();
68
+ // The row is gone after an unlink, so focus goes to the list's heading; after a refusal, back to that row's button.
69
+ focusNext.current = res.ok ? `${id}-h` : `${id}-unlink-${account}`;
55
70
  setSaid(res.ok ? (you ? t.youUnlinked : t.unlinked) : res.message);
56
71
  await reload();
57
72
  }
58
- return (_jsxs("section", { "aria-labelledby": `${id}-h`, children: [_jsx("h2", { id: `${id}-h`, className: headingClassName, children: t.linkedHeading }), _jsx("p", { style: s.note, children: t.linkedIntro(menu.maxLinked) }), menu.set.length ? (_jsx("ul", { style: s.list, children: menu.set.map((m) => (_jsxs("li", { style: s.row, children: [_jsxs("div", { children: [_jsx("strong", { children: m.label }), m.you ? ` ${t.thisAccount}` : '', _jsx("p", { style: s.note, children: t.status(m.status, m.you) })] }), unlinking === m.id ? (_jsxs("div", { role: "group", "aria-label": t.unlinkAsk(m.label), children: [_jsxs("span", { children: [t.unlinkAsk(m.you ? null : m.label), " "] }), _jsx("button", { type: "button", style: s.button, disabled: busy, onClick: () => void unlink(m.id, m.you), children: t.unlink }), ' ', _jsx("button", { type: "button", style: s.button, onClick: () => setUnlinking(null), children: t.keep })] })) : (_jsx("button", { type: "button", style: s.button, disabled: busy, onClick: () => setUnlinking(m.id), "aria-label": t.unlinkNamed(m.label), children: t.unlink }))] }, String(m.id)))) })) : null, full ? (_jsx("p", { style: s.note, children: t.setFull })) : (_jsxs("form", { onSubmit: (e) => void request(e), children: [_jsx("label", { htmlFor: `${id}-email`, style: { display: 'block', marginBottom: 6 }, children: t.emailLabel }), _jsx("input", { id: `${id}-email`, type: "email", autoComplete: "off", required: true, style: s.input, value: email, onChange: (e) => setEmail(e.target.value) }), ' ', _jsx("button", { type: "submit", style: s.button, disabled: busy || !email.trim(), children: t.send })] })), _jsx("p", { role: "status", style: s.note, children: said })] }));
73
+ return (_jsxs("section", { "aria-labelledby": `${id}-h`, children: [_jsx("style", { children: linkedCss }), _jsx("h2", { id: `${id}-h`, className: headingClassName, tabIndex: -1, children: t.linkedHeading }), _jsx("p", { style: s.note, children: t.linkedIntro(menu.maxLinked) }), menu.set.length ? (_jsx("ul", { style: s.list, children: menu.set.map((m) => (_jsxs("li", { style: s.row, children: [_jsxs("div", { children: [_jsx("strong", { children: m.label }), m.you ? ` ${t.thisAccount}` : '', _jsx("p", { style: s.note, children: t.status(m.status, m.you) })] }), unlinking === m.id ? (_jsxs("div", { role: "group", "aria-label": t.unlinkAsk(m.label), children: [_jsxs("span", { children: [t.unlinkAsk(m.you ? null : m.label), " "] }), _jsx("button", { id: `${id}-confirm-${m.id}`, type: "button", className: "hats-la-btn", style: s.button, disabled: busy, onClick: () => void unlink(m.id, m.you), children: t.unlink }), ' ', _jsx("button", { type: "button", className: "hats-la-btn", style: s.button, onClick: () => {
74
+ focusNext.current = `${id}-unlink-${m.id}`;
75
+ setUnlinking(null);
76
+ }, children: t.keep })] })) : (_jsx("button", { id: `${id}-unlink-${m.id}`, type: "button", className: "hats-la-btn", style: s.button, disabled: busy, onClick: () => {
77
+ focusNext.current = `${id}-confirm-${m.id}`;
78
+ setUnlinking(m.id);
79
+ }, "aria-label": t.unlinkNamed(m.label), children: t.unlink }))] }, String(m.id)))) })) : null, full ? (_jsx("p", { style: s.note, children: t.setFull })) : (_jsxs("form", { onSubmit: (e) => void request(e), children: [_jsx("label", { htmlFor: `${id}-email`, style: { display: 'block', marginBottom: 6 }, children: t.emailLabel }), _jsx("input", { id: `${id}-email`, type: "email", autoComplete: "off", required: true, className: "hats-la-input", style: s.input, value: email, onChange: (e) => setEmail(e.target.value) }), ' ', _jsx("button", { type: "submit", className: "hats-la-btn", style: s.button, disabled: busy || !email.trim(), children: t.send })] })), _jsx("p", { role: "status", style: s.note, children: said })] }));
59
80
  }
@@ -0,0 +1,17 @@
1
+ import { type HatsText } from './api.js';
2
+ export type HatsSwitchedNoteProps = {
3
+ apiRoute?: string;
4
+ text?: Partial<HatsText>;
5
+ /** Called after "Switch back" works, instead of reloading the page. */
6
+ onSwitched?: () => void;
7
+ /** How long a note with no way back stays, in milliseconds. Default 5000; it waits while hovered or focused. */
8
+ noteMs?: number;
9
+ };
10
+ /**
11
+ * The note after a switch: "Now acting as Curator. Switch back to Member." in a status region, with a dismiss button. A note with
12
+ * a way back stays until dismissed; one without goes after `noteMs` (5 seconds), longer while hovered or focused. The switch saves it in this tab's sessionStorage before the
13
+ * page reloads or moves on; whichever page loads next shows it once, and moves focus to that page's heading when the note has no way back.
14
+ * `HatSwitcher` includes it. Put it on pages that have no switch (a site's own pages, say), so the note follows a
15
+ * switch that lands there.
16
+ */
17
+ export declare function HatsSwitchedNote({ apiRoute, text, onSwitched, noteMs }: HatsSwitchedNoteProps): import("react").JSX.Element;
@@ -0,0 +1,113 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
4
+ import { defaultText, hatsApi } from './api.js';
5
+ import { dropNote, saveNote, session, takeNote } from './model.js';
6
+ import { css } from './styles.js';
7
+ /** The page heading; on a page without an h1, the main region or the first content heading (Payload's dashboard). */
8
+ function findHeading() {
9
+ return (document.querySelector('main h1, h1') ??
10
+ document.querySelector('main, [role="main"]') ??
11
+ [...document.querySelectorAll('h2')].find((x) => !x.closest('header, nav, dialog, [role="dialog"], .hats-sw')) ??
12
+ null);
13
+ }
14
+ /** Focus a non-control for this move only, with no ring: it isn't a control, and the ring goes once focus moves on. */
15
+ function focusQuietly(h) {
16
+ if (!h.hasAttribute('tabindex')) {
17
+ h.setAttribute('tabindex', '-1');
18
+ const before = h.style.outline;
19
+ h.style.outline = 'none';
20
+ h.addEventListener('blur', () => (h.removeAttribute('tabindex'), (h.style.outline = before)), { once: true });
21
+ }
22
+ h.focus({ preventScroll: true });
23
+ }
24
+ /**
25
+ * The note after a switch: "Now acting as Curator. Switch back to Member." in a status region, with a dismiss button. A note with
26
+ * a way back stays until dismissed; one without goes after `noteMs` (5 seconds), longer while hovered or focused. The switch saves it in this tab's sessionStorage before the
27
+ * page reloads or moves on; whichever page loads next shows it once, and moves focus to that page's heading when the note has no way back.
28
+ * `HatSwitcher` includes it. Put it on pages that have no switch (a site's own pages, say), so the note follows a
29
+ * switch that lands there.
30
+ */
31
+ export function HatsSwitchedNote({ apiRoute = '/api', text, onSwitched, noteMs = 5000 }) {
32
+ const t = { ...defaultText, ...text };
33
+ const [note, setNote] = useState(null);
34
+ const [noteError, setNoteError] = useState('');
35
+ const [held, setHeld] = useState(false);
36
+ const banner = useRef(null);
37
+ useEffect(() => {
38
+ // Read without removing: it's removed only once shown, so a page that mounts twice (Strict Mode) or is replaced
39
+ // before the note appears still shows it.
40
+ const found = takeNote(session(), Date.now(), true);
41
+ if (!found)
42
+ return;
43
+ // Shown a moment after the empty status region exists, so screen readers announce it.
44
+ const shown = setTimeout(() => {
45
+ dropNote(session());
46
+ setNote(found);
47
+ }, 150);
48
+ // The page heading; on a page without an h1, the main region or the first content heading (Payload's dashboard).
49
+ // Tried a few times, since the admin draws its heading after hydrating.
50
+ let tries = 0;
51
+ let heading;
52
+ const toHeading = () => {
53
+ const h = findHeading();
54
+ if (!h) {
55
+ if (++tries < 6)
56
+ heading = setTimeout(toHeading, 300);
57
+ return;
58
+ }
59
+ focusQuietly(h);
60
+ };
61
+ // A note with a way back keeps focus where it is: it stays until dismissed, and moving focus would cut off
62
+ // the announcement and take a keyboard user away from the quickest undo.
63
+ if (!found.back)
64
+ heading = setTimeout(toHeading, 300);
65
+ return () => (clearTimeout(shown), clearTimeout(heading));
66
+ }, []);
67
+ useEffect(() => {
68
+ // A note with a way back stays until it's dismissed (WCAG 2.2.1). One without goes after `noteMs`.
69
+ if (!note || note.back || held || noteError)
70
+ return;
71
+ const id = setTimeout(() => setNote(null), noteMs);
72
+ return () => clearTimeout(id);
73
+ }, [note, held, noteError, noteMs]);
74
+ // The banner is fixed to the bottom of the screen and can sit over the control a keyboard user tabs to
75
+ // (WCAG 2.4.11). While it shows, the page keeps scroll padding as tall as the space it covers, so the browser scrolls
76
+ // a focused control clear of it. Simpler and sturdier than moving it into the page flow: no layout shift, and it works
77
+ // wherever a site mounts the note.
78
+ useLayoutEffect(() => {
79
+ if (!note || !banner.current)
80
+ return;
81
+ const root = document.documentElement;
82
+ const before = root.style.scrollPaddingBottom;
83
+ const covered = Math.max(0, window.innerHeight - banner.current.getBoundingClientRect().top);
84
+ root.style.scrollPaddingBottom = `${Math.ceil(covered)}px`;
85
+ return () => {
86
+ root.style.scrollPaddingBottom = before;
87
+ };
88
+ }, [note, noteError]);
89
+ // After Dismiss the button is gone, so focus goes to the switch's trigger, else the page heading (WCAG 2.4.3).
90
+ function dismiss() {
91
+ setNote(null);
92
+ const trigger = document.querySelector('.hats-sw-trigger');
93
+ const target = trigger ?? findHeading();
94
+ if (trigger)
95
+ trigger.focus();
96
+ else if (target)
97
+ focusQuietly(target);
98
+ }
99
+ async function switchBack() {
100
+ if (!note?.back || noteError === t.switching)
101
+ return;
102
+ setNoteError(t.switching);
103
+ const res = await hatsApi(apiRoute, t).switchTo({ hat: note.back.id });
104
+ if (!res.ok)
105
+ return setNoteError(res.message || t.failed);
106
+ saveNote(session(), { hat: note.back.label, back: null });
107
+ if (onSwitched)
108
+ onSwitched();
109
+ else
110
+ window.location.reload();
111
+ }
112
+ return (_jsxs("div", { className: "hats-sw-note", children: [_jsx("style", { children: css }), _jsx("div", { role: "status", children: note ? (_jsxs("div", { ref: banner, className: "hats-sw-banner", onPointerEnter: () => setHeld(true), onPointerLeave: () => setHeld(false), onFocus: () => setHeld(true), onBlur: (e) => !e.currentTarget.contains(e.relatedTarget) && setHeld(false), children: [_jsxs("p", { children: [t.nowActing(note.hat), note.back ? (_jsxs(_Fragment, { children: [' ', _jsx("button", { type: "button", className: "hats-sw-link", onClick: () => void switchBack(), children: t.switchBack(note.back.label) })] })) : null, noteError ? _jsxs("span", { className: "hats-sw-help", children: [" ", noteError] }) : null] }), _jsx("button", { type: "button", className: "hats-sw-close", "aria-label": t.dismiss, onClick: dismiss, children: _jsx("span", { "aria-hidden": "true", children: "\u00D7" }) })] })) : null })] }));
113
+ }
@@ -59,9 +59,31 @@ export declare const hatsApi: (apiRoute?: string, words?: Words) => {
59
59
  export declare const statusText: (status: string, you: boolean) => "Linked" | "Confirmed. Waiting for an administrator to approve it." | "Waiting for you to confirm from this account’s email." | "Waiting for its email to be confirmed.";
60
60
  /** Every word the components show, so a site can pass its own translations. English by default. */
61
61
  export declare const defaultText: {
62
+ /** Visually hidden after the trigger's words. */
62
63
  switchHint: string;
63
64
  switchGroup: string;
64
65
  switchFallback: string;
66
+ /** The trigger's words; cut to 24 characters. */
67
+ trigger: (hat: string) => string;
68
+ title: string;
69
+ /** The default heading for the current account's group, and for a linked account's. */
70
+ accountThis: string;
71
+ accountLinked: string;
72
+ close: string;
73
+ actingNow: string;
74
+ current: string;
75
+ needsCode: string;
76
+ switching: string;
77
+ backTo: (hat: string) => string;
78
+ confirmTitle: string;
79
+ confirmBody: (hat: string, account: string) => string;
80
+ codeField: string;
81
+ confirmButton: (hat: string) => string;
82
+ cancel: string;
83
+ anotherWay: string;
84
+ nowActing: (hat: string) => string;
85
+ switchBack: (hat: string) => string;
86
+ dismiss: string;
65
87
  actAs: string;
66
88
  asksForCode: string;
67
89
  signedInAs: (signedIn: string, acting: string) => string;
@@ -28,9 +28,31 @@ export const statusText = (status, you) => status === 'approved'
28
28
  : 'Waiting for its email to be confirmed.';
29
29
  /** Every word the components show, so a site can pass its own translations. English by default. */
30
30
  export const defaultText = {
31
- switchHint: 'switch account or role',
31
+ /** Visually hidden after the trigger's words. */
32
+ switchHint: 'Switch account or role.',
32
33
  switchGroup: 'Switch account or role',
33
- switchFallback: 'Switch',
34
+ switchFallback: 'Switch role',
35
+ /** The trigger's words; cut to 24 characters. */
36
+ trigger: (hat) => `Acting as ${hat}`,
37
+ title: 'Switch role',
38
+ /** The default heading for the current account's group, and for a linked account's. */
39
+ accountThis: 'This account',
40
+ accountLinked: 'Linked account',
41
+ close: 'Close',
42
+ actingNow: 'You are acting as',
43
+ current: 'Current',
44
+ needsCode: 'Needs a code',
45
+ switching: 'Switching…',
46
+ backTo: (hat) => `Back to ${hat}`,
47
+ confirmTitle: 'Confirm it’s you',
48
+ confirmBody: (hat, account) => `Enter the 6-digit code from your authenticator app to act as ${hat} on ${/^this /i.test(account) ? account.toLowerCase() : `the ${account}`}.`,
49
+ codeField: 'Code',
50
+ confirmButton: (hat) => `Switch to ${hat}`,
51
+ cancel: 'Cancel',
52
+ anotherWay: 'Use another way',
53
+ nowActing: (hat) => `Now acting as ${hat}.`,
54
+ switchBack: (hat) => `Switch back to ${hat}.`,
55
+ dismiss: 'Dismiss',
34
56
  actAs: 'Act as',
35
57
  asksForCode: 'asks for a code',
36
58
  signedInAs: (signedIn, acting) => `Signed in as ${signedIn}, acting as ${acting}.`,
@@ -1,3 +1,5 @@
1
- export { HatSwitcher } from './HatSwitcher.js';
1
+ export { HatSwitcher, type HatSwitcherProps } from './HatSwitcher.js';
2
+ export { HatsSwitchedNote, type HatsSwitchedNoteProps } from './SwitchedNote.js';
3
+ export { defaultOrder, type AccountInfo, type HatHelp, type SwitcherOptions } from './model.js';
2
4
  export { LinkedAccounts } from './LinkedAccounts.js';
3
5
  export { defaultText, hatsApi, statusText, type HatsMenu, type HatsText, type MenuHat } from './api.js';
@@ -1,4 +1,6 @@
1
1
  'use client';
2
2
  export { HatSwitcher } from './HatSwitcher.js';
3
+ export { HatsSwitchedNote } from './SwitchedNote.js';
4
+ export { defaultOrder } from './model.js';
3
5
  export { LinkedAccounts } from './LinkedAccounts.js';
4
6
  export { defaultText, hatsApi, statusText } from './api.js';
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The switcher's decisions, kept apart from React so they can be tested on their own: which hat is worn, how the
3
+ * groups and rows are ordered, which hats ask for a code, what the trigger says, where focus goes, and the note
4
+ * kept across the reload after a switch.
5
+ */
6
+ import type { HatsMenu, MenuHat } from './api.js';
7
+ export type SignedInMenu = Extract<HatsMenu, {
8
+ signedIn: true;
9
+ }>;
10
+ /** What a site can say about one account, to head its group (for example its job: "Maintainer account"). */
11
+ export type AccountInfo = {
12
+ id: string | number;
13
+ label: string;
14
+ hats: MenuHat[];
15
+ current: boolean;
16
+ };
17
+ export type SwitcherOptions = {
18
+ /** The heading for an account's group. Default: "This account" for the current one, "Linked account" for others. */
19
+ accountTitle?: (account: AccountInfo) => string;
20
+ /**
21
+ * One helper line under each hat: by hat id, or a function of the hat and its account (so the same hat can read
22
+ * differently on different accounts). A hat with none shows no line.
23
+ */
24
+ hatHelp?: HatHelp;
25
+ /** The order of hats inside a group. Default: as the site gives them, with hats that ask for a code last. */
26
+ orderHats?: (hats: MenuHat[]) => MenuHat[];
27
+ };
28
+ export type HatHelp = Record<string, string> | ((hat: MenuHat, account: AccountInfo) => string | null | undefined);
29
+ /** The helper line for one hat on one account's group, if the site gave one. */
30
+ export declare function helpLine(help: HatHelp | undefined, hat: MenuHat, group: Group): string | undefined;
31
+ export type Group = {
32
+ /** Undefined for the current account (a switch without `account` stays on it). */
33
+ account: string | number | undefined;
34
+ id: string | number;
35
+ title: string;
36
+ email: string;
37
+ current: boolean;
38
+ hats: MenuHat[];
39
+ /** The account's narrowest hat, as the site gave it (before ordering): where "Back to …" goes. */
40
+ first: MenuHat | undefined;
41
+ };
42
+ /** A hat that asks for a code, or that the site marks sensitive, sits after the ones that don't. */
43
+ export declare const isSensitive: (h: MenuHat) => boolean;
44
+ /** Default order: as given, with sensitive hats after the others. Stable, so the site's own order holds inside each part. */
45
+ export declare const defaultOrder: (hats: MenuHat[]) => MenuHat[];
46
+ /** The hat worn now: the menu's hat, or the account's full set (the last hat) for a plain sign-in. */
47
+ export declare const currentHatOf: (menu: SignedInMenu) => MenuHat | undefined;
48
+ /** The groups, current account first, then linked accounts in the order the server gives. */
49
+ export declare function groupsOf(menu: SignedInMenu, opts?: SwitcherOptions, words?: {
50
+ accountThis: string;
51
+ accountLinked: string;
52
+ }): Group[];
53
+ /** What tapping a row does: nothing for the hat worn now, the code screen for one that asks, else switch at once. */
54
+ export declare function actionFor(group: Group, hat: MenuHat, current: MenuHat | undefined): 'none' | 'code' | 'switch';
55
+ /**
56
+ * The narrowest hat on the current account, offered as "Back to …" when the hat worn is above it. Null when already
57
+ * there or when the narrowest would itself ask for a code.
58
+ */
59
+ export declare function backHat(menu: SignedInMenu): MenuHat | null;
60
+ /** Trigger words, at most `max` characters, cut with an ellipsis. */
61
+ export declare const clip: (s: string, max?: number) => string;
62
+ /** A stable element id for one hat's radio, so the code screen can hand focus back to it. */
63
+ export declare const radioId: (base: string, account: string | number | undefined, hat: string) => string;
64
+ /**
65
+ * Where focus goes after an action: back to the hat's radio when the code screen is left with Cancel, to the
66
+ * trigger when the panel closes, and to the code box when the code screen opens.
67
+ */
68
+ export declare function focusAfter(action: 'cancel-code' | 'close' | 'open-code', ids: {
69
+ trigger: string;
70
+ radio: string;
71
+ code: string;
72
+ }): string;
73
+ /**
74
+ * A typed or pasted code, ready to send: spaces removed, and dashes too for the numeric code ("123 456" and
75
+ * "123-456" both become "123456"). Recovery codes (`otherWay`) keep their dashes. Not capped; the server decides.
76
+ */
77
+ export declare const cleanCode: (raw: string, otherWay?: boolean) => string;
78
+ /** The note kept across the reload after a switch, read once by the next page. */
79
+ export type SwitchedNote = {
80
+ hat: string;
81
+ back: {
82
+ id: string;
83
+ label: string;
84
+ } | null;
85
+ at: number;
86
+ };
87
+ export declare const NOTE_KEY = "hats:switched";
88
+ /** A note older than this is stale (a switch that never reloaded, or a tab left for later) and is dropped. */
89
+ export declare const NOTE_MAX_AGE_MS = 60000;
90
+ type Store = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
91
+ export declare function saveNote(store: Store | undefined, note: Omit<SwitchedNote, 'at'>, now?: number): void;
92
+ /**
93
+ * Reads the note. By default it's removed, so it shows once; `keep` leaves it for whoever shows it to remove
94
+ * (a page that mounts twice, or is replaced before the note appears, must not lose it). Anything malformed or stale
95
+ * is dropped.
96
+ */
97
+ export declare function takeNote(store: Store | undefined, now?: number, keep?: boolean): SwitchedNote | null;
98
+ /** Removes the note once it has been shown. */
99
+ export declare function dropNote(store: Store | undefined): void;
100
+ /** This tab's sessionStorage, or nothing where there is none (server render, storage blocked). */
101
+ export declare const session: () => Store | undefined;
102
+ export {};
@@ -0,0 +1,125 @@
1
+ /** The helper line for one hat on one account's group, if the site gave one. */
2
+ export function helpLine(help, hat, group) {
3
+ if (!help)
4
+ return undefined;
5
+ const line = typeof help === 'function' ? help(hat, { id: group.id, label: group.email, hats: group.hats, current: group.current }) : help[hat.id];
6
+ return line || undefined;
7
+ }
8
+ /** A hat that asks for a code, or that the site marks sensitive, sits after the ones that don't. */
9
+ export const isSensitive = (h) => h.needsCode || h.sensitive === true;
10
+ /** Default order: as given, with sensitive hats after the others. Stable, so the site's own order holds inside each part. */
11
+ export const defaultOrder = (hats) => [...hats.filter((h) => !isSensitive(h)), ...hats.filter(isSensitive)];
12
+ /** The hat worn now: the menu's hat, or the account's full set (the last hat) for a plain sign-in. */
13
+ export const currentHatOf = (menu) => menu.hats.find((h) => h.id === menu.hat) ?? menu.hats.at(-1);
14
+ /** The groups, current account first, then linked accounts in the order the server gives. */
15
+ export function groupsOf(menu, opts = {}, words = { accountThis: 'This account', accountLinked: 'Linked account' }) {
16
+ const order = opts.orderHats ?? defaultOrder;
17
+ const title = opts.accountTitle ?? ((a) => (a.current ? words.accountThis : words.accountLinked));
18
+ const one = (id, email, hats, current) => ({
19
+ account: current ? undefined : id,
20
+ id,
21
+ title: title({ id, label: email, hats, current }),
22
+ email,
23
+ current,
24
+ hats: order(hats),
25
+ first: hats[0],
26
+ });
27
+ return [one(menu.account.id, menu.account.label, menu.hats, true), ...menu.linked.map((l) => one(l.id, l.label, l.hats, false))];
28
+ }
29
+ /** What tapping a row does: nothing for the hat worn now, the code screen for one that asks, else switch at once. */
30
+ export function actionFor(group, hat, current) {
31
+ if (group.current && current && hat.id === current.id)
32
+ return 'none';
33
+ return hat.needsCode ? 'code' : 'switch';
34
+ }
35
+ /**
36
+ * The narrowest hat on the current account, offered as "Back to …" when the hat worn is above it. Null when already
37
+ * there or when the narrowest would itself ask for a code.
38
+ */
39
+ export function backHat(menu) {
40
+ const first = menu.hats[0];
41
+ const current = currentHatOf(menu);
42
+ if (!first || !current || first.id === current.id || first.needsCode)
43
+ return null;
44
+ return first;
45
+ }
46
+ /** Trigger words, at most `max` characters, cut with an ellipsis. */
47
+ export const clip = (s, max = 24) => (s.length <= max ? s : `${s.slice(0, max - 1).trimEnd()}…`);
48
+ /** A stable element id for one hat's radio, so the code screen can hand focus back to it. */
49
+ export const radioId = (base, account, hat) => `${base}-r-${String(account ?? 'self').replace(/[^A-Za-z0-9_-]/g, '_')}-${hat.replace(/[^A-Za-z0-9_-]/g, '_')}`;
50
+ /**
51
+ * Where focus goes after an action: back to the hat's radio when the code screen is left with Cancel, to the
52
+ * trigger when the panel closes, and to the code box when the code screen opens.
53
+ */
54
+ export function focusAfter(action, ids) {
55
+ if (action === 'cancel-code')
56
+ return ids.radio;
57
+ if (action === 'open-code')
58
+ return ids.code;
59
+ return ids.trigger;
60
+ }
61
+ /**
62
+ * A typed or pasted code, ready to send: spaces removed, and dashes too for the numeric code ("123 456" and
63
+ * "123-456" both become "123456"). Recovery codes (`otherWay`) keep their dashes. Not capped; the server decides.
64
+ */
65
+ export const cleanCode = (raw, otherWay = false) => raw.replace(otherWay ? /\s+/g : /[\s-]+/g, '');
66
+ export const NOTE_KEY = 'hats:switched';
67
+ /** A note older than this is stale (a switch that never reloaded, or a tab left for later) and is dropped. */
68
+ export const NOTE_MAX_AGE_MS = 60_000;
69
+ export function saveNote(store, note, now = Date.now()) {
70
+ try {
71
+ store?.setItem(NOTE_KEY, JSON.stringify({ ...note, at: now }));
72
+ }
73
+ catch {
74
+ // Storage full or blocked: the switch still happened, there's just no note.
75
+ }
76
+ }
77
+ /**
78
+ * Reads the note. By default it's removed, so it shows once; `keep` leaves it for whoever shows it to remove
79
+ * (a page that mounts twice, or is replaced before the note appears, must not lose it). Anything malformed or stale
80
+ * is dropped.
81
+ */
82
+ export function takeNote(store, now = Date.now(), keep = false) {
83
+ try {
84
+ const raw = store?.getItem(NOTE_KEY);
85
+ if (!raw)
86
+ return null;
87
+ const n = JSON.parse(raw);
88
+ const bad = typeof n.hat !== 'string' || typeof n.at !== 'number' || now - n.at > NOTE_MAX_AGE_MS || n.at > now + 5_000;
89
+ if (!keep || bad)
90
+ store?.removeItem(NOTE_KEY);
91
+ if (bad)
92
+ return null;
93
+ if (typeof n.hat !== 'string' || typeof n.at !== 'number')
94
+ return null;
95
+ const back = n.back && typeof n.back.id === 'string' && typeof n.back.label === 'string' ? { id: n.back.id, label: n.back.label } : null;
96
+ return { hat: n.hat, back, at: n.at };
97
+ }
98
+ catch {
99
+ try {
100
+ store?.removeItem(NOTE_KEY);
101
+ }
102
+ catch {
103
+ // Nothing more to do.
104
+ }
105
+ return null;
106
+ }
107
+ }
108
+ /** Removes the note once it has been shown. */
109
+ export function dropNote(store) {
110
+ try {
111
+ store?.removeItem(NOTE_KEY);
112
+ }
113
+ catch {
114
+ // Storage blocked: nothing was kept anyway.
115
+ }
116
+ }
117
+ /** This tab's sessionStorage, or nothing where there is none (server render, storage blocked). */
118
+ export const session = () => {
119
+ try {
120
+ return typeof window === 'undefined' ? undefined : window.sessionStorage;
121
+ }
122
+ catch {
123
+ return undefined;
124
+ }
125
+ };
@@ -0,0 +1,23 @@
1
+ export declare const tokens: {
2
+ ink: string;
3
+ paper: string;
4
+ line: string;
5
+ field: string;
6
+ muted: string;
7
+ hover: string;
8
+ selected: string;
9
+ error: string;
10
+ focus: string;
11
+ scrim: string;
12
+ shadow: string;
13
+ radius: string;
14
+ radiusSmall: string;
15
+ small: string;
16
+ row: string;
17
+ gap: string;
18
+ space: string;
19
+ };
20
+ /** Phone below 640px: a bottom sheet. Wider: a popover under the trigger. */
21
+ export declare const css: string;
22
+ /** The account page's buttons carry inline styles, so their focus ring comes from here and works outside Payload admin. */
23
+ export declare const linkedCss: string;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The switcher's look. Every color and size reads a `--hats-*` variable first, then the Payload admin's theme
3
+ * variables, then the surrounding text, so it follows the admin's light and dark themes and a site's own tokens.
4
+ * No fixed colors.
5
+ */
6
+ const v = (name, fallback) => `var(--hats-${name}, ${fallback})`;
7
+ export const tokens = {
8
+ ink: v('ink', 'var(--theme-text, currentColor)'),
9
+ paper: v('paper', 'var(--theme-elevation-0, Canvas)'),
10
+ line: v('line', 'var(--theme-elevation-150, color-mix(in srgb, currentColor 30%, transparent))'),
11
+ // Field borders need 3:1 (WCAG 1.4.11), which elevation 150 doesn't give.
12
+ field: v('field', 'var(--theme-elevation-600, color-mix(in srgb, currentColor 60%, transparent))'),
13
+ // Payload's elevation 650 keeps 4.5:1 on its own backgrounds in light and dark.
14
+ muted: v('muted', 'var(--theme-elevation-650, color-mix(in srgb, currentColor 78%, transparent))'),
15
+ hover: v('hover', 'var(--theme-elevation-50, color-mix(in srgb, currentColor 6%, transparent))'),
16
+ selected: v('selected', 'var(--theme-elevation-100, color-mix(in srgb, currentColor 10%, transparent))'),
17
+ error: v('error', 'var(--theme-error-650, currentColor)'),
18
+ focus: v('focus', 'var(--accessibility-outline, 2px solid currentColor)'),
19
+ scrim: v('scrim', 'color-mix(in srgb, var(--theme-elevation-1000, CanvasText) 45%, transparent)'),
20
+ shadow: v('shadow', '0 8px 28px color-mix(in srgb, var(--theme-elevation-1000, CanvasText) 22%, transparent)'),
21
+ radius: v('radius', 'var(--style-radius-l, 8px)'),
22
+ radiusSmall: v('radius-small', 'var(--style-radius-m, 4px)'),
23
+ small: v('small', '0.875rem'),
24
+ row: v('row', '48px'),
25
+ gap: v('gap', '8px'),
26
+ space: v('space', '16px'),
27
+ };
28
+ const t = tokens;
29
+ /** Phone below 640px: a bottom sheet. Wider: a popover under the trigger. */
30
+ export const css = `
31
+ .hats-sw{position:relative;display:inline-block;font:inherit;color:${t.ink}}
32
+ .hats-sw *{box-sizing:border-box}
33
+ .hats-sw :focus-visible,.hats-sw-note :focus-visible{outline:${t.focus};outline-offset:2px}
34
+ .hats-sw-vh{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
35
+ .hats-sw-trigger{font:inherit;color:${t.ink};background:${t.paper};border:1px solid ${t.field};border-radius:999px;min-height:36px;padding:4px 14px;cursor:pointer;display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
36
+ .hats-sw-trigger:hover{background:${t.hover}}
37
+ .hats-sw-scrim{display:none}
38
+ .hats-sw-panel{position:absolute;inset-inline-end:0;top:calc(100% + 6px);z-index:60;width:360px;max-width:90vw;max-height:min(80vh,640px);display:flex;flex-direction:column;background:${t.paper};color:${t.ink};border:1px solid ${t.line};border-radius:${t.radius};box-shadow:${t.shadow};text-align:start;white-space:normal;overflow-wrap:anywhere;line-height:1.4}
39
+ @media (max-width:639.98px){
40
+ .hats-sw-scrim{display:block;position:fixed;inset:0;z-index:59;background:${t.scrim}}
41
+ .hats-sw-panel{position:fixed;inset-inline:0;bottom:0;top:auto;width:100%;max-width:none;max-height:85dvh;border-radius:${t.radius} ${t.radius} 0 0;border-bottom:0;padding-bottom:env(safe-area-inset-bottom)}
42
+ }
43
+ .hats-sw-head{display:flex;align-items:center;justify-content:space-between;gap:${t.gap};padding:${t.gap} ${t.gap} 0 ${t.space}}
44
+ .hats-sw-title{font-size:1.125rem;font-weight:600;margin:0}
45
+ .hats-sw-close{font:inherit;font-size:1.5rem;line-height:1;color:${t.ink};background:transparent;border:0;border-radius:${t.radiusSmall};width:${t.row};height:${t.row};cursor:pointer;flex:none}
46
+ .hats-sw-close:hover{background:${t.hover}}
47
+ .hats-sw-body{overflow-y:auto;overscroll-behavior:contain;padding:0 ${t.space} ${t.space};flex:1 1 auto}
48
+ .hats-sw-now{margin:${t.gap} 0 0;padding:12px;border-radius:${t.radiusSmall};background:${t.selected}}
49
+ .hats-sw-now-label{font-size:${t.small};color:${t.muted};margin:0}
50
+ .hats-sw-now-hat{font-weight:600;margin:2px 0 0;display:flex;flex-wrap:wrap;align-items:center;gap:${t.gap}}
51
+ .hats-sw-help{font-size:${t.small};color:${t.muted};margin:2px 0 0}
52
+ .hats-sw-tag{font-size:${t.small};font-weight:600;border:1px solid ${t.field};border-radius:999px;padding:0 8px;line-height:1.6;white-space:nowrap;display:inline-flex;align-items:center;gap:4px;flex:none}
53
+ .hats-sw-group{border:0;margin:${t.space} 0 0;padding:${t.space} 0 0;min-inline-size:0;border-top:1px solid ${t.line}}
54
+ .hats-sw-group legend{padding:0;margin:0 0 ${t.gap};float:left;width:100%}
55
+ .hats-sw-group legend+*{clear:both}
56
+ .hats-sw-acct{display:block;font-weight:600}
57
+ .hats-sw-email{display:block;font-size:${t.small};color:${t.muted};text-decoration:none;font-weight:400}
58
+ .hats-sw-rows{display:flex;flex-direction:column;gap:${t.gap};clear:both}
59
+ .hats-sw-row{font:inherit;color:inherit;text-align:start;background:transparent;border:0;width:100%;display:flex;align-items:center;gap:12px;min-height:${t.row};padding:6px 10px;border-radius:${t.radiusSmall};cursor:pointer}
60
+ .hats-sw-row:hover{background:${t.hover}}
61
+ .hats-sw-row[data-current="true"]{background:${t.selected}}
62
+ .hats-sw-row[aria-disabled="true"]{cursor:progress}
63
+ .hats-sw-row-text{flex:1 1 auto;min-width:0}
64
+ .hats-sw-row-name{display:block}
65
+ .hats-sw-row[data-current="true"] .hats-sw-row-name{font-weight:600}
66
+ .hats-sw-row .hats-sw-help{display:block}
67
+ .hats-sw-foot{flex:none;border-top:1px solid ${t.line};padding:${t.gap} ${t.space};background:${t.paper};border-radius:0 0 ${t.radius} ${t.radius}}
68
+ .hats-sw-btn{font:inherit;color:${t.ink};background:${t.paper};border:1px solid ${t.line};border-radius:${t.radiusSmall};min-height:${t.row};padding:8px 16px;cursor:pointer}
69
+ .hats-sw-btn:hover{background:${t.hover}}
70
+ .hats-sw-btn[data-primary="true"]{background:${t.ink};color:${t.paper};border-color:${t.ink};font-weight:600}
71
+ .hats-sw-btn[aria-disabled="true"]{cursor:progress;opacity:.75}
72
+ .hats-sw-wide{width:100%;text-align:start}
73
+ .hats-sw-link{font:inherit;color:inherit;background:none;border:0;padding:0;text-decoration:underline;text-underline-offset:2px;cursor:pointer}
74
+ .hats-sw-code{padding-top:${t.gap}}
75
+ .hats-sw-code p{margin:0 0 12px}
76
+ .hats-sw-code .hats-sw-more{margin-top:${t.gap}}
77
+ .hats-sw-more .hats-sw-link{min-height:32px;min-width:32px;display:inline-flex;align-items:center}
78
+ .hats-sw-code label{display:block;font-weight:600;margin-bottom:4px}
79
+ .hats-sw-input{font:inherit;font-size:1.25rem;letter-spacing:.15em;color:${t.ink};background:${t.paper};border:1px solid ${t.field};border-radius:${t.radiusSmall};min-height:${t.row};padding:6px 12px;width:100%;max-width:14em}
80
+ .hats-sw-input[aria-invalid="true"]{border-color:${t.error};border-width:2px}
81
+ .hats-sw-actions{display:flex;flex-wrap:wrap;gap:${t.gap};margin-top:${t.space}}
82
+ .hats-sw-error{color:${t.error};font-size:${t.small};margin:6px 0 0}
83
+ .hats-sw-error:empty{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
84
+ .hats-sw-banner{position:fixed;z-index:70;inset-inline:${t.space};bottom:calc(${t.space} + env(safe-area-inset-bottom));margin-inline:auto;max-width:480px;display:flex;align-items:center;gap:${t.gap};background:${t.paper};color:${t.ink};border:1px solid ${t.line};border-radius:${t.radius};box-shadow:${t.shadow};padding:${t.gap} ${t.gap} ${t.gap} ${t.space}}
85
+ .hats-sw-banner:empty{display:none}
86
+ .hats-sw-banner p{margin:0;flex:1 1 auto}
87
+ `;
88
+ /** The account page's buttons carry inline styles, so their focus ring comes from here and works outside Payload admin. */
89
+ export const linkedCss = `
90
+ .hats-la-btn:focus-visible,.hats-la-input:focus-visible{outline:${t.focus};outline-offset:2px}
91
+ `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
5
5
  "keywords": [
6
6
  "payload",
@@ -55,10 +55,13 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@payloadcms/db-mongodb": "3.92.1",
58
+ "@testing-library/dom": "^10.4.2",
59
+ "@testing-library/react": "^16.3.3",
58
60
  "@types/node": "^24.0.0",
59
61
  "@types/react": "^19.3.0",
60
62
  "@types/react-dom": "^19.3.0",
61
63
  "graphql": "^16.14.2",
64
+ "jsdom": "^31.0.1",
62
65
  "mongodb-memory-server": "^11.3.0",
63
66
  "payload": "3.92.1",
64
67
  "react": "^19.3.1",