@extantape/payload-plugin-hats 0.2.0 → 0.4.0
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 +47 -4
- package/dist/client/HatSwitcher.d.ts +51 -7
- package/dist/client/HatSwitcher.js +203 -65
- package/dist/client/LinkedAccounts.js +24 -3
- package/dist/client/SwitchedNote.d.ts +17 -0
- package/dist/client/SwitchedNote.js +113 -0
- package/dist/client/api.d.ts +22 -0
- package/dist/client/api.js +24 -2
- package/dist/client/index.d.ts +3 -1
- package/dist/client/index.js +2 -0
- package/dist/client/model.d.ts +102 -0
- package/dist/client/model.js +125 -0
- package/dist/client/styles.d.ts +23 -0
- package/dist/client/styles.js +91 -0
- package/dist/endpoints.d.ts +24 -1
- package/dist/endpoints.js +170 -89
- package/dist/index.d.ts +17 -1
- package/dist/index.js +11 -1
- package/package.json +4 -1
|
@@ -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
|
+
}
|
package/dist/client/api.d.ts
CHANGED
|
@@ -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;
|
package/dist/client/api.js
CHANGED
|
@@ -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
|
-
|
|
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}.`,
|
package/dist/client/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/client/index.js
CHANGED
|
@@ -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/dist/endpoints.d.ts
CHANGED
|
@@ -1,4 +1,27 @@
|
|
|
1
|
-
import { type Endpoint } from 'payload';
|
|
1
|
+
import { type Endpoint, type PayloadRequest } from 'payload';
|
|
2
2
|
import { revokeSessions } from './sessions.js';
|
|
3
|
+
/** What a switch came to. A refusal carries the endpoint's `reason` (`needsCode` included) and its English message. */
|
|
4
|
+
export type SwitchResult = {
|
|
5
|
+
ok: true;
|
|
6
|
+
account: string;
|
|
7
|
+
hat: string; /** The Set-Cookie value for the new session, or null when the hat changed on the same account. */
|
|
8
|
+
cookie: string | null;
|
|
9
|
+
} | {
|
|
10
|
+
ok: false;
|
|
11
|
+
status: number;
|
|
12
|
+
reason: string;
|
|
13
|
+
message: string;
|
|
14
|
+
};
|
|
15
|
+
/** The input of a switch: the same three fields the endpoint reads from its body. */
|
|
16
|
+
export type SwitchInput = {
|
|
17
|
+
account?: unknown;
|
|
18
|
+
hat?: unknown;
|
|
19
|
+
code?: unknown;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The one switch, shared by POST /api/hats/switch and `switchSession`, so the two can't drift. It acts only for
|
|
23
|
+
* `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
|
|
24
|
+
*/
|
|
25
|
+
export declare function runSwitch(req: PayloadRequest, input: SwitchInput | null | undefined): Promise<SwitchResult>;
|
|
3
26
|
export declare const hatEndpoints: Endpoint[];
|
|
4
27
|
export { revokeSessions };
|