Questionnaire
A form that asks one question at a time, with choice and text questions, optional Skip, script validation, Back and a progress bar.
pnpm dlx shadcn@latest add @haze/questionnaire---
import { CircleAlert } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Checkbox from "./checkbox.astro";
import Textarea from "./textarea.astro";
interface Option {
value: string;
label: string;
description?: string;
}
interface Question {
/** Used as the form field name. */
id: string;
title: string;
description?: string;
/** single: pick one (radios). multiple: pick any (checkboxes). text: free text. */
type: "single" | "multiple" | "text";
options?: Option[];
/** Questions are optional unless this is true. */
required?: boolean;
placeholder?: string;
}
interface Props {
/** Required. Ids of the questions, headings and messages derive from it. */
id: string;
questions?: Question[];
action?: string;
method?: "get" | "post" | "dialog";
/** Heading level of each question title. */
headingLevel?: 2 | 3 | 4 | 5 | 6;
/** First word of the counter, "Question 2 of 4". */
questionLabel?: string;
/** Middle word of the counter. */
ofLabel?: string;
/** Accessible name of the progress bar. */
progressLabel?: string;
/** Marker after the title of an optional question. */
optionalLabel?: string;
backLabel?: string;
nextLabel?: string;
skipLabel?: string;
submitLabel?: string;
/** Message shown when a required question is empty, by question type. */
errorLabels?: { single: string; multiple: string; text: string };
class?: string;
}
const {
id,
questions = [
{
id: "team-size",
title: "How big is your team?",
description: "We use this to suggest seats and permissions.",
type: "single",
required: true,
options: [
{ value: "solo", label: "Just me" },
{ value: "small", label: "2 to 10 people", description: "A small team that shares one project board." },
{ value: "large", label: "11 or more people" },
],
},
{
id: "tools",
title: "Which tools should we connect?",
description: "Pick any that your team uses today.",
type: "multiple",
required: true,
options: [
{ value: "calendar", label: "Calendar" },
{ value: "chat", label: "Team chat" },
{ value: "repo", label: "Code repository" },
{ value: "storage", label: "File storage" },
],
},
{
id: "goal",
title: "What should your first project achieve?",
description: "A sentence or two is enough.",
type: "text",
placeholder: "Move our weekly planning out of spreadsheets",
},
{
id: "summary-to",
title: "Where should we send your setup summary?",
description: "An email address or a team channel name.",
type: "text",
required: true,
placeholder: "ops@harborworks.example",
},
],
action = "#workspace-setup",
method = "post",
headingLevel = 3,
questionLabel = "Question",
ofLabel = "of",
progressLabel = "Progress",
optionalLabel = "optional",
backLabel = "Back",
nextLabel = "Next",
skipLabel = "Skip",
submitLabel = "Submit",
errorLabels = {
single: "Choose one option to continue.",
multiple: "Choose at least one option to continue.",
text: "Write an answer to continue.",
},
class: className,
} = Astro.props;
const Heading = `h${headingLevel}` as "h3";
---
<form
id={id}
action={action}
method={method}
data-haze-questionnaire
data-question-label={questionLabel}
data-of-label={ofLabel}
class={cn("grid min-w-0 gap-6", className)}
>
<div class="hidden gap-2 [[data-haze-questionnaire][data-enhanced]_&]:grid">
<p data-q-counter class="text-[0.8125rem]/5 font-medium text-muted-foreground tabular-nums">{questionLabel} 1 {ofLabel} {questions.length}</p>
<div
data-q-bar
role="progressbar"
aria-label={progressLabel}
aria-valuemin={1}
aria-valuemax={questions.length}
aria-valuenow={1}
aria-valuetext={`${questionLabel} 1 ${ofLabel} ${questions.length}`}
class="h-1.5 w-full overflow-hidden rounded-full bg-muted forced-colors:border forced-colors:border-solid"
>
<div data-q-fill class="h-full rounded-full bg-primary transition-[width] duration-300 ease-snappy forced-colors:border forced-colors:border-solid" style={`width: ${100 / questions.length}%`}></div>
</div>
</div>
{
questions.map((q, index) => {
const qid = `${id}-q${index}`;
const describedby = [q.description ? `${qid}-description` : "", `${qid}-error`].filter(Boolean).join(" ");
return (
<fieldset
data-q
data-type={q.type}
data-required={q.required ? "" : undefined}
data-error={errorLabels[q.type]}
aria-describedby={describedby}
class="grid min-w-0 gap-4 border-0 p-0"
>
<legend class="mb-1 grid gap-1 p-0">
<Heading
id={`${qid}-title`}
tabindex="-1"
class="rounded-sm text-[1.0625rem]/6 font-medium tracking-[-0.01em] text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
{q.title}
{!q.required && <span class="text-[0.8125rem] font-normal text-muted-foreground"> ({optionalLabel})</span>}
</Heading>
{q.description && <span id={`${qid}-description`} class="text-[0.8125rem]/5 font-normal text-muted-foreground">{q.description}</span>}
</legend>
{q.type === "single" && (
<div class="flex flex-col gap-3">
{(q.options ?? []).map((option, o) => {
const oid = `${qid}-o${o}`;
return (
<div class="flex items-start gap-3">
<span class="relative mt-0.75 inline-grid size-4.5 shrink-0 place-items-center">
<input
id={oid}
name={q.id}
type="radio"
value={option.value}
data-q-input
required={q.required && o === 0 ? true : undefined}
aria-describedby={option.description ? `${oid}-description` : undefined}
class="peer col-start-1 row-start-1 size-4.5 cursor-pointer appearance-none rounded-full border border-border-strong bg-field transition-[background-color,border-color,scale] duration-150 ease-snappy hover:border-foreground active:scale-90 active:duration-75 checked:border-primary checked:hover:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-invalid:border-destructive! forced-colors:appearance-auto"
/>
<span class="pointer-events-none col-start-1 row-start-1 size-2 scale-0 rounded-full bg-primary-foreground transition-[scale] duration-200 ease-spring peer-checked:scale-100 forced-colors:hidden" aria-hidden="true" />
</span>
<div class="grid gap-1">
<label for={oid} class="text-[0.8125rem]/6 font-medium text-foreground">{option.label}</label>
{option.description && <p id={`${oid}-description`} class="text-[0.8125rem]/5 text-muted-foreground">{option.description}</p>}
</div>
</div>
);
})}
</div>
)}
{q.type === "multiple" && (
<div class="flex flex-col gap-3">
{(q.options ?? []).map((option, o) => (
<Checkbox id={`${qid}-o${o}`} name={q.id} value={option.value} label={option.label} description={option.description} data-q-input />
))}
</div>
)}
{q.type === "text" && (
<Textarea id={`${qid}-input`} name={q.id} rows={3} placeholder={q.placeholder} required={q.required} aria-labelledby={`${qid}-title`} data-q-input />
)}
<p id={`${qid}-error`} data-q-error hidden class="flex items-start gap-1.5 text-[0.8125rem]/5 font-medium text-destructive">
<CircleAlert aria-hidden="true" class="mt-0.5 size-4 shrink-0" />
<span data-q-error-text></span>
</p>
</fieldset>
);
})
}
<div class="flex flex-wrap items-center justify-between gap-2">
<Button variant="ghost" data-q-back hidden>{backLabel}</Button>
<div class="ms-auto flex flex-wrap items-center gap-2">
<Button variant="secondary" data-q-skip hidden>{skipLabel}</Button>
<Button data-q-next hidden>{nextLabel}</Button>
<Button type="submit" data-q-submit>{submitLabel}</Button>
</div>
</div>
</form>
<script>
function enhance(form: HTMLFormElement) {
if (form.hasAttribute("data-enhanced")) return;
form.setAttribute("data-enhanced", "");
// Our own checks replace the browser's bubble, so the message sits next to the question.
form.noValidate = true;
const panels = Array.from(form.querySelectorAll<HTMLFieldSetElement>("fieldset[data-q]"));
const counter = form.querySelector<HTMLElement>("[data-q-counter]");
const bar = form.querySelector<HTMLElement>("[data-q-bar]");
const fill = form.querySelector<HTMLElement>("[data-q-fill]");
const back = form.querySelector<HTMLButtonElement>("[data-q-back]");
const skip = form.querySelector<HTMLButtonElement>("[data-q-skip]");
const next = form.querySelector<HTMLButtonElement>("[data-q-next]");
const submit = form.querySelector<HTMLButtonElement>("[data-q-submit]");
if (!panels.length || !back || !skip || !next || !submit) return;
const questionWord = form.getAttribute("data-question-label") ?? "";
const ofWord = form.getAttribute("data-of-label") ?? "";
let current = 0;
const inputs = (panel: HTMLElement) => Array.from(panel.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("[data-q-input]"));
const heading = (panel: HTMLElement) => panel.querySelector<HTMLElement>("legend [id]");
const isRequired = (panel: HTMLElement) => panel.hasAttribute("data-required");
const isValid = (panel: HTMLElement) => {
const fields = inputs(panel);
if (panel.getAttribute("data-type") === "text") {
const field = fields[0] as HTMLTextAreaElement;
return (!isRequired(panel) || field.value.trim() !== "") && field.checkValidity();
}
return !isRequired(panel) || fields.some((field) => (field as HTMLInputElement).checked);
};
const showError = (panel: HTMLElement, on: boolean) => {
const message = panel.querySelector<HTMLElement>("[data-q-error]");
const text = panel.querySelector<HTMLElement>("[data-q-error-text]");
if (!message || !text) return;
const copy = on ? (panel.getAttribute("data-error") ?? "") : "";
if (text.textContent !== copy) text.textContent = copy;
message.hidden = !on;
for (const field of inputs(panel)) {
if (on) field.setAttribute("aria-invalid", "true");
else field.removeAttribute("aria-invalid");
// Tie the message to the control only while it shows.
const tokens = (field.getAttribute("aria-describedby") ?? "").split(/\s+/).filter((token) => token && token !== message.id);
if (on) tokens.push(message.id);
if (tokens.length) field.setAttribute("aria-describedby", tokens.join(" "));
else field.removeAttribute("aria-describedby");
}
};
const render = () => {
const total = panels.length;
panels.forEach((panel, i) => { panel.hidden = i !== current; });
const text = questionWord + " " + (current + 1) + " " + ofWord + " " + total;
if (counter && counter.textContent !== text) counter.textContent = text;
if (bar) {
bar.setAttribute("aria-valuenow", String(current + 1));
bar.setAttribute("aria-valuetext", text);
}
if (fill) fill.style.width = ((current + 1) / total) * 100 + "%";
const last = current === total - 1;
back.hidden = current === 0;
skip.hidden = isRequired(panels[current]) || last;
next.hidden = last;
submit.hidden = !last;
};
const go = (index: number, focus = true) => {
current = Math.min(Math.max(index, 0), panels.length - 1);
render();
if (focus) heading(panels[current])?.focus();
};
const fail = (index: number) => {
go(index, false);
showError(panels[index], true);
inputs(panels[index])[0]?.focus();
};
next.addEventListener("click", () => {
const panel = panels[current];
if (!isValid(panel)) { fail(current); return; }
showError(panel, false);
go(current + 1);
});
back.addEventListener("click", () => go(current - 1));
skip.addEventListener("click", () => {
const panel = panels[current];
for (const field of inputs(panel)) {
if (field instanceof HTMLTextAreaElement) field.value = "";
else field.checked = false;
}
showError(panel, false);
go(current + 1);
});
// Clear a message as soon as the answer changes.
form.addEventListener("input", (event) => {
const panel = (event.target as HTMLElement).closest<HTMLElement>("fieldset[data-q]");
if (panel && isValid(panel)) showError(panel, false);
});
// Enter in a field moves on instead of submitting early; the last question submits as usual.
form.addEventListener("keydown", (event) => {
const target = event.target as HTMLElement;
if (event.key !== "Enter" || event.isComposing || !(target instanceof HTMLInputElement)) return;
if (current === panels.length - 1) return;
event.preventDefault();
next.click();
});
form.addEventListener("submit", (event) => {
for (let i = 0; i < panels.length; i++) {
if (!isValid(panels[i])) {
event.preventDefault();
fail(i);
return;
}
}
});
form.addEventListener("reset", () => queueMicrotask(() => { panels.forEach((panel) => showError(panel, false)); go(0, false); }));
render();
}
const init = () => document.querySelectorAll<HTMLFormElement>("[data-haze-questionnaire]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-questionnaire-listener")) {
document.documentElement.setAttribute("data-haze-questionnaire-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- An AI agent or setup flow asks a few clarifying questions and each deserves the reader's full attention
- An intake form mixes single choice, multiple choice and free text, and some questions can be skipped
- A short survey must still submit as one plain form, with native checks on required text and single choice, if scripts fail
When not to use
- Questions are unrelated fields of one record, such as an address. Use fieldset with form fields.
- The steps are a long flow with its own screens and a numbered header. Use stepper.
- The flow must stay inside a modal. Use dialog-stack.
Installation
Add the Haze registry to components.json once, then install Questionnaire with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/questionnairenpx shadcn@latest add @haze/questionnaireyarn dlx shadcn@latest add @haze/questionnairebunx --bun shadcn@latest add @haze/questionnaireFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Id of the form; question and message ids derive from it. |
| questions | { id: string; title: string; description?: string; type: "single" | "multiple" | "text"; options?: { value: string; label: string; description?: string }[]; required?: boolean; placeholder?: string }[] | four-question workspace intake | Questions in order. The question id is the form field name. Questions are optional unless required is true. |
| action | string | "#workspace-setup" | Where the form posts. |
| method | "get" | "post" | "dialog" | "post" | Form method. |
| headingLevel | 2 | 3 | 4 | 5 | 6 | 3 | Heading level of each question title. |
| questionLabel | string | "Question" | First word of the counter, "Question 2 of 4". |
| ofLabel | string | "of" | Middle word of the counter. |
| progressLabel | string | "Progress" | Accessible name of the progress bar. |
| optionalLabel | string | "optional" | Marker after the title of an optional question. |
| backLabel | string | "Back" | Back button text. |
| nextLabel | string | "Next" | Next button text. |
| skipLabel | string | "Skip" | Skip button text, shown on optional questions. |
| submitLabel | string | "Submit" | Submit button text. |
| errorLabels | { single: string; multiple: string; text: string } | English messages | Message shown when a required question is empty, by question type. |
| class | string | – | Extra classes on the form. |
Keyboard interactions
- TabShiftTab
- Move between the answers and the buttons.
- Arrow keys
- Change the selected option in a single-choice question.
- Space
- Toggle a checkbox option.
- Enter
- Go to the next question from a choice; press Submit on the last one.
Accessibility
- Every question is a fieldset with its title in the legend, so choices are announced with their question.
- A blocked Next shows the message under the question, adds it to each control's aria-describedby while it shows, marks the controls invalid and moves focus to the first one.
- Moving between questions puts focus on the new question's heading. The counter is plain text with a matching progress bar.
- Enter in a field moves to the next question instead of submitting early; in the text area it adds a line.
- Without script all questions show in one form with one Submit button and the browser's own validation: required text and required single-choice questions are enforced. HTML has no native "at least one" rule for checkboxes, so a required multiple-choice question is enforced only with script.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Questionnaire" with `npx shadcn@latest add @haze/questionnaire`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Questionnaire from "@/components/haze/ui/questionnaire.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/questionnaire.md
Customize with real content
Adapt the Haze questionnaire ui for our product. Replace the demo values of these props with our real content: id, questions, action, method, headingLevel, questionLabel, ofLabel, progressLabel, optionalLabel, backLabel, nextLabel, skipLabel, submitLabel, errorLabels, class. Keep the layout, the heading level rules and these accessibility details: Every question is a fieldset with its title in the legend, so choices are announced with their question. A blocked Next shows the message under the question, adds it to each control's aria-describedby while it shows, marks the controls invalid and moves focus to the first one. Moving between questions puts focus on the new question's heading. The counter is plain text with a matching progress bar. Enter in a field moves to the next question instead of submitting early; in the text area it adds a line. Without script all questions show in one form with one Submit button and the browser's own validation: required text and required single-choice questions are enforced. HTML has no native "at least one" rule for checkboxes, so a required multiple-choice question is enforced only with script. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using questionnaire, check it fits: use it when an ai agent or setup flow asks a few clarifying questions and each deserves the reader's full attention; an intake form mixes single choice, multiple choice and free text, and some questions can be skipped; a short survey must still submit as one plain form, with native checks on required text and single choice, if scripts fail. Avoid it when questions are unrelated fields of one record, such as an address. use fieldset with form fields.; the steps are a long flow with its own screens and a numbered header. use stepper.; the flow must stay inside a modal. use dialog-stack.. Alternatives: @haze/stepper, @haze/dialog-stack, @haze/fieldset, @haze/radio-group.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/checkbox
- @haze/textarea
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.