@extantape/payload-plugin-wizards 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +76 -2
- package/dist/client/Wizard.d.ts +46 -0
- package/dist/client/Wizard.js +127 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +2 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +18 -0
- package/dist/steps.d.ts +54 -0
- package/dist/steps.js +198 -0
- package/dist/types.d.ts +71 -0
- package/dist/types.js +1 -0
- package/package.json +78 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EXTANT APE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-plugin-wizards
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.
|
|
4
|
+
|
|
5
|
+
**Status:** 0.1.0, not on npm yet. The server tests run on Payload 3.92 with an in-memory MongoDB, and the component tests in jsdom (32 tests: 14 server, 18 component). No site uses it yet, and nothing has run in a real browser.
|
|
6
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
9
|
+
- **Steps in the admin** (`guided-steps`): each has a flow, a key, a group, an order and a kind:
|
|
10
|
+
- **gate:** Yes needed to go on;
|
|
11
|
+
- **info:** Next;
|
|
12
|
+
- **choice:** options, any of which can stop the flow.
|
|
13
|
+
|
|
14
|
+
Each step also has its question, a text version, an optional video with required captions, a stop message, and active or not.
|
|
15
|
+
- Every gate and choice needs a stop message, which says what to do when the answer is No. A choice's options each need their own value.
|
|
16
|
+
- A video has to be a video file, and its captions a WebVTT file.
|
|
17
|
+
- Each step's content hash covers what a person confirms (question, text, kind, options, stop message, video and captions) in the language they read it. It's worked out each time a step is read, so it can't go stale.
|
|
18
|
+
- Editors (`access.edit`, required) change steps. The public reads active ones only.
|
|
19
|
+
- **Flows are registered in code:** a list of slots, either your own code steps (finding a kit with the camera, choosing an animal) or a group of content steps. Other plugins register flows at `config.custom.wizardFlows` with no import, and a flow registered twice, or one that uses a group of steps twice, stops the site at start-up.
|
|
20
|
+
- **`flowSteps(payload, { flow, locale })`** gives the flow's slots, with active steps in order, for the page.
|
|
21
|
+
- **`<Wizard>`** (`./client`) shows one step per screen:
|
|
22
|
+
- focus on the question, "Step N of M", and Back;
|
|
23
|
+
- No shows the stop message and stays, and withdraws an earlier Yes on that step;
|
|
24
|
+
- video with captions, never autoplaying, and the text version always shown;
|
|
25
|
+
- your code steps rendered with `next` and `back`;
|
|
26
|
+
- state in memory only.
|
|
27
|
+
- **The answers are checked on the server, not trusted.** Call `answersFor(payload, { flow, answers })` before acting. It refuses:
|
|
28
|
+
- a No, or a stopping choice;
|
|
29
|
+
- a missing, extra or repeated step;
|
|
30
|
+
- a group of steps with no active step, so a safety group that was never seeded, is misspelled or was switched off never waves the flow through;
|
|
31
|
+
- any step whose wording changed since the screen loaded;
|
|
32
|
+
- a flow it doesn't know.
|
|
33
|
+
|
|
34
|
+
Pass the `locale` the person read. It returns the record to keep with your action: the language, each step's hash and question as the person read them, the answers, and the time. The hash identifies the full wording; the plugin keeps no copy of older wording, so keep versions on `guided-steps` if you need to show a past version in full. A client can't skip a gate by posting straight to your action.
|
|
35
|
+
|
|
36
|
+
## On its own, and with others
|
|
37
|
+
|
|
38
|
+
**On its own:** Wizards needs only Payload, an `access.edit` rule, and an upload collection if your steps have videos (`media`, or `false` for none). Your site registers its flows in `flows` and renders its own code steps.
|
|
39
|
+
|
|
40
|
+
**Works with:**
|
|
41
|
+
- **Sample Kits:** with `adapters.wizards`, Sample Kits registers its `kit-activation` flow at `config.custom.wizardFlows` and checks the answers with `answersFor`.
|
|
42
|
+
- **Scan:** a code step can show Scan's `<CameraScanButton>`, for example to find a kit. Neither plugin imports the other.
|
|
43
|
+
|
|
44
|
+
**Family:** Wizards sits in the Fulfillment family, with Kitting, Restock, Sample Kits, Shipping, Scan, Labels, Custody and Sequences, though the families are a working draft and Fulfillment is due to be split into different groups.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
npm install @extantape/payload-plugin-wizards
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { wizardsPlugin } from '@extantape/payload-plugin-wizards'
|
|
54
|
+
|
|
55
|
+
wizardsPlugin({
|
|
56
|
+
flows: { 'kit-activation': { slots: [{ code: 'find-kit' }, { steps: 'safety' }, { code: 'sampled' }] } },
|
|
57
|
+
access: { edit: ({ req }) => req.user?.role === 'editor' }, // required
|
|
58
|
+
media: 'media', // your upload collection for videos and captions, or false
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
// In your action, before doing anything:
|
|
62
|
+
const check = await answersFor(payload, { flow: 'kit-activation', answers, locale })
|
|
63
|
+
if (!check.ok) return refuse(check.problem)
|
|
64
|
+
await markSampled(kit, { confirmed: check.record })
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Commands
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
npm test
|
|
71
|
+
npm run typecheck
|
|
72
|
+
npm run build
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { Answer, Step } from '../types.js';
|
|
3
|
+
/** One screen of the flow, as the server's flowSteps() returns it. */
|
|
4
|
+
export type WizardSlot = {
|
|
5
|
+
code: string;
|
|
6
|
+
} | {
|
|
7
|
+
step: Step;
|
|
8
|
+
};
|
|
9
|
+
/** What a code step's renderer gets. */
|
|
10
|
+
export type CodeStepContext = {
|
|
11
|
+
/** Store `value` under `values[code]` (when given) and go to the next screen. */
|
|
12
|
+
next: (value?: unknown) => void;
|
|
13
|
+
/** Go to the previous screen. Does nothing on the first. */
|
|
14
|
+
back: () => void;
|
|
15
|
+
values: Record<string, unknown>;
|
|
16
|
+
answers: Answer[];
|
|
17
|
+
};
|
|
18
|
+
export type WizardResult = {
|
|
19
|
+
answers: Answer[];
|
|
20
|
+
values: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
export type WizardLabels = {
|
|
23
|
+
yes: string;
|
|
24
|
+
no: string;
|
|
25
|
+
next: string;
|
|
26
|
+
back: string;
|
|
27
|
+
stepOf: (n: number, m: number) => string;
|
|
28
|
+
/** Shown when a code slot has no renderer. That's a bug in the site, not something the person can fix. */
|
|
29
|
+
missingCode: (code: string) => string;
|
|
30
|
+
/** Shown when onFinish throws or rejects. The buttons come back so the person can try again. */
|
|
31
|
+
finishFailed: string;
|
|
32
|
+
/** Visible marker on the option or button chosen earlier, so the choice isn't shown by color alone. */
|
|
33
|
+
chosen: string;
|
|
34
|
+
};
|
|
35
|
+
export type WizardProps = {
|
|
36
|
+
slots: WizardSlot[];
|
|
37
|
+
renderCode: Record<string, (ctx: CodeStepContext) => ReactNode>;
|
|
38
|
+
onFinish: (result: WizardResult) => void | Promise<void>;
|
|
39
|
+
labels?: Partial<WizardLabels>;
|
|
40
|
+
};
|
|
41
|
+
export declare const defaultLabels: WizardLabels;
|
|
42
|
+
/**
|
|
43
|
+
* A guided flow, one slot per screen. State lives in memory only: nothing is
|
|
44
|
+
* written to localStorage, sessionStorage or cookies.
|
|
45
|
+
*/
|
|
46
|
+
export declare function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, }: WizardProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
|
4
|
+
export const defaultLabels = {
|
|
5
|
+
yes: 'Yes',
|
|
6
|
+
no: 'No',
|
|
7
|
+
next: 'Next',
|
|
8
|
+
back: 'Back',
|
|
9
|
+
stepOf: (n, m) => `Step ${n} of ${m}`,
|
|
10
|
+
missingCode: (code) => `This step ("${code}") can't be shown. Please contact the site.`,
|
|
11
|
+
finishFailed: "That didn't go through. Please try again.",
|
|
12
|
+
chosen: '(chosen)',
|
|
13
|
+
};
|
|
14
|
+
const buttonStyle = { minHeight: 44, minWidth: 44, padding: '0.5rem 1rem' };
|
|
15
|
+
function isCode(slot) {
|
|
16
|
+
return 'code' in slot;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A guided flow, one slot per screen. State lives in memory only: nothing is
|
|
20
|
+
* written to localStorage, sessionStorage or cookies.
|
|
21
|
+
*/
|
|
22
|
+
export function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, }) {
|
|
23
|
+
const labels = { ...defaultLabels, ...labelOverrides };
|
|
24
|
+
const baseId = useId();
|
|
25
|
+
const [index, setIndex] = useState(0);
|
|
26
|
+
// Answers keyed by slot index, so Back keeps them and answering again replaces them.
|
|
27
|
+
const [answers, setAnswers] = useState({});
|
|
28
|
+
const [values, setValues] = useState({});
|
|
29
|
+
const [stopMessage, setStopMessage] = useState('');
|
|
30
|
+
const [busy, setBusy] = useState(false);
|
|
31
|
+
const [done, setDone] = useState(false);
|
|
32
|
+
const [error, setError] = useState('');
|
|
33
|
+
const finishing = useRef(false);
|
|
34
|
+
const focusTarget = useRef(null);
|
|
35
|
+
const mounted = useRef(false);
|
|
36
|
+
// Move focus to the new screen's heading when the step changes. Not on first
|
|
37
|
+
// render, so the page doesn't jump to the wizard before the person gets there.
|
|
38
|
+
useEffect(() => {
|
|
39
|
+
if (!mounted.current) {
|
|
40
|
+
mounted.current = true;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
focusTarget.current?.focus();
|
|
44
|
+
}, [index]);
|
|
45
|
+
const ordered = (byIndex) => slots.flatMap((slot, i) => (!isCode(slot) && byIndex[i] ? [byIndex[i]] : []));
|
|
46
|
+
const advance = useCallback((nextAnswers, nextValues) => {
|
|
47
|
+
setStopMessage('');
|
|
48
|
+
setError('');
|
|
49
|
+
if (index < slots.length - 1) {
|
|
50
|
+
setIndex(index + 1);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (finishing.current)
|
|
54
|
+
return;
|
|
55
|
+
finishing.current = true;
|
|
56
|
+
setBusy(true);
|
|
57
|
+
const result = {
|
|
58
|
+
answers: slots.flatMap((slot, i) => (!isCode(slot) && nextAnswers[i] ? [nextAnswers[i]] : [])),
|
|
59
|
+
values: nextValues,
|
|
60
|
+
};
|
|
61
|
+
Promise.resolve()
|
|
62
|
+
.then(() => onFinish(result))
|
|
63
|
+
.then(() => setDone(true), () => {
|
|
64
|
+
finishing.current = false;
|
|
65
|
+
setBusy(false);
|
|
66
|
+
setError(labels.finishFailed);
|
|
67
|
+
});
|
|
68
|
+
}, [index, slots, onFinish, labels.finishFailed]);
|
|
69
|
+
const back = useCallback(() => {
|
|
70
|
+
if (busy || done || index === 0)
|
|
71
|
+
return;
|
|
72
|
+
setStopMessage('');
|
|
73
|
+
setError('');
|
|
74
|
+
setIndex(index - 1);
|
|
75
|
+
}, [busy, done, index]);
|
|
76
|
+
const record = (step, value) => {
|
|
77
|
+
const nextAnswers = { ...answers, [index]: { key: step.key, hash: step.hash, value } };
|
|
78
|
+
setAnswers(nextAnswers);
|
|
79
|
+
advance(nextAnswers, values);
|
|
80
|
+
};
|
|
81
|
+
// No withdraws an earlier Yes on this step: it's no longer shown as chosen, and the flow can't finish with it.
|
|
82
|
+
const stop = (message) => {
|
|
83
|
+
setStopMessage(message);
|
|
84
|
+
setAnswers((current) => {
|
|
85
|
+
if (!(index in current))
|
|
86
|
+
return current;
|
|
87
|
+
const { [index]: _withdrawn, ...rest } = current;
|
|
88
|
+
return rest;
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
if (slots.length === 0)
|
|
92
|
+
return null;
|
|
93
|
+
const slot = slots[index];
|
|
94
|
+
if (!slot)
|
|
95
|
+
return null;
|
|
96
|
+
const disabled = busy || done;
|
|
97
|
+
const progressId = `${baseId}-progress`;
|
|
98
|
+
const headingId = `${baseId}-heading`;
|
|
99
|
+
const progress = labels.stepOf(index + 1, slots.length);
|
|
100
|
+
const backButton = index > 0 ? (_jsx("button", { type: "button", style: buttonStyle, onClick: back, disabled: disabled, className: "wizard-back", children: labels.back })) : null;
|
|
101
|
+
const liveRegions = (_jsxs(_Fragment, { children: [_jsx("div", { role: "status", "aria-live": "polite", className: "wizard-stop", children: stopMessage ? _jsx("p", { children: stopMessage }) : null }), _jsx("div", { role: "alert", className: "wizard-error", children: error ? _jsx("p", { children: error }) : null })] }));
|
|
102
|
+
if (isCode(slot)) {
|
|
103
|
+
const render = renderCode[slot.code];
|
|
104
|
+
const ctx = {
|
|
105
|
+
next: (value) => {
|
|
106
|
+
if (disabled)
|
|
107
|
+
return;
|
|
108
|
+
const nextValues = value === undefined ? values : { ...values, [slot.code]: value };
|
|
109
|
+
setValues(nextValues);
|
|
110
|
+
advance(answers, nextValues);
|
|
111
|
+
},
|
|
112
|
+
back,
|
|
113
|
+
values,
|
|
114
|
+
answers: ordered(answers),
|
|
115
|
+
};
|
|
116
|
+
return (_jsxs("section", { className: "wizard", "data-slot": slot.code, "aria-labelledby": progressId, "aria-busy": busy || undefined, tabIndex: -1, ref: (el) => {
|
|
117
|
+
focusTarget.current = el;
|
|
118
|
+
}, children: [_jsx("p", { id: progressId, className: "wizard-progress", children: progress }), render ? render(ctx) : _jsx("p", { className: "wizard-missing", children: labels.missingCode(slot.code) }), liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
|
|
119
|
+
}
|
|
120
|
+
const step = slot.step;
|
|
121
|
+
const previous = answers[index]?.value;
|
|
122
|
+
return (_jsxs("section", { className: "wizard", "data-step": step.key, "aria-labelledby": headingId, "aria-busy": busy || undefined, children: [_jsx("p", { id: progressId, className: "wizard-progress", children: progress }), _jsx("h2", { id: headingId, tabIndex: -1, "aria-describedby": progressId, ref: (el) => {
|
|
123
|
+
focusTarget.current = el;
|
|
124
|
+
}, children: step.question }), step.video ? (
|
|
125
|
+
// Never autoplays; the person starts it. The text version below is always on the page.
|
|
126
|
+
_jsx("video", { controls: true, preload: "none", src: step.video.url, className: "wizard-video", children: _jsx("track", { kind: "captions", default: true, src: step.video.captionsUrl }) })) : null, step.body ? _jsx("p", { className: "wizard-body", children: step.body }) : null, step.kind === 'gate' ? (_jsxs("div", { className: "wizard-actions", role: "group", "aria-labelledby": headingId, children: [_jsxs("button", { type: "button", style: buttonStyle, disabled: disabled, "aria-pressed": previous === 'yes', onClick: () => record(step, 'yes'), children: [labels.yes, previous === 'yes' ? ` ${labels.chosen}` : null] }), _jsx("button", { type: "button", style: buttonStyle, disabled: disabled, onClick: () => stop(step.stopMessage), children: labels.no })] })) : null, step.kind === 'info' ? (_jsx("div", { className: "wizard-actions", children: _jsx("button", { type: "button", style: buttonStyle, disabled: disabled, onClick: () => record(step, 'seen'), children: labels.next }) })) : null, step.kind === 'choice' ? (_jsx("div", { className: "wizard-actions", role: "group", "aria-labelledby": headingId, children: step.options.map((option) => (_jsxs("button", { type: "button", style: buttonStyle, disabled: disabled, "aria-pressed": previous === option.value, onClick: () => (option.stops ? stop(step.stopMessage) : record(step, option.value)), children: [option.label, previous === option.value ? ` ${labels.chosen}` : null] }, option.value))) })) : null, liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
|
|
127
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/plugin.d.ts
ADDED
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { flowsOf, stepsCollection } from './steps.js';
|
|
2
|
+
/** Wizards: gated step-by-step flows, steps edited in the admin, and answers checked on the server. */
|
|
3
|
+
export const wizardsPlugin = (options) => (config) => {
|
|
4
|
+
const o = { slug: options.slug ?? 'guided-steps', flows: options.flows ?? {}, edit: options?.access?.edit, media: options.media === undefined ? 'media' : options.media, adminGroup: options.adminGroup ?? 'Wizards' };
|
|
5
|
+
if (typeof o.edit !== 'function')
|
|
6
|
+
throw new Error('Wizards: give `access.edit`, saying who may change the steps.');
|
|
7
|
+
if (o.media && !(config.collections ?? []).some((c) => c.slug === o.media && c.upload))
|
|
8
|
+
throw new Error(`Wizards: "${o.media}" isn't an upload collection. Set \`media\`, or false for no videos.`);
|
|
9
|
+
return {
|
|
10
|
+
...config,
|
|
11
|
+
custom: { ...config.custom, wizards: o },
|
|
12
|
+
collections: [...(config.collections ?? []), stepsCollection(o)],
|
|
13
|
+
onInit: async (payload) => {
|
|
14
|
+
flowsOf(payload);
|
|
15
|
+
await config.onInit?.(payload);
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
};
|
package/dist/steps.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { CollectionConfig, Payload } from 'payload';
|
|
2
|
+
import type { Flow, Resolved, Step, WizardRecord } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* What a person confirms, in the language they read it: question, body, kind, options, the stop message, and the
|
|
5
|
+
* video with its captions. Worked out each time a step is read in a locale, never stored, so it can't be stale or
|
|
6
|
+
* belong to another language.
|
|
7
|
+
*/
|
|
8
|
+
export declare const contentHash: (s: {
|
|
9
|
+
question?: unknown;
|
|
10
|
+
body?: unknown;
|
|
11
|
+
kind?: unknown;
|
|
12
|
+
options?: unknown;
|
|
13
|
+
stopMessage?: unknown;
|
|
14
|
+
video?: unknown;
|
|
15
|
+
captions?: unknown;
|
|
16
|
+
}) => string;
|
|
17
|
+
export declare const stepsCollection: (o: Resolved) => CollectionConfig;
|
|
18
|
+
/** Every flow: the site's own and those other plugins registered at `config.custom.wizardFlows`. One owner each. */
|
|
19
|
+
export declare function flowsOf(payload: Payload): Record<string, Flow>;
|
|
20
|
+
/**
|
|
21
|
+
* The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
|
|
22
|
+
* `empty` names any group of steps with no active step: the flow can't be passed until an editor fixes it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function flowSteps(payload: Payload, args: {
|
|
25
|
+
flow: string;
|
|
26
|
+
locale?: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
slots: ({
|
|
29
|
+
code: string;
|
|
30
|
+
} | {
|
|
31
|
+
step: Step;
|
|
32
|
+
})[];
|
|
33
|
+
empty: string[];
|
|
34
|
+
}>;
|
|
35
|
+
/**
|
|
36
|
+
* Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
|
|
37
|
+
* answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
|
|
38
|
+
* choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
|
|
39
|
+
* mistake never waves a flow through. A step changed since the screen loaded fails, and the person sees the new
|
|
40
|
+
* wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
|
|
41
|
+
* the person read it, with the answer and the time.
|
|
42
|
+
*/
|
|
43
|
+
export declare function answersFor(payload: Payload, args: {
|
|
44
|
+
flow: string;
|
|
45
|
+
answers: unknown;
|
|
46
|
+
locale?: string;
|
|
47
|
+
}): Promise<{
|
|
48
|
+
ok: true;
|
|
49
|
+
record: WizardRecord;
|
|
50
|
+
} | {
|
|
51
|
+
ok: false;
|
|
52
|
+
problem: 'unknownFlow' | 'noSteps' | 'badAnswers' | 'missing' | 'extra' | 'changed' | 'notYes';
|
|
53
|
+
key?: string;
|
|
54
|
+
}>;
|
package/dist/steps.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const configOf = (payload) => {
|
|
3
|
+
const o = payload.config.custom?.wizards;
|
|
4
|
+
if (!o)
|
|
5
|
+
throw new Error('Wizards: the plugin is not configured on this site.');
|
|
6
|
+
return o;
|
|
7
|
+
};
|
|
8
|
+
/** A media file as the hash sees it: its id and when it last changed, so a swapped or replaced file counts as new. */
|
|
9
|
+
const fileOf = (v) => (v && typeof v === 'object' ? [String(v.id ?? ''), String(v.updatedAt ?? '')] : v ? [String(v), ''] : null);
|
|
10
|
+
/**
|
|
11
|
+
* What a person confirms, in the language they read it: question, body, kind, options, the stop message, and the
|
|
12
|
+
* video with its captions. Worked out each time a step is read in a locale, never stored, so it can't be stale or
|
|
13
|
+
* belong to another language.
|
|
14
|
+
*/
|
|
15
|
+
export const contentHash = (s) => createHash('sha256')
|
|
16
|
+
.update(JSON.stringify([s.question ?? '', s.body ?? '', s.kind ?? '', s.options?.map((x) => { const o = x; return [o.value, o.label, Boolean(o.stops)]; }) ?? [], s.stopMessage ?? '', fileOf(s.video), fileOf(s.captions)]))
|
|
17
|
+
.digest('hex')
|
|
18
|
+
.slice(0, 24);
|
|
19
|
+
const idOf = (v) => (v && typeof v === 'object' ? v.id : v);
|
|
20
|
+
const beforeChange = (o) => async ({ data, originalDoc, req }) => {
|
|
21
|
+
const next = { ...originalDoc, ...data };
|
|
22
|
+
if (next.video && !next.captions)
|
|
23
|
+
throw new Error('A step with a video needs its captions (a WebVTT file).');
|
|
24
|
+
if (next.kind === 'choice' && !(Array.isArray(next.options) && next.options.length >= 2))
|
|
25
|
+
throw new Error('A choice step needs at least two options.');
|
|
26
|
+
if (next.kind === 'choice') {
|
|
27
|
+
const values = next.options.map((x) => String(x?.value ?? ''));
|
|
28
|
+
// One value for a stopping and a going-on option would let the check accept either.
|
|
29
|
+
if (new Set(values).size !== values.length)
|
|
30
|
+
throw new Error('Each option in a choice step needs its own value.');
|
|
31
|
+
}
|
|
32
|
+
if (next.kind !== 'info' && !String(next.stopMessage ?? '').trim())
|
|
33
|
+
throw new Error('A gate or choice step needs a stop message: what to do when the answer is No.');
|
|
34
|
+
if (o.media && (next.video || next.captions)) {
|
|
35
|
+
const mime = async (v) => String((await req.payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: true, req }).catch(() => null))?.mimeType ?? '');
|
|
36
|
+
if (next.video && !(await mime(next.video)).startsWith('video/'))
|
|
37
|
+
throw new Error('The video needs to be a video file.');
|
|
38
|
+
if (next.captions && !/^text\/(vtt|plain)$/.test(await mime(next.captions)))
|
|
39
|
+
throw new Error('The captions need to be a WebVTT (.vtt) file.');
|
|
40
|
+
}
|
|
41
|
+
return data;
|
|
42
|
+
};
|
|
43
|
+
export const stepsCollection = (o) => ({
|
|
44
|
+
slug: o.slug,
|
|
45
|
+
labels: { singular: 'Guided step', plural: 'Guided steps' },
|
|
46
|
+
admin: { group: o.adminGroup, useAsTitle: 'question', defaultColumns: ['flow', 'group', 'order', 'question', 'active'] },
|
|
47
|
+
access: {
|
|
48
|
+
read: async (args) => ((await o.edit(args)) === true ? true : { active: { equals: true } }),
|
|
49
|
+
create: async (args) => (await o.edit(args)) === true,
|
|
50
|
+
update: async (args) => (await o.edit(args)) === true,
|
|
51
|
+
delete: async (args) => (await o.edit(args)) === true,
|
|
52
|
+
},
|
|
53
|
+
hooks: { beforeChange: [beforeChange(o)] },
|
|
54
|
+
indexes: [{ fields: ['flow', 'key'], unique: true }],
|
|
55
|
+
fields: [
|
|
56
|
+
{ name: 'flow', type: 'text', required: true, index: true },
|
|
57
|
+
{ name: 'key', type: 'text', required: true, admin: { description: 'Stable: answers name it. Don’t reuse a key for a different question.' } },
|
|
58
|
+
{ name: 'group', type: 'text', required: true, admin: { description: 'The flow takes a group of steps in one place, such as "safety".' } },
|
|
59
|
+
{ name: 'order', type: 'number', defaultValue: 100 },
|
|
60
|
+
{ name: 'kind', type: 'select', required: true, defaultValue: 'gate', options: [{ label: 'Gate (Yes needed to go on)', value: 'gate' }, { label: 'Information (Next)', value: 'info' }, { label: 'Choice', value: 'choice' }] },
|
|
61
|
+
{ name: 'question', type: 'text', required: true, localized: true },
|
|
62
|
+
{ name: 'body', type: 'textarea', localized: true, admin: { description: 'The text version: everything the video says.' } },
|
|
63
|
+
...(o.media
|
|
64
|
+
? [
|
|
65
|
+
{ name: 'video', type: 'upload', relationTo: o.media },
|
|
66
|
+
{ name: 'captions', type: 'upload', relationTo: o.media, admin: { description: 'WebVTT captions. Required with a video.' } },
|
|
67
|
+
]
|
|
68
|
+
: []),
|
|
69
|
+
{
|
|
70
|
+
name: 'options',
|
|
71
|
+
type: 'array',
|
|
72
|
+
admin: { condition: (d) => d?.kind === 'choice' },
|
|
73
|
+
fields: [
|
|
74
|
+
{ name: 'value', type: 'text', required: true },
|
|
75
|
+
{ name: 'label', type: 'text', required: true, localized: true },
|
|
76
|
+
{ name: 'stops', type: 'checkbox', admin: { description: 'This answer stops the flow until changed.' } },
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
{ name: 'stopMessage', type: 'textarea', localized: true, admin: { description: 'What No says: what to do before going on.' } },
|
|
80
|
+
{ name: 'active', type: 'checkbox', defaultValue: true, index: true },
|
|
81
|
+
],
|
|
82
|
+
});
|
|
83
|
+
/** Every flow: the site's own and those other plugins registered at `config.custom.wizardFlows`. One owner each. */
|
|
84
|
+
export function flowsOf(payload) {
|
|
85
|
+
const o = configOf(payload);
|
|
86
|
+
const all = {};
|
|
87
|
+
const owner = {};
|
|
88
|
+
const add = (who, flows) => {
|
|
89
|
+
for (const [k, f] of Object.entries(flows ?? {})) {
|
|
90
|
+
if (owner[k])
|
|
91
|
+
throw new Error(`Wizards: the flow "${k}" is registered by both ${owner[k]} and ${who}.`);
|
|
92
|
+
if (!Array.isArray(f?.slots) || !f.slots.length)
|
|
93
|
+
throw new Error(`Wizards: the flow "${k}" from ${who} has no slots.`);
|
|
94
|
+
const groups = f.slots.flatMap((s) => ('steps' in s ? [s.steps] : []));
|
|
95
|
+
// A group in two slots would ask each step twice, and no answer could pass.
|
|
96
|
+
if (new Set(groups).size !== groups.length)
|
|
97
|
+
throw new Error(`Wizards: the flow "${k}" from ${who} uses a group of steps twice.`);
|
|
98
|
+
owner[k] = who;
|
|
99
|
+
all[k] = f;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
add('the site', o.flows);
|
|
103
|
+
const regs = payload.config.custom?.wizardFlows;
|
|
104
|
+
for (const r of Array.isArray(regs) ? regs : [])
|
|
105
|
+
add(String(r?.owner ?? 'a plugin'), r?.flows);
|
|
106
|
+
return all;
|
|
107
|
+
}
|
|
108
|
+
const urlOf = (v) => (v && typeof v === 'object' && typeof v.url === 'string' ? v.url : null);
|
|
109
|
+
/**
|
|
110
|
+
* The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
|
|
111
|
+
* `empty` names any group of steps with no active step: the flow can't be passed until an editor fixes it.
|
|
112
|
+
*/
|
|
113
|
+
export async function flowSteps(payload, args) {
|
|
114
|
+
const o = configOf(payload);
|
|
115
|
+
const flows = flowsOf(payload);
|
|
116
|
+
const flow = Object.hasOwn(flows, args.flow) ? flows[args.flow] : null;
|
|
117
|
+
if (!flow)
|
|
118
|
+
throw new Error(`Wizards: no flow "${args.flow}".`);
|
|
119
|
+
const docs = (await payload.find({ collection: o.slug, where: { and: [{ flow: { equals: args.flow } }, { active: { equals: true } }] }, sort: ['order', 'key'], pagination: false, depth: 1, overrideAccess: true, ...(args.locale ? { locale: args.locale } : {}) })).docs;
|
|
120
|
+
const out = [];
|
|
121
|
+
const empty = [];
|
|
122
|
+
for (const slot of flow.slots) {
|
|
123
|
+
if ('code' in slot)
|
|
124
|
+
out.push({ code: slot.code });
|
|
125
|
+
else {
|
|
126
|
+
const group = docs.filter((x) => x.group === slot.steps);
|
|
127
|
+
if (!group.length)
|
|
128
|
+
empty.push(slot.steps);
|
|
129
|
+
for (const d of group) {
|
|
130
|
+
const video = urlOf(d.video);
|
|
131
|
+
const captions = urlOf(d.captions);
|
|
132
|
+
out.push({
|
|
133
|
+
step: {
|
|
134
|
+
key: d.key,
|
|
135
|
+
group: d.group,
|
|
136
|
+
kind: d.kind,
|
|
137
|
+
question: d.question,
|
|
138
|
+
body: d.body ?? '',
|
|
139
|
+
video: video && captions ? { url: video, captionsUrl: captions } : null,
|
|
140
|
+
options: (d.options ?? []).map((x) => ({ value: String(x.value), label: String(x.label), stops: Boolean(x.stops) })),
|
|
141
|
+
stopMessage: d.stopMessage ?? '',
|
|
142
|
+
hash: contentHash(d),
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return { slots: out, empty };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
|
|
152
|
+
* answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
|
|
153
|
+
* choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
|
|
154
|
+
* mistake never waves a flow through. A step changed since the screen loaded fails, and the person sees the new
|
|
155
|
+
* wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
|
|
156
|
+
* the person read it, with the answer and the time.
|
|
157
|
+
*/
|
|
158
|
+
export async function answersFor(payload, args) {
|
|
159
|
+
let flow;
|
|
160
|
+
try {
|
|
161
|
+
flow = await flowSteps(payload, { flow: args.flow, locale: args.locale });
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return { ok: false, problem: 'unknownFlow' };
|
|
165
|
+
}
|
|
166
|
+
if (flow.empty.length)
|
|
167
|
+
return { ok: false, problem: 'noSteps', key: flow.empty[0] };
|
|
168
|
+
if (!Array.isArray(args.answers) || args.answers.some((a) => !a || typeof a !== 'object' || typeof a.key !== 'string' || typeof a.hash !== 'string' || typeof a.value !== 'string'))
|
|
169
|
+
return { ok: false, problem: 'badAnswers' };
|
|
170
|
+
const answers = args.answers;
|
|
171
|
+
const steps = flow.slots.flatMap((s) => ('step' in s ? [s.step] : []));
|
|
172
|
+
const byKey = new Map();
|
|
173
|
+
for (const a of answers)
|
|
174
|
+
byKey.set(a.key, [...(byKey.get(a.key) ?? []), a]);
|
|
175
|
+
for (const a of answers)
|
|
176
|
+
if (!steps.some((s) => s.key === a.key))
|
|
177
|
+
return { ok: false, problem: 'extra', key: a.key };
|
|
178
|
+
for (const s of steps) {
|
|
179
|
+
const given = byKey.get(s.key) ?? [];
|
|
180
|
+
if (given.length !== 1)
|
|
181
|
+
return { ok: false, problem: given.length ? 'extra' : 'missing', key: s.key };
|
|
182
|
+
const a = given[0];
|
|
183
|
+
if (a.hash !== s.hash)
|
|
184
|
+
return { ok: false, problem: 'changed', key: s.key };
|
|
185
|
+
if (s.kind === 'gate' && a.value !== 'yes')
|
|
186
|
+
return { ok: false, problem: 'notYes', key: s.key };
|
|
187
|
+
if (s.kind === 'info' && a.value !== 'seen')
|
|
188
|
+
return { ok: false, problem: 'notYes', key: s.key };
|
|
189
|
+
if (s.kind === 'choice') {
|
|
190
|
+
const opt = s.options.find((x) => x.value === a.value);
|
|
191
|
+
if (!opt || opt.stops)
|
|
192
|
+
return { ok: false, problem: 'notYes', key: s.key };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const localization = payload.config.localization;
|
|
196
|
+
const locale = args.locale ?? (localization ? localization.defaultLocale : null);
|
|
197
|
+
return { ok: true, record: { flow: args.flow, at: new Date().toISOString(), locale, answers: steps.map((s) => ({ key: s.key, hash: s.hash, value: byKey.get(s.key)[0].value, question: s.question })) } };
|
|
198
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Access, Payload, PayloadRequest } from 'payload';
|
|
2
|
+
export type Req = Partial<PayloadRequest>;
|
|
3
|
+
/** A slot in a flow: a code step the site renders, or every active guided step in a group, in order. */
|
|
4
|
+
export type Slot = {
|
|
5
|
+
code: string;
|
|
6
|
+
} | {
|
|
7
|
+
steps: string;
|
|
8
|
+
};
|
|
9
|
+
export type Flow = {
|
|
10
|
+
slots: Slot[];
|
|
11
|
+
};
|
|
12
|
+
export type FlowRegistration = {
|
|
13
|
+
owner: string;
|
|
14
|
+
flows: Record<string, Flow>;
|
|
15
|
+
};
|
|
16
|
+
/** A content step as the client gets it. */
|
|
17
|
+
export type Step = {
|
|
18
|
+
key: string;
|
|
19
|
+
group: string;
|
|
20
|
+
kind: 'gate' | 'info' | 'choice';
|
|
21
|
+
question: string;
|
|
22
|
+
body: string;
|
|
23
|
+
video: {
|
|
24
|
+
url: string;
|
|
25
|
+
captionsUrl: string;
|
|
26
|
+
} | null;
|
|
27
|
+
options: {
|
|
28
|
+
value: string;
|
|
29
|
+
label: string;
|
|
30
|
+
stops: boolean;
|
|
31
|
+
}[];
|
|
32
|
+
stopMessage: string;
|
|
33
|
+
hash: string;
|
|
34
|
+
};
|
|
35
|
+
/** What the client sends for each content step it showed: the step, the wording it saw, and the answer. */
|
|
36
|
+
export type Answer = {
|
|
37
|
+
key: string;
|
|
38
|
+
hash: string;
|
|
39
|
+
value: string;
|
|
40
|
+
};
|
|
41
|
+
/** What to store with the owner's action: which wording, in which language, was confirmed, and when. */
|
|
42
|
+
export type WizardRecord = {
|
|
43
|
+
flow: string;
|
|
44
|
+
at: string;
|
|
45
|
+
locale: string | null;
|
|
46
|
+
answers: (Answer & {
|
|
47
|
+
question: string;
|
|
48
|
+
})[];
|
|
49
|
+
};
|
|
50
|
+
export type WizardsOptions = {
|
|
51
|
+
flows?: Record<string, Flow>;
|
|
52
|
+
/** Who edits the steps. Required; only an answer of exactly true counts. */
|
|
53
|
+
access: {
|
|
54
|
+
edit: Access;
|
|
55
|
+
};
|
|
56
|
+
/** The upload collection for videos and captions. Default 'media'; `false` for no videos. */
|
|
57
|
+
media?: string | false;
|
|
58
|
+
slug?: string;
|
|
59
|
+
adminGroup?: string;
|
|
60
|
+
};
|
|
61
|
+
export type Resolved = {
|
|
62
|
+
slug: string;
|
|
63
|
+
flows: Record<string, Flow>;
|
|
64
|
+
edit: Access;
|
|
65
|
+
media: string | false;
|
|
66
|
+
adminGroup: string;
|
|
67
|
+
};
|
|
68
|
+
export type Ctx = {
|
|
69
|
+
payload: Payload;
|
|
70
|
+
req?: Req;
|
|
71
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-wizards",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.",
|
|
5
|
+
"homepage": "https://github.com/ExtantApe/payload-plugin-wizards#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/ExtantApe/payload-plugin-wizards/issues"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"payload",
|
|
11
|
+
"payload-plugin",
|
|
12
|
+
"payloadcms",
|
|
13
|
+
"forms",
|
|
14
|
+
"content",
|
|
15
|
+
"wizard",
|
|
16
|
+
"guided-steps",
|
|
17
|
+
"step-by-step",
|
|
18
|
+
"checklist",
|
|
19
|
+
"onboarding",
|
|
20
|
+
"accessibility"
|
|
21
|
+
],
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/ExtantApe/payload-plugin-wizards.git"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./client": {
|
|
34
|
+
"types": "./dist/client/index.d.ts",
|
|
35
|
+
"import": "./dist/client/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"main": "./dist/index.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"README.md",
|
|
43
|
+
"LICENSE"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"leak-check": "bash scripts/leak-check.sh",
|
|
53
|
+
"prepack": "npm run build",
|
|
54
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"payload": "^3.80.0",
|
|
58
|
+
"react": "^19.0.0"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@payloadcms/db-mongodb": "3.92.1",
|
|
62
|
+
"@testing-library/react": "^16.3.3",
|
|
63
|
+
"@types/node": "^24.0.0",
|
|
64
|
+
"@types/react": "^19.3.0",
|
|
65
|
+
"@types/react-dom": "^19.3.0",
|
|
66
|
+
"graphql": "^16.14.2",
|
|
67
|
+
"jsdom": "^31.0.0",
|
|
68
|
+
"mongodb-memory-server": "^11.3.0",
|
|
69
|
+
"payload": "3.92.1",
|
|
70
|
+
"react": "^19.3.1",
|
|
71
|
+
"react-dom": "^19.3.1",
|
|
72
|
+
"typescript": "^5.9.0",
|
|
73
|
+
"vitest": "^3.2.0"
|
|
74
|
+
},
|
|
75
|
+
"peerDependenciesMeta": {
|
|
76
|
+
"react": {
|
|
77
|
+
"optional": true
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|