Questionnaire
Questions one at a time: choose from a few answers or write your own, step back and forward, skip what is optional, and send them all at once as an ordinary form.
"use client";
import { useState, type FormEvent } from "react";
import {
Questionnaire,
QuestionnaireActions,
QuestionnaireChoice,
QuestionnaireChoices,
QuestionnaireDescription,
QuestionnaireError,
QuestionnaireInput,
QuestionnaireItem,
QuestionnaireNext,
QuestionnairePrevious,
QuestionnaireProgress,
QuestionnaireSkip,
QuestionnaireSubmit,
QuestionnaireTitle,
} from "@/components/ui/questionnaire";
const items = [
{
name: "direction",
required: true,
prompt: "What should we draw next?",
description: "Choose a direction or write your own.",
choices: [
{ value: "margins", label: "Margin notes", description: "Asides that point at the words they are about." },
{ value: "maps", label: "Maps", description: "Routes and borders, drawn in one pull." },
{ value: "both", label: "Both together" },
],
input: { label: "Another answer", placeholder: "Something else…" },
},
{
name: "detail",
required: false,
prompt: "How much detail?",
description: "Skip this if you are not sure yet.",
choices: [
{ value: "focused", label: "Focused" },
{ value: "complete", label: "The whole page" },
],
},
] as const;
export default function QuestionnaireDemo() {
const [sent, setSent] = useState<Record<string, string[]> | null>(null);
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
setSent(Object.fromEntries(items.map((item) => [item.name, data.getAll(item.name).map(String)])));
};
return (
<div className="flex w-full max-w-md flex-col gap-4">
<Questionnaire items={items} onSubmit={submit}>
<QuestionnaireProgress />
{items.map((question) => (
<QuestionnaireItem key={question.name} name={question.name} required={question.required}>
<QuestionnaireTitle>{question.prompt}</QuestionnaireTitle>
<QuestionnaireDescription>{question.description}</QuestionnaireDescription>
<QuestionnaireChoices>
{question.choices.map((choice) => (
<QuestionnaireChoice key={choice.value} value={choice.value}>
<span className="font-bold">{choice.label}</span>
{"description" in choice && <span className="text-sm text-ink-3">{choice.description}</span>}
</QuestionnaireChoice>
))}
{"input" in question && <QuestionnaireInput aria-label={question.input.label} placeholder={question.input.placeholder} />}
</QuestionnaireChoices>
<QuestionnaireError />
</QuestionnaireItem>
))}
<QuestionnaireActions>
<QuestionnairePrevious />
<QuestionnaireSkip />
<QuestionnaireNext />
<QuestionnaireSubmit />
</QuestionnaireActions>
</Questionnaire>
{sent && (
<pre className="text-sm text-ink-2" aria-live="polite">
{JSON.stringify(sent)}
</pre>
)}
</div>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ questionnaire"use client";
import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type FormEvent, type KeyboardEvent } from "react";
import { cn } from "@/lib/utils";
import { usePen } from "@/hooks/use-ink-box";
import { InkGlyph } from "@/lib/ink-glyphs";
import { InkOutline } from "@/lib/ink-outline";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
// Questions, one at a time: pick from a few answers, or write your own, step
// forward and back, skip what is optional, and send them all at once. It is
// a real <form>, so an answer goes out under its question's name and
// `new FormData(form)` reads them: answers.get("direction"), or getAll for a
// question that takes several.
type Entry = { name: string; required: boolean; multiple: boolean };
type Answer = { chosen: string[]; text: string };
const empty: Answer = { chosen: [], text: "" };
type QuestionnaireContextValue = {
entries: Entry[];
active: number;
answers: Record<string, Answer>;
errors: Record<string, string | undefined>;
setAnswer: (name: string, update: (answer: Answer) => Answer) => void;
register: (name: string) => () => void;
previous: () => void;
next: () => void;
skip: () => void;
};
const QuestionnaireContext = createContext<QuestionnaireContextValue | null>(null);
function useQuestionnaire() {
const context = useContext(QuestionnaireContext);
if (!context) throw new Error("Questionnaire parts must be used inside <Questionnaire>.");
return context;
}
type ItemContextValue = { name: string; id: string; multiple: boolean; answer: Answer; choose: (value: string) => void; write: (text: string) => void };
const ItemContext = createContext<ItemContextValue | null>(null);
function useItem() {
const context = useContext(ItemContext);
if (!context) throw new Error("Choices and answers must be used inside <QuestionnaireItem>.");
return context;
}
const isAnswered = (answer: Answer | undefined) => !!answer && (answer.chosen.length > 0 || answer.text.trim() !== "");
/**
* The form. Give it `items` (name, required, multiple) and it knows the order
* and the count from the first render, server included; without them it learns
* them from the QuestionnaireItems inside, in the order they mount. A question
* marked `required` can't be stepped past, or submitted, unanswered.
*/
function Questionnaire({
items,
activeItem,
defaultActiveItem,
onActiveItemChange,
defaultAnswers,
shortcuts = false,
className,
children,
onSubmit,
onKeyDown,
...props
}: Omit<ComponentProps<"form">, "onSubmit"> & {
items?: readonly { name: string; required?: boolean; multiple?: boolean }[];
/** The question showing, by name, for the page to control. */
activeItem?: string;
defaultActiveItem?: string;
onActiveItemChange?: (name: string) => void;
/** Answers to start from: a value, or a list of them for a question that takes several. */
defaultAnswers?: Record<string, string | string[]>;
/** Number the answers 1–9 and let those keys choose them. */
shortcuts?: boolean;
onSubmit?: (event: FormEvent<HTMLFormElement>) => void;
}) {
const form = useRef<HTMLFormElement>(null);
const [registered, setRegistered] = useState<string[]>([]);
const [own, setOwn] = useState<string | undefined>(defaultActiveItem);
const [answers, setAnswers] = useState<Record<string, Answer>>(() =>
Object.fromEntries(Object.entries(defaultAnswers ?? {}).map(([name, value]) => [name, { chosen: [value].flat(), text: "" }])),
);
const [errors, setErrors] = useState<Record<string, string | undefined>>({});
const moved = useRef(false);
// The questions, in order: the ones you gave, or the ones that have mounted.
const [seen, setSeen] = useState<Record<string, { required: boolean; multiple: boolean }>>({});
const entries = useMemo<Entry[]>(
() => (items ?? registered.map((name): { name: string; required?: boolean; multiple?: boolean } => ({ name }))).map((item) => ({ name: item.name, required: item.required ?? seen[item.name]?.required ?? false, multiple: item.multiple ?? seen[item.name]?.multiple ?? false })),
[items, registered, seen],
);
const name = activeItem ?? own ?? entries[0]?.name;
const found = entries.findIndex((entry) => entry.name === name);
const active = found === -1 ? 0 : found;
const register = useCallback((id: string) => {
setRegistered((all) => (all.includes(id) ? all : [...all, id]));
return () => setRegistered((all) => all.filter((other) => other !== id));
}, []);
const go = useCallback(
(index: number) => {
const target = entries[index];
if (!target) return;
moved.current = true;
setOwn(target.name);
onActiveItemChange?.(target.name);
},
[entries, onActiveItemChange],
);
const setAnswer = useCallback(
(key: string, update: (answer: Answer) => Answer) => {
setAnswers((all) => ({ ...all, [key]: update(all[key] ?? empty) }));
setErrors((all) => (all[key] ? { ...all, [key]: undefined } : all));
},
[],
);
/** Can this question be left? A required one must be answered first. */
const check = (index: number) => {
const entry = entries[index];
if (!entry?.required || isAnswered(answers[entry.name])) return true;
setErrors((all) => ({ ...all, [entry.name]: "Choose an answer to carry on." }));
focusFirst(form.current, entry.name);
return false;
};
const next = () => {
if (check(active)) go(active + 1);
};
const skip = () => {
const entry = entries[active];
if (entry) setAnswers((all) => ({ ...all, [entry.name]: empty }));
if (active < entries.length - 1) go(active + 1);
else form.current?.requestSubmit();
};
// After stepping, the new question takes focus.
useEffect(() => {
if (!moved.current) return;
moved.current = false;
focusFirst(form.current, entries[active]?.name);
}, [active, entries]);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
const missing = entries.map((entry, i) => ({ entry, i })).filter(({ entry }) => entry.required && !isAnswered(answers[entry.name]));
if (missing.length) {
event.preventDefault();
setErrors((all) => ({ ...all, ...Object.fromEntries(missing.map(({ entry }) => [entry.name, "Choose an answer to carry on."])) }));
go(missing[0].i);
return;
}
onSubmit?.(event);
};
const handleKeyDown = (event: KeyboardEvent<HTMLFormElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const target = event.target as HTMLElement;
const typing = target instanceof HTMLInputElement && target.type === "text";
// Enter in a text field goes on to the next question; it only sends on the last.
if (event.key === "Enter" && typing) {
event.preventDefault();
if (active < entries.length - 1) next();
else form.current?.requestSubmit();
} else if (shortcuts && !typing && /^[1-9]$/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) {
const choices = form.current?.querySelectorAll<HTMLInputElement>("[data-slot=questionnaire-item]:not([hidden]) [data-slot=questionnaire-choice] input");
const choice = choices?.[Number(event.key) - 1];
if (choice) {
event.preventDefault();
choice.click();
}
}
};
const context: QuestionnaireContextValue = { entries, active, answers, errors, setAnswer, register, previous: () => go(active - 1), next, skip };
return (
<QuestionnaireContext value={context}>
<SeenContext value={setSeen}>
<form
ref={form}
noValidate
data-slot="questionnaire"
data-shortcuts={shortcuts ? "" : undefined}
className={cn("group/questionnaire flex w-full flex-col gap-5 text-base", className)}
onSubmit={handleSubmit}
onKeyDown={handleKeyDown}
{...props}
>
{children}
</form>
</SeenContext>
</QuestionnaireContext>
);
}
const SeenContext = createContext<(update: (seen: Record<string, { required: boolean; multiple: boolean }>) => Record<string, { required: boolean; multiple: boolean }>) => void>(() => {});
/** Puts focus on a question's first answer. */
function focusFirst(form: HTMLFormElement | null, name?: string) {
if (!form || !name) return;
const items = form.querySelectorAll<HTMLElement>("[data-slot=questionnaire-item]");
for (const item of items) {
if (item.dataset.name === name) {
const control = item.querySelector<HTMLElement>("input:not([type=hidden])");
// Wait a frame: the question may only just have been shown.
requestAnimationFrame(() => control?.focus());
}
}
}
/** How far along: a bar, named "Question 2 of 5" for screen readers. */
function QuestionnaireProgress({ className, ...props }: Omit<ComponentProps<typeof Progress>, "value" | "aria-label">) {
const { entries, active } = useQuestionnaire();
const count = Math.max(entries.length, 1);
return <Progress data-slot="questionnaire-progress" size="sm" value={((active + 1) / count) * 100} aria-label={`Question ${active + 1} of ${count}`} className={className} {...props} />;
}
/** One question: a fieldset, only the current one showing. */
function QuestionnaireItem({
name,
required = false,
multiple = false,
className,
children,
...props
}: Omit<ComponentProps<"fieldset">, "name"> & { name: string; required?: boolean; multiple?: boolean }) {
const { entries, active, answers, errors, setAnswer, register } = useQuestionnaire();
const setSeen = useContext(SeenContext);
const id = useId();
useLayoutEffect(() => register(name), [register, name]);
useLayoutEffect(() => {
setSeen((all) => ({ ...all, [name]: { required, multiple } }));
}, [setSeen, name, required, multiple]);
const index = entries.findIndex((entry) => entry.name === name);
const showing = index === active;
const answer = answers[name] ?? empty;
const error = errors[name];
const context = useMemo<ItemContextValue>(
() => ({
name,
id,
multiple,
answer,
choose: (value) =>
setAnswer(name, (a) => (multiple ? { ...a, chosen: a.chosen.includes(value) ? a.chosen.filter((v) => v !== value) : [...a.chosen, value] } : { chosen: [value], text: "" })),
write: (text) => setAnswer(name, (a) => ({ chosen: multiple || !text ? a.chosen : [], text })),
}),
[name, id, multiple, answer, setAnswer],
);
return (
<ItemContext value={context}>
<fieldset
data-slot="questionnaire-item"
data-name={name}
data-required={required ? "" : undefined}
hidden={!showing}
inert={!showing}
aria-invalid={error ? true : undefined}
aria-describedby={error ? `${id}-error` : undefined}
className={cn("flex min-w-0 flex-col gap-3", className)}
{...props}
>
{children}
{answer.chosen.map((value) => (
<input key={value} type="hidden" name={name} value={value} />
))}
{answer.text.trim() !== "" && <input type="hidden" name={name} value={answer.text} />}
</fieldset>
</ItemContext>
);
}
/** The question. */
function QuestionnaireTitle({ className, ...props }: ComponentProps<"legend">) {
return <legend data-slot="questionnaire-title" className={cn("mb-1 text-xl leading-snug font-bold", className)} {...props} />;
}
function QuestionnaireDescription({ className, ...props }: ComponentProps<"p">) {
return <p data-slot="questionnaire-description" className={cn("-mt-1 text-base text-ink-3", className)} {...props} />;
}
/** The answers to choose from, numbered when the form has `shortcuts`. */
function QuestionnaireChoices({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="questionnaire-choices" className={cn("flex flex-col gap-2 [counter-reset:choice]", className)} {...props} />;
}
/** One answer, pencilled round: it is inked over when chosen. A radio for one answer, a checkbox when the question takes several. */
function QuestionnaireChoice({ value, className, children, ...props }: Omit<ComponentProps<"label">, "children"> & { value: string; children?: React.ReactNode }) {
const item = useItem();
const pen = usePen({ passes: 1, corners: "joined" });
const markPen = usePen({ passes: 1 });
const checked = item.answer.chosen.includes(value);
return (
<label
data-slot="questionnaire-choice"
data-checked={checked ? "" : undefined}
className={cn(
"group/choice relative isolate flex cursor-pointer items-start gap-3 px-3.5 py-2.5 text-left [counter-increment:choice] has-focus-visible:outline-solid has-focus-visible:outline-[1.5px] has-focus-visible:outline-offset-3 has-focus-visible:outline-ring has-focus-visible:[border-radius:var(--hand-radius)]",
className,
)}
{...props}
>
{/* Not part of the form (it names a form that isn't there): the answer is sent under the question's own name. */}
<input
type={item.multiple ? "checkbox" : "radio"}
name={`${item.name}:choice`}
form="questionnaire-detached"
value={value}
checked={checked}
onChange={() => item.choose(value)}
className="peer sr-only"
/>
<InkOutline pen={pen} estimate={[320, 48]} maxRadius={14} className="text-ink-line transition-colors duration-(--dur-hover) group-hover/choice:text-ink group-data-checked/choice:text-ink" />
<span aria-hidden="true" className="relative mt-0.5 flex size-5 shrink-0 items-center justify-center text-ink-3 transition-colors group-data-checked/choice:text-ink">
<InkOutline pen={markPen} shape={item.multiple ? "box" : "ring"} estimate={[20, 20]} pad={3} maxRadius={5} />
<InkGlyph name={item.multiple ? "check" : "dot"} className="size-3.5 opacity-0 transition-opacity duration-(--dur-hover) group-data-checked/choice:opacity-100" />
</span>
<span className="relative flex min-w-0 flex-1 flex-col gap-0.5">{children}</span>
<span aria-hidden="true" className="relative mt-0.5 hidden h-5 min-w-5 items-center justify-center text-sm text-ink-3 before:content-[counter(choice)] group-data-shortcuts/questionnaire:flex">
{" "}
</span>
</label>
);
}
/** Where a reader writes an answer of their own: typing it sets any chosen answer aside (for a question that takes one). It needs a label: `aria-label` will do. */
function QuestionnaireInput({ className, ...props }: Omit<ComponentProps<typeof Input>, "value" | "defaultValue" | "onChange" | "name">) {
const item = useItem();
return <Input data-slot="questionnaire-input" value={item.answer.text} onChange={(event) => item.write(event.target.value)} className={className} {...props} />;
}
/** Says why the question can't be left yet, in red pen. */
function QuestionnaireError({ className, children, ...props }: ComponentProps<"div">) {
const item = useItem();
const { errors } = useQuestionnaire();
const message = errors[item.name];
if (!message) return null;
return (
<div id={`${item.id}-error`} role="alert" data-slot="questionnaire-error" className={cn("text-sm text-destructive", className)} {...props}>
{children ?? message}
</div>
);
}
function QuestionnaireActions({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="questionnaire-actions" className={cn("flex flex-wrap items-center gap-3", className)} {...props} />;
}
function QuestionnairePrevious({ children = "Back", variant = "ghost", ...props }: ComponentProps<typeof Button>) {
const { active, previous } = useQuestionnaire();
if (active === 0) return null;
return (
<Button data-slot="questionnaire-previous" type="button" variant={variant} onClick={previous} {...props}>
{children}
</Button>
);
}
/** Leaves an optional question unanswered and goes on. Not shown for a required one. */
function QuestionnaireSkip({ children = "Skip", variant = "ghost", ...props }: ComponentProps<typeof Button>) {
const { entries, active, skip } = useQuestionnaire();
if (entries[active]?.required !== false) return null;
return (
<Button data-slot="questionnaire-skip" type="button" variant={variant} onClick={skip} {...props}>
{children}
</Button>
);
}
function QuestionnaireNext({ children = "Next", variant = "outline", ...props }: ComponentProps<typeof Button>) {
const { entries, active, next } = useQuestionnaire();
if (active >= entries.length - 1) return null;
return (
<Button data-slot="questionnaire-next" type="button" variant={variant} onClick={next} {...props}>
{children}
</Button>
);
}
/** Sends the answers, on the last question. */
function QuestionnaireSubmit({ children = "Submit", ...props }: ComponentProps<typeof Button>) {
const { entries, active } = useQuestionnaire();
if (entries.length > 0 && active < entries.length - 1) return null;
return (
<Button data-slot="questionnaire-submit" type="submit" {...props}>
{children}
</Button>
);
}
export {
Questionnaire,
QuestionnaireProgress,
QuestionnaireItem,
QuestionnaireTitle,
QuestionnaireDescription,
QuestionnaireChoices,
QuestionnaireChoice,
QuestionnaireInput,
QuestionnaireError,
QuestionnaireActions,
QuestionnairePrevious,
QuestionnaireSkip,
QuestionnaireNext,
QuestionnaireSubmit,
};Usage
import { Questionnaire, QuestionnaireActions, QuestionnaireChoice, QuestionnaireChoices, QuestionnaireItem, QuestionnaireNext, QuestionnaireSubmit, QuestionnaireTitle } from "@/components/ui/questionnaire"
<Questionnaire onSubmit={(event) => { event.preventDefault(); const answers = new FormData(event.currentTarget) }}>
<QuestionnaireItem name="direction" required>
<QuestionnaireTitle>What should we draw next?</QuestionnaireTitle>
<QuestionnaireChoices>
<QuestionnaireChoice value="margins">Margin notes</QuestionnaireChoice>
<QuestionnaireChoice value="maps">Maps</QuestionnaireChoice>
</QuestionnaireChoices>
</QuestionnaireItem>
<QuestionnaireActions>
<QuestionnaireNext />
<QuestionnaireSubmit />
</QuestionnaireActions>
</Questionnaire>Examples
Several answers, with shortcuts
A question that takes more than one; `shortcuts` numbers the answers and lets the keys 1–9 choose them.
"use client";
import { useState, type FormEvent } from "react";
import {
Questionnaire,
QuestionnaireActions,
QuestionnaireChoice,
QuestionnaireChoices,
QuestionnaireDescription,
QuestionnaireError,
QuestionnaireItem,
QuestionnaireSubmit,
QuestionnaireTitle,
} from "@/components/ui/questionnaire";
const pens = ["Blue ballpoint", "Black gel", "Red felt tip", "Pencil"];
export default function QuestionnaireMultiple() {
const [sent, setSent] = useState<string[] | null>(null);
return (
<div className="flex w-full max-w-md flex-col gap-4">
<Questionnaire
shortcuts
onSubmit={(event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSent(new FormData(event.currentTarget).getAll("pens").map(String));
}}
>
<QuestionnaireItem name="pens" multiple required>
<QuestionnaireTitle>Which pens are on your desk?</QuestionnaireTitle>
<QuestionnaireDescription>Pick as many as you like: press 1 to 4.</QuestionnaireDescription>
<QuestionnaireChoices>
{pens.map((pen) => (
<QuestionnaireChoice key={pen} value={pen}>
{pen}
</QuestionnaireChoice>
))}
</QuestionnaireChoices>
<QuestionnaireError />
</QuestionnaireItem>
<QuestionnaireActions>
<QuestionnaireSubmit>Send</QuestionnaireSubmit>
</QuestionnaireActions>
</Questionnaire>
{sent && <p className="text-ink-2">You chose {sent.join(", ")}.</p>}
</div>
);
}API reference
- Questionnaire items
{ name, required?, multiple? }[]The questions in order. Given, the count and the first question render on the server; without it they are learnt from the items inside.
- Questionnaire activeItem / defaultActiveItem / onActiveItemChange
stringThe question showing, by name, controlled or not.
- Questionnaire defaultAnswers
Record<string, string | string[]>Answers to start from, to resume a saved form.
- Questionnaire shortcutsdefault
false booleanNumber the answers and let the keys 1–9 choose them.
- Questionnaire onSubmit
(event) => voidCalled once every required question is answered. Read the answers with new FormData(event.currentTarget).
- QuestionnaireItem name / required / multiple
string / boolean / booleanThe answer's name in the form data; whether it can be left; radios or checkboxes.
- QuestionnaireInput
Input propsA write-in answer. It needs a label: aria-label will do. Typing sets a chosen answer aside, for a question that takes one.
- QuestionnaireSkip / Next / Previous / Submit
Button propsSkip is only shown for optional questions; Submit only on the last.