@extantape/payload-plugin-hats 0.1.5 → 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,13 +2,15 @@
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 22 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
 
9
9
  - **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Unlinking is self-serve and immediate.
10
10
  - **Hats.** Wearing a hat narrows the user before `req.user` exists, so every access rule follows it: admin, REST, GraphQL and the Local API with `req`. If narrowing fails, the request is signed out, never given full roles.
11
- - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 3 hours per account.
11
+ - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 3 hours per account (or per linked set, see below).
12
+ - **Step up on gain.** Pass `stepUpWhen` to decide for yourself when a switch asks for a code, in place of the `sensitive` flag. It gets the hat worn now (`from`) and the one it would become (`to`), each with the user as it would be worn, so a site can ask only when `to` holds a role or permission that `from` doesn't. Going down asks nothing, going up or sideways asks. Only an exact `false` skips the code. `true`, a throw or any other answer asks, so a broken check never lets a switch through.
13
+ - **One code for the whole set.** `stepUp.rememberPer: 'set'` remembers a good code for every account in the same linked set, for the same 3 hours, so one two-step covers the person. The default, `'account'`, is unchanged. An account in no set is remembered on its own either way. `stepUp.available` and `stepUp.verify` also get `signedIn` (the account that actually signed in) and `set` (the linked set's id, or `null`), so a site can check against one two-step for the person. `user` stays the account being switched into.
12
14
  - **Revocation.** Unlinking, deleting a row, losing a role or deleting an account ends every session switched into or through it. Switched sessions also re-check their set on every request. An ended session's record is kept, marked revoked, so a session that Payload writes back by accident (two writes to an account's sessions at once) stays signed out. Old records are deleted once their Payload session is gone, at most 50 per switch.
13
15
  - **Link limits.** Pass `limit` to rate-limit link requests, per person and per email address. It must answer exactly `true` to allow one. Any other answer, or a throw, refuses the request with `tooMany` (429) and nothing is sent.
14
16
 
@@ -41,7 +43,9 @@ hats({
41
43
  hatsOf: (user) => [{ id: 'member', label: 'Member' }, { id: 'admin', label: 'Administrator', sensitive: true }],
42
44
  wear: (user, hat) => ({ ...user, roles: hat === 'admin' ? user.roles : ['member'] }),
43
45
  canApproveLinks: ({ user }) => user.roles.includes('admin'),
44
- stepUp: { available: (user) => hasAuthenticator(user), verify: ({ user, code }) => checkCode(user, code) },
46
+ stepUp: { available: (user) => hasAuthenticator(user), verify: ({ user, code }) => checkCode(user, code), rememberPer: 'set' }, // rememberPer is optional
47
+ // optional: ask only when the new hat holds something the current one doesn't
48
+ stepUpWhen: ({ from, to }) => holdsMoreThan(to.user, from.user),
45
49
  limit: ({ user, email }) => allowAttempt('hatsLink', `${user.id}:${email}`), // optional
46
50
  })
47
51
  ```
@@ -58,9 +62,23 @@ Endpoints, under the API route:
58
62
 
59
63
  Approvers approve in the admin, under Accounts → Linked accounts.
60
64
 
61
- 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.
62
66
 
63
- 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.
64
82
 
65
83
  ## Commands
66
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;