Questionnaire
SaveAn agent's clarifying questions as one compact step card: single or multiple choice, an Other field, number keys, Back and Skip, and a review of every answer before sending.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Questionnaire preview
Before I write the migration plan, three quick questions.
Migration plan
Which tables should the migration touch first?
I found 14 tables that still use integer ids.
Installation
npx @shakenui/cli add questionnaireReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add questionnaire --dry-runUsage
questionnaire-example.tsx
"use client";
import { useState } from "react";
import { type Question, type QuestionnaireAnswers, Questionnaire, formatAnswer } from "@/components/shaken/agent/questionnaire";
const scope: Question = {
id: "scope",
title: "Which tables should the migration touch first?",
description: "I found 14 tables that still use integer ids.",
options: [
{ value: "billing", label: "Billing only", description: "invoices, payments, refunds" },
{ value: "core", label: "Core models", description: "users, workspaces, memberships" },
{ value: "all", label: "All 14 tables", description: "One migration, longer lock window" },
],
allowOther: true,
otherPlaceholder: "List the tables",
};
const environments: Question = {
id: "environments",
title: "Where should it run?",
type: "multiple",
options: [
{ value: "preview", label: "Preview branches" },
{ value: "staging", label: "Staging" },
{ value: "production", label: "Production", description: "Needs a maintenance window" },
],
required: true,
};
const downtime: Question = {
id: "downtime",
title: "How much downtime is acceptable?",
options: [
{ value: "none", label: "None", description: "Dual-write, then backfill in batches" },
{ value: "minutes", label: "A few minutes", description: "Faster, single cutover" },
],
};
const questions = [scope, environments, downtime];
export default function QuestionnaireExample() {
const [sent, setSent] = useState<QuestionnaireAnswers | null>(null);
return (
<div className="grid w-full max-w-md gap-3">
<p className="text-sm text-zinc-600 dark:text-zinc-400">Before I write the migration plan, three quick questions.</p>
<Questionnaire title="Migration plan" questions={questions} onSubmit={setSent} />
{sent ? (
<p className="text-xs text-zinc-500">
Planning for {formatAnswer(scope, sent.scope).toLowerCase()} in {formatAnswer(environments, sent.environments).toLowerCase()}.
</p>
) : null}
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| questions | Question[] | — | The steps. Each has an id, title, optional description, type ("single" or "multiple"), options ({ value, label, description? }), allowOther, otherPlaceholder, and required. |
| title | ReactNode | "A few questions" | Small heading above the steps; names the card for screen readers. |
| defaultAnswers | Record<string, QuestionAnswer> | — | Answers to start from, keyed by question id. An answer is { values, other?, skipped? }. |
| onAnswerChange | (questionId, answer, answers) => void | — | Called whenever an answer changes. |
| onSubmit | (answers) => void | — | Called with every answer when the user sends them from the review step. |
| onDismiss | () => void | — | Adds a close button and closes on Escape. |
| submitLabel | string | "Send answers" | Label of the send button on the review step. |
| advanceDelay | number | 260 | Milliseconds between picking a single-choice answer and moving to the next question. |
| defaultSubmitted | boolean | false | Starts in the sent state with the answers shown read-only. |
| formatAnswer | (question, answer) => string | — | Helper: an answer as readable text, e.g. "Preview branches, Staging" or "Skipped". |
Accessibility
- The card is a region named by its title. Single-choice options are a radiogroup of role="radio" buttons with one tab stop; multiple-choice options are role="checkbox" buttons in a group named by the question.
- Number keys 1 to 9 pick the matching option (each row declares aria-keyshortcuts); the key after the last option focuses the Other field. Up and Down arrows move between options; Enter in the Other field moves on; Escape dismisses when onDismiss is set.
- When a step changes while focus is in the card, focus moves to the chosen or first option of the new step, and after sending it moves to the "Answers sent" status line.
- Progress is a progressbar with a value text such as "Question 2 of 3"; skipped questions read "Skipped" in the review.
- Focus rings are solid sky outlines on every option, the Other field's row, and each button.
- With reduced motion, steps cross-fade in place without sliding or blur, the card height changes instantly, and the progress fill and check marks do not animate.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/questionnaire.tsxquestionnaire- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/questionnaire/0.1.0.json.
agent/questionnaire.tsxShowHide
agent/questionnaire.tsx
"use client";
import { AnimatePresence, motion, useReducedMotion, type Variants } from "motion/react";
import {
type ComponentProps,
type KeyboardEvent,
type ReactNode,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const quint = [0.23, 1, 0.32, 1] as const;
export interface QuestionOption {
value: string;
label: string;
/** One line under the label. */
description?: string;
}
export interface Question {
id: string;
/** The question itself, e.g. "Which environments should the migration run in?" */
title: string;
/** Context under the question. */
description?: ReactNode;
/** single picks one answer and moves on; multiple toggles any number. @default "single" */
type?: "single" | "multiple";
options: QuestionOption[];
/** Adds a last row with a text field for an answer that is not listed. */
allowOther?: boolean;
/** Placeholder for the Other field. @default "Something else" */
otherPlaceholder?: string;
/** Hides Skip, so the question needs an answer. */
required?: boolean;
}
export interface QuestionAnswer {
/** Values of the chosen options. */
values: string[];
/** Text typed into Other, when it is chosen. */
other?: string;
/** The question was skipped. */
skipped?: boolean;
}
export type QuestionnaireAnswers = Record<string, QuestionAnswer>;
export interface QuestionnaireProps extends Omit<ComponentProps<"section">, "children" | "onSubmit" | "title"> {
questions: Question[];
/** Heading above the steps, e.g. "Before I plan the migration". */
title?: ReactNode;
/** Answers to start from. */
defaultAnswers?: QuestionnaireAnswers;
/** Called whenever an answer changes. */
onAnswerChange?: (questionId: string, answer: QuestionAnswer, answers: QuestionnaireAnswers) => void;
/** Called with every answer when the user sends them from the review step. */
onSubmit?: (answers: QuestionnaireAnswers) => void;
/** Adds a close button and closes on Escape. */
onDismiss?: () => void;
/** Label of the send button on the review step. @default "Send answers" */
submitLabel?: string;
/** Pause between picking a single-choice answer and the next question, so the choice is seen landing. @default 260 */
advanceDelay?: number;
/** Starts in the sent state, showing the answers read-only. */
defaultSubmitted?: boolean;
}
function hasAnswer(answer: QuestionAnswer | undefined) {
return Boolean(answer && !answer.skipped && (answer.values.length > 0 || (answer.other ?? "").trim()));
}
/** Readable text for an answer: option labels joined, then the Other text. */
export function formatAnswer(question: Question, answer: QuestionAnswer | undefined): string {
if (!answer || answer.skipped) return "Skipped";
const labels = question.options.filter((option) => answer.values.includes(option.value)).map((option) => option.label);
const other = (answer.other ?? "").trim();
if (other) labels.push(other);
return labels.length ? labels.join(", ") : "No answer";
}
const slide: Variants = {
enter: (direction: number) => ({ x: direction * 18, opacity: 0, filter: "blur(3px)" }),
center: { x: 0, opacity: 1, filter: "blur(0px)" },
exit: (direction: number) => ({ x: direction * -12, opacity: 0, filter: "blur(2px)" }),
};
// Same resting pose as the slide, so the server render matches either way.
const fade: Variants = {
enter: { x: 0, opacity: 0, filter: "blur(0px)" },
center: { x: 0, opacity: 1, filter: "blur(0px)" },
exit: { x: 0, opacity: 0, filter: "blur(0px)" },
};
/**
* An agent's clarifying questions as one compact step card in the thread: pick with the mouse or
* the number keys, type an Other answer, go Back or Skip, then review every answer before sending.
* Questions slide in the direction of travel while the card's height eases to fit.
*/
export function Questionnaire({
questions,
title,
defaultAnswers,
onAnswerChange,
onSubmit,
onDismiss,
submitLabel = "Send answers",
advanceDelay = 260,
defaultSubmitted = false,
className,
onKeyDown,
...props
}: QuestionnaireProps) {
const id = useId();
const reduce = useReducedMotion();
const [step, setStep] = useState(defaultSubmitted ? questions.length : 0);
const [direction, setDirection] = useState(1);
const [answers, setAnswers] = useState<QuestionnaireAnswers>(defaultAnswers ?? {});
const [submitted, setSubmitted] = useState(defaultSubmitted);
const [pressed, setPressed] = useState<string | null>(null);
const rootRef = useRef<HTMLElement>(null);
const bodyRef = useRef<HTMLDivElement>(null);
const advanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Set when a step change should carry focus into the new step (focus was inside the card).
const moveFocus = useRef(false);
const [height, setHeight] = useState<number | "auto">("auto");
const total = questions.length;
const reviewing = step >= total;
const question = reviewing ? null : questions[step];
const answer = question ? answers[question.id] : undefined;
const stepKey = question ? question.id : "review";
const scope = `[data-step-key="${typeof CSS !== "undefined" ? CSS.escape(stepKey) : stepKey}"]`;
useEffect(
() => () => {
if (advanceTimer.current) clearTimeout(advanceTimer.current);
if (pressTimer.current) clearTimeout(pressTimer.current);
},
[],
);
// The card's height follows the active step. The outgoing step is taken out of flow while it
// leaves, so the measured box is always the incoming step.
useLayoutEffect(() => {
const body = bodyRef.current;
if (!body) return;
const measure = () => setHeight(body.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(body);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (!moveFocus.current) return;
moveFocus.current = false;
const root = rootRef.current;
if (!root) return;
const target =
root.querySelector<HTMLElement>(`${scope} [aria-checked="true"]`) ??
root.querySelector<HTMLElement>(`${scope} [data-option]`) ??
root.querySelector<HTMLElement>("[data-autofocus]");
target?.focus({ preventScroll: true });
}, [step]);
function go(next: number) {
if (advanceTimer.current) clearTimeout(advanceTimer.current);
advanceTimer.current = null;
const clamped = Math.max(0, Math.min(total, next));
if (clamped === step) return;
moveFocus.current = Boolean(rootRef.current?.contains(document.activeElement));
setDirection(clamped > step ? 1 : -1);
setStep(clamped);
}
function update(questionId: string, next: QuestionAnswer) {
setAnswers((current) => {
const all = { ...current, [questionId]: next };
onAnswerChange?.(questionId, next, all);
return all;
});
}
function flash(key: string) {
setPressed(key);
if (pressTimer.current) clearTimeout(pressTimer.current);
pressTimer.current = setTimeout(() => setPressed(null), 140);
}
function pick(option: QuestionOption) {
if (!question || submitted) return;
flash(option.value);
if (question.type === "multiple") {
const values = answer?.values ?? [];
const nextValues = values.includes(option.value) ? values.filter((value) => value !== option.value) : [...values, option.value];
update(question.id, { values: nextValues, other: answer?.other });
return;
}
update(question.id, { values: [option.value] });
if (advanceTimer.current) clearTimeout(advanceTimer.current);
const from = step;
advanceTimer.current = setTimeout(() => {
advanceTimer.current = null;
moveFocus.current = Boolean(rootRef.current?.contains(document.activeElement));
setDirection(1);
setStep((current) => (current === from ? from + 1 : current));
}, advanceDelay);
}
function setOther(text: string) {
if (!question) return;
if (question.type === "multiple") update(question.id, { values: answer?.values ?? [], other: text });
else update(question.id, { values: [], other: text });
}
function skip() {
if (!question) return;
update(question.id, { values: [], skipped: true });
go(step + 1);
}
function submit() {
setSubmitted(true);
onSubmit?.(answers);
// The send button goes away; keep focus in the card on the confirmation.
requestAnimationFrame(() => rootRef.current?.querySelector<HTMLElement>("[data-sent]")?.focus({ preventScroll: true }));
}
function handleKeyDown(event: KeyboardEvent<HTMLElement>) {
onKeyDown?.(event);
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target as HTMLElement;
const typing = target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable;
if (event.key === "Escape" && onDismiss) {
if (typing && (target as HTMLInputElement).value) return;
event.preventDefault();
onDismiss();
return;
}
if (typing || !question || submitted) return;
if (/^[1-9]$/.test(event.key)) {
const index = Number(event.key) - 1;
if (index < question.options.length) {
event.preventDefault();
pick(question.options[index]!);
} else if (index === question.options.length && question.allowOther) {
event.preventDefault();
rootRef.current?.querySelector<HTMLInputElement>(`${scope} [data-other-input]`)?.focus();
}
return;
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
const rows = Array.from(rootRef.current?.querySelectorAll<HTMLElement>(`${scope} [data-option]`) ?? []);
const index = rows.indexOf(target);
if (index === -1) return;
event.preventDefault();
rows[(index + (event.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length]?.focus();
}
}
const titleId = `${id}-title`;
const variants = reduce ? fade : slide;
const canContinue = hasAnswer(answer) || (question?.type === "multiple" && (answer?.values.length ?? 0) > 0);
const answeredCount = questions.filter((item) => hasAnswer(answers[item.id])).length;
return (
<section
ref={rootRef}
aria-labelledby={titleId}
data-step={reviewing ? "review" : step}
onKeyDown={handleKeyDown}
className={cx(
"w-full max-w-md overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
"dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
className,
)}
{...props}
>
<header className="flex items-center gap-3 px-4 pt-3.5">
<h2 id={titleId} className="min-w-0 flex-1 truncate text-xs font-medium text-zinc-500">
{title ?? "A few questions"}
</h2>
<Progress total={total} step={step} answers={answers} questions={questions} reviewing={reviewing} />
<span aria-hidden="true" className="font-mono text-xs text-zinc-500 tabular-nums">
{reviewing ? `${answeredCount} of ${total}` : `${step + 1} of ${total}`}
</span>
{onDismiss ? (
<button
type="button"
aria-label="Dismiss questions"
onClick={onDismiss}
className={cx(
"-my-1 -mr-1.5 flex size-7 shrink-0 items-center justify-center rounded-md text-zinc-400 dark:text-zinc-500",
"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] hover:text-zinc-700 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-200",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid",
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
<path d="m4.5 4.5 7 7m0-7-7 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</button>
) : null}
</header>
<motion.div
initial={false}
animate={{ height }}
transition={reduce ? { duration: 0 } : { duration: 0.32, ease: quint }}
className="overflow-hidden"
>
<div ref={bodyRef} className="relative">
<AnimatePresence initial={false} mode="popLayout" custom={direction}>
<motion.div
key={stepKey}
data-step-key={stepKey}
custom={direction}
variants={variants}
initial="enter"
animate="center"
exit="exit"
transition={reduce ? { duration: 0.12 } : { duration: 0.3, ease: quint }}
className="px-4 pt-2 pb-4"
>
{question ? (
<QuestionStep
id={id}
question={question}
answer={answer}
pressed={pressed}
disabled={submitted}
onPick={pick}
onOther={setOther}
onEnterOther={() => {
if (hasAnswer(answers[question.id])) go(step + 1);
}}
/>
) : (
<Review questions={questions} answers={answers} submitted={submitted} onEdit={(index) => go(index)} />
)}
</motion.div>
</AnimatePresence>
</div>
</motion.div>
<footer className="flex min-h-12 items-center gap-1 border-t border-zinc-950/[0.07] px-2 py-2 dark:border-white/[0.08]">
{submitted ? (
<p
role="status"
data-sent=""
tabIndex={-1}
className={cx(
"outline-none",
"flex items-center gap-2 px-2 text-sm text-zinc-600 dark:text-zinc-400",
`transition-[opacity,translate] duration-300 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`,
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4 text-emerald-600 dark:text-emerald-400">
<circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth="1.5" />
<path d="m5.5 8.25 1.75 1.75 3.25-3.75" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
Answers sent
</p>
) : (
<>
<button type="button" onClick={() => go(step - 1)} disabled={step === 0} className={ghostButton}>
Back
</button>
<span className="flex-1" />
{question && !question.required ? (
<button type="button" onClick={skip} className={ghostButton}>
Skip
</button>
) : null}
{reviewing ? (
<button type="button" data-autofocus="" onClick={submit} className={primaryButton}>
{submitLabel}
</button>
) : (
<button type="button" onClick={() => go(step + 1)} disabled={!canContinue} className={primaryButton}>
{step === total - 1 ? "Review" : "Next"}
</button>
)}
</>
)}
</footer>
</section>
);
}
const buttonBase = cx(
"inline-flex h-8 items-center justify-center gap-2 rounded-lg px-3 text-sm font-medium whitespace-nowrap select-none",
"transition-[background-color,color,scale,opacity] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid",
"disabled:pointer-events-none disabled:opacity-40",
);
const ghostButton = cx(
buttonBase,
"text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
);
const primaryButton = cx(
buttonBase,
"bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800",
"dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200",
);
/** One short segment per question; segments fill left to right as the user moves forward. */
function Progress({
total,
step,
answers,
questions,
reviewing,
}: {
total: number;
step: number;
answers: QuestionnaireAnswers;
questions: Question[];
reviewing: boolean;
}) {
return (
<span
role="progressbar"
aria-label="Questions"
aria-valuemin={1}
aria-valuemax={total}
aria-valuenow={Math.min(step + 1, total)}
aria-valuetext={reviewing ? "Reviewing answers" : `Question ${step + 1} of ${total}`}
className="flex items-center gap-1"
>
{questions.map((question, index) => {
const filled = reviewing || index <= step;
const skipped = answers[question.id]?.skipped;
return (
<span key={question.id} className="relative h-1 w-3.5 overflow-hidden rounded-full bg-zinc-950/10 sm:w-4 dark:bg-white/15">
<span
className={cx(
"absolute inset-0 origin-left rounded-full",
skipped && index !== step ? "bg-zinc-950/30 dark:bg-white/35" : "bg-zinc-950 dark:bg-white",
`transition-[scale] duration-300 ${ease} motion-reduce:transition-none`,
filled ? "scale-x-100" : "scale-x-0",
)}
/>
</span>
);
})}
</span>
);
}
function QuestionStep({
id,
question,
answer,
pressed,
disabled,
onPick,
onOther,
onEnterOther,
}: {
id: string;
question: Question;
answer: QuestionAnswer | undefined;
pressed: string | null;
disabled: boolean;
onPick: (option: QuestionOption) => void;
onOther: (text: string) => void;
onEnterOther: () => void;
}) {
const multiple = question.type === "multiple";
const headingId = `${id}-${question.id}`;
const otherId = `${id}-${question.id}-other`;
const otherText = answer?.other ?? "";
const otherChosen = otherText.trim().length > 0;
const values = answer?.values ?? [];
// Roving focus: the checked row, else the first row, is the one Tab lands on.
const firstChecked = question.options.findIndex((option) => values.includes(option.value));
const tabIndexFor = (index: number) => (index === (firstChecked === -1 ? 0 : firstChecked) ? 0 : -1);
return (
<div>
<h3 id={headingId} className="text-sm leading-6 font-semibold text-pretty">
{question.title}
</h3>
{question.description ? <p className="mt-0.5 text-sm text-pretty text-zinc-600 dark:text-zinc-400">{question.description}</p> : null}
<div role={multiple ? "group" : "radiogroup"} aria-labelledby={headingId} className="mt-3 grid gap-1.5">
{question.options.map((option, index) => {
const checked = values.includes(option.value);
return (
<button
key={option.value}
type="button"
role={multiple ? "checkbox" : "radio"}
aria-checked={checked}
aria-keyshortcuts={index < 9 ? String(index + 1) : undefined}
data-option=""
data-pressed={pressed === option.value || undefined}
tabIndex={multiple ? 0 : tabIndexFor(index)}
disabled={disabled}
onClick={() => onPick(option)}
className={rowClass(checked)}
>
<Key index={index} checked={checked} multiple={multiple} />
<span className="grid min-w-0 flex-1 gap-0.5 py-px">
<span className="text-sm leading-5 font-medium">{option.label}</span>
{option.description ? <span className="text-xs leading-4 text-zinc-500">{option.description}</span> : null}
</span>
</button>
);
})}
{question.allowOther ? (
<label htmlFor={otherId} className={cx(rowClass(otherChosen), "cursor-text")}>
<Key index={question.options.length} checked={otherChosen} multiple={multiple} />
<span className="sr-only">Other</span>
<input
id={otherId}
data-other-input=""
type="text"
value={otherText}
disabled={disabled}
placeholder={question.otherPlaceholder ?? "Something else"}
onChange={(event) => onOther(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
onEnterOther();
}
}}
className="h-5 min-w-0 flex-1 bg-transparent py-px text-sm leading-5 font-medium text-zinc-950 placeholder:font-normal placeholder:text-zinc-500 focus:outline-none dark:text-white"
/>
</label>
) : null}
</div>
</div>
);
}
function rowClass(checked: boolean) {
return cx(
"group/row flex w-full items-start gap-3 rounded-lg border px-3 py-2.5 text-left select-none",
"transition-[background-color,border-color,scale] duration-150 ease-out motion-reduce:transition-none",
"motion-safe:active:scale-[0.99] motion-safe:data-[pressed]:scale-[0.985]",
"focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-sky-500 focus-visible:outline-solid",
"has-[input:focus-visible]:outline-2 has-[input:focus-visible]:-outline-offset-1 has-[input:focus-visible]:outline-sky-500 has-[input:focus-visible]:outline-solid",
"disabled:pointer-events-none",
checked
? "border-zinc-950/50 bg-zinc-950/[0.035] dark:border-white/45 dark:bg-white/[0.06]"
: "border-zinc-950/10 hover:border-zinc-950/20 hover:bg-zinc-950/[0.02] dark:border-white/10 dark:hover:border-white/20 dark:hover:bg-white/[0.03]",
);
}
/** The number to press. Circles for one answer, squares for many; filled once chosen. */
function Key({ index, checked, multiple }: { index: number; checked: boolean; multiple: boolean }) {
return (
<span
aria-hidden="true"
className={cx(
"relative mt-px flex size-5 shrink-0 items-center justify-center border font-mono text-[11px] leading-none tabular-nums",
multiple ? "rounded-[5px]" : "rounded-full",
`transition-[background-color,border-color,color] duration-200 ${ease} motion-reduce:transition-none`,
checked
? "border-zinc-950 bg-zinc-950 text-white dark:border-white dark:bg-white dark:text-black"
: "border-zinc-950/15 text-zinc-500 group-hover/row:border-zinc-950/30 group-hover/row:text-zinc-700 dark:border-white/20 dark:group-hover/row:border-white/35 dark:group-hover/row:text-zinc-300",
)}
>
{multiple && checked ? (
<svg viewBox="0 0 16 16" fill="none" className="size-3.5">
<path
d="m4 8.25 2.75 2.75L12 5.5"
pathLength={1}
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
className={`[stroke-dasharray:1] [stroke-dashoffset:0] transition-[stroke-dashoffset] duration-200 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}
/>
</svg>
) : index < 9 ? (
index + 1
) : null}
</span>
);
}
function Review({
questions,
answers,
submitted,
onEdit,
}: {
questions: Question[];
answers: QuestionnaireAnswers;
submitted: boolean;
onEdit: (index: number) => void;
}) {
return (
<div>
<h3 className="text-sm leading-6 font-semibold">{submitted ? "Your answers" : "Review your answers"}</h3>
<dl className="mt-2 grid divide-y divide-zinc-950/[0.07] dark:divide-white/[0.08]">
{questions.map((question, index) => {
const answer = answers[question.id];
const missing = !hasAnswer(answer);
return (
<div key={question.id} className="flex items-start gap-3 py-2.5 first:pt-1 last:pb-0">
<div className="grid min-w-0 flex-1 gap-0.5">
<dt className="text-xs text-zinc-500">{question.title}</dt>
<dd className={cx("text-sm", missing ? "text-zinc-500" : "text-zinc-950 dark:text-white")}>{formatAnswer(question, answer)}</dd>
</div>
{submitted ? null : (
<button
type="button"
onClick={() => onEdit(index)}
aria-label={`Edit: ${question.title}`}
className={cx(ghostButton, "-mr-1.5 h-7 px-2 text-xs")}
>
Edit
</button>
)}
</div>
);
})}
</dl>
</div>
);
}