@case-framework/survey-ui
v0.19.0
Published
Participant-facing React survey player for CASE surveys.
Readme
@case-framework/survey-ui
Participant-facing React components for rendering and completing CASE surveys. This package intentionally excludes the Survey Editor and Survey Assistant.
Localization
Pass UI translations through localizations, keyed by language and message namespace.
Navigation, validation, and element controls use exact-locale, base-language, then
English fallback:
const localizations = {
fr: {
navigation: { submitButtonLabel: "Envoyer" },
elements: { requiredError: "Ce champ est obligatoire." },
},
};
<SurveyPlayer session={session} localizations={localizations} />;Date controls automatically follow the survey language: calendars use DayPicker's
translated locales, while field names use browser locale data.
No host translations, locale imports, or dateLocales map are required. Additional
calendar languages load individually on demand and are shared across controls. Failed
requests fall back to English and retry when a picker is reopened.
Unavailable library languages fall back to English calendar text; field names also
fall back to English when the browser lacks that language's locale data. Dates always
use the Gregorian calendar and ISO storage. Picker-specific actions use the bundled
English/Dutch/German wording with English fallback; hosts can optionally override it.
Empty segments use symbolic hints such as DD / MM / YYYY, never example dates.
Hosts can optionally customize date-entry wording in the same catalog's dateEntry
namespace, or override calendar data with dateLocales. Current-language overrides
win over automatic wording; unrelated English fallback messages do not replace it.
The independent dateLocale option controls regional date order, separators,
numerals, and week start. These behaviors also apply to editor bounds, translation
previews, and form matrices. Authored survey content is translated separately in
the survey definition. A separate host-owned simulator only needs localization
options when the host wants to customize the defaults there as well.
The package owns the participant messages used by its default registry. Hosts that
compose another registry can reuse the exported catalogs, including
defaultConsentElementPlayerLocalizations, defaultInputElementPlayerLocalizations,
and defaultDateEntryLocalizations, as defaults and message-key references.
Sessions and submission
Create a SurveySession from survey-core and pass it to the player:
<SurveyPlayer session={session} responseId="response-1" onSubmit={submit} />The default renderer registry covers the built-in elements. A custom registry
maps element types to participant components. Core registrations remain headless;
see Composable architecture.
onSubmit(response, session) receives a detached version-3 response with flat
active answers[slotId], item metadata, events, and recorded context. Hidden
answers remain retained in the session; disabled visible answers are included.
Use session.snapshot() for continuation, never a filtered submission. A new
session initializes prefills once; a resumed session restores its bound snapshot.
Hosts own authorization, trusted server validation, and persistence.
The player sets submittedAt and prevents concurrent submission. It validates
all active pages and focuses an earlier invalid input when needed. Custom controls
report local draft issues and use the same atomic session write contract.
Layouts
SurveyPlayer has two layouts. Whether the participant can answer comes from the
session, not the layout:
layout="paged"(default) is the participant flow: one page at a time, page validation that blocks Next, progress and submit.layout="single-page"shows every item on one scrolling page, with authored page breaks as numbered separators ("Page 2") and no navigation, progress or submit. With a writable session it stays interactive and shows each answered question's checks as it changes; unanswered questions are not flagged. With a read-only session fromopenResponseit is the submission view below.showHiddenadds the hidden items in place (see below).
A read-only session always uses the single-page layout, since it cannot navigate or submit.
Narrow screens
When the player is narrower than 32rem (a phone), item cards run edge to edge: no rounded corners or side borders. Text outside the cards (progress, page separators, navigation) is inset 16px to line up with the card content. The player measures its own width (a container query), so this also works inside a preview frame.
This is on by default and expects the host to render the player without side padding at that width, on a page background that differs from the cards so items stay apart:
<main className="bg-muted py-4 sm:px-4">
<SurveyPlayer session={session} onSubmit={submit} />
</main>To keep inset cards inside your own page margin, pass disableFullBleed:
<SurveyPlayer session={session} onSubmit={submit} disableFullBleed />Scrolling between pages
When the participant moves to another page, the paged player scrolls its nearest
viewport: the closest ancestor with overflow-y: auto | scroll, else the window.
Outer overflow: hidden shells, such as dialogs, are never scrolled. Choose the
behaviour with scrollOnPageChange:
"player"(default): align the player's top with the viewport's top."viewport": scroll the viewport to its very top, revealing host content (a header or app bar) above the player."none": leave scrolling to the host.
<SurveyPlayer session={session} onSubmit={submit} scrollOnPageChange="viewport" />If you render the player in your own scroll container, give that container
position: relative. Otherwise the player's visually hidden labels (absolutely
positioned) resolve against an ancestor outside it and can make the outer shell
scrollable.
Previewing a survey
useSurveyPreview gives an author or researcher a throwaway session for a survey, for
example from a version list. Render its session with SurveyPlayer. Prefills and
conditions are live, and the hook never stores or sends anything.
const preview = useSurveyPreview({ survey, locale: "nl" });
{
preview.session ? (
<SurveyPlayer
session={preview.session}
layout="single-page"
onSubmit={(response) => setResponse(response)}
/>
) : (
<p>{preview.error ?? "Loading…"}</p>
);
}
<Button onClick={preview.restart}>Restart</Button>;There is no preview component and no built-in notice, restart button or end screen.
The player is the same one participants use, so the host owns everything around it:
where the controls go, what to tell the author, and what a submission does. Typical
choices are to show the submitted response, offer it as a JSON download, call
restart(), or switch back to the player.
previewis{ status, error, session, locale, restart }.statusis"loading","ready"or"error"(the survey cannot run;errorsays why).sessionis set while"ready".restart()starts a fresh session and discards answers.layout="single-page"onSurveyPlayergives an overview with hidden items shown, marked and live (showHidden, on by default there).layout="paged"tries the participant flow; its last page callsonSubmit(response, session).- Submitting only calls
onSubmit, as in a participant app. The session is not locked or changed, so a host can unmount the player to show its own screen and mount it again with the samesessionto return: answers and the current page are kept, and only transient screen state (shown validation messages, unfinished text in a control) is not. Callrestart()instead for a clean start. - Changing
localekeeps the answers (conditions follow the new language). A newsurvey,admissionorcontextstarts a fresh session, likerestart(). - Previous-response prefills find no previous answer and stay unanswered.
admission: "draft"previews unfinished definitions whose broken references evaluate as missing; the default"strict"shows why a definition cannot run.contextsetscurrentDate,participantFlagsorcustomValuesto try conditions that depend on them.
Viewing a submitted response
SubmissionView is the drop-in viewer: give it the exact survey definition and the
stored response. It opens the response itself (with SurveySession.openResponse),
shows it read-only on one page and never changes it.
<SubmissionView
survey={survey} // the exact definition the response was given against
response={stored} // ResponseForReading; keep the object stable between renders
definitionId={versionId} // optional: refuse a response from another version
displayLocale={viewerLocale} // optional; defaults to the recorded locale
showHidden // optional: also show hidden item cards
/>- It notes, above the answers, when the participant's question and option order was
not recorded (a stable substitute order is shown) and how many stored answers could
not be shown in full. Passing
definitionIdshows "This response belongs to a different survey version" instead of rendering it against the wrong questions. - It reopens the response when
survey,responseordefinitionIdchange, not whendisplayLocaledoes. - For your own handling of diagnostics or ordering, open the response yourself and
render the session with
SurveyPlayer layout="single-page":
const opened = SurveySession.openResponse(survey, {
binding,
response: stored,
mode: "view",
});
<SurveyPlayer session={opened.session} layout="single-page" displayLocale={viewerLocale} />;- The view shows every visible item on one scrolling page. Authored page breaks become numbered separators ("Page 2"); there is no navigation, progress, validation or submit. It shows the submitted state, not a replay of earlier screens or answers.
displayLocaleis presentation only: it translates authored content, player messages, dates and numbers. Visibility and conditions keep the recorded locale, so a reviewer reading in another language sees what the participant saw.showHiddenadds the items that were hidden for this response, in place, with a dashed outline, a "Hidden · not shown to the participant" label and faded, inert content. It works on whole items only: everything under a hidden item is hidden and unanswered, and options, rows and follow-ups inside visible items keep their recorded state.- Answers render with normal contrast and no editing affordances: no placeholders, hover, resize handles or pointer cursor, and a neutral dashed focus outline. Unselected options stay visible. Items the survey itself disabled keep their disabled look. Missing answers stay empty.
- Recorded event visualization belongs to the host application.
SurveySession.openResponseexposesrecordedEventsin stored order, including unknown or malformed entries, without changing the stored response. The history describes recorded activity; it does not reconstruct earlier answers or prove that all activity was recorded. - When you open the response yourself, show
opened.ordering === "fallback"andopened.diagnosticsto reviewers, asSubmissionViewdoes: the order is then not the participant's, and some stored answers were unusable.
Custom renderers
ElementRendererProps carries readOnly and displayLocale. A custom renderer
should:
- use
displayLocale(notsession.locale) for content, numbers and dates; - when
readOnlyis set, show the answer without editing affordances, never callsession.write(a read-only session throws), and leave missing answers empty rather than showing placeholders; - keep
readOnlyseparate from authored disabled state (active.disabled(element.id)), which still renders as disabled.
The shared UI primitives style read-only controls already (Base UI
data-readonly, native :read-only). The exported ChoiceMatrixField,
FormMatrixField and FormMatrixCellControl take disabled for authored disabled
state and readOnly for a submitted answer; readOnly used to mean disabled.
Consent dialogs
The existing inline/dialog consent UI is retained. Keep one compatible
@base-ui/react instance in hosts that surround the player with dialogs so their
focus and dismissal stacks agree.
Styling in a Tailwind CSS v4 / shadcn host
Import the React API normally:
import { SurveyPlayer } from "@case-framework/survey-ui";Do not import @case-framework/survey-ui/css in a standard shadcn application.
The host already owns Tailwind, shadcn's semantic theme tokens, Preflight, and
the global :root/.dark theme. Importing another complete generated
stylesheet can duplicate those layers and overwrite host variables or base
element styles.
Instead, explicitly register the installed package as a Tailwind source in the host's existing global stylesheet:
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@source "../node_modules/@case-framework/survey-ui/dist";The path is relative to the stylesheet containing @source; adjust it for the
host's directory layout. Tailwind generates only the utilities it detects in
the package, using the host application's theme.
@case-framework/survey-ui/css is currently a complete precompiled stylesheet
for standalone/non-Tailwind integrations. It includes global theme and base
rules, so treat it as an application-level stylesheet, import it only once, and
do not combine it with an existing shadcn global stylesheet without first
reviewing the cascade.
Install @case-framework/survey-editor-ui only in authoring applications.
Why this integration
- Tailwind: detecting classes in source files
documents
@sourcespecifically for external UI libraries because dependencies undernode_modulesare ignored by automatic source detection. - Tailwind: Preflight documents that
@import "tailwindcss"includes global base styles by default. - shadcn: theming recommends that the
application own semantic CSS variables such as
--background,--primary, and--border. - shadcn: Tailwind v4 shows those
variables and
@theme inlinein the application's global stylesheet.
Reusable date entry
DateEntry is the shared control used by input elements, form matrices, and the editor's
fixed date bounds. It works without a survey context:
import { DateEntry } from "@case-framework/survey-ui";
<DateEntry
label="Appointment date"
locale="en-GB"
mode="year-month-day"
value={date} // ISO calendar string, e.g. "2026-09-20", or undefined
onChange={setDate}
onDraftIssueChange={setDateDraftIssue}
isDateDisabled={(value) => value < "2026-09-20"}
/>;The locale determines the numeric segment order through
Intl.DateTimeFormat().formatToParts() using the Gregorian calendar. Each segment
has an accessible name and visible placeholder. Completing a day/month (two digits) or year
(four digits) advances to the next segment; Tab/Shift+Tab work normally, and
Backspace in an empty segment returns to the previous one. Local numeral input is
normalized to ASCII for ISO storage. No ambiguous free-text dates are parsed.
Use mode="year-month" or mode="year" for partial dates. These modes omit unused
segments. Month/year fields offer a month picker; year-only fields use numeric entry.
Both picker modes localize automatically. For optional custom wording, use labels
or getDateEntryLabels(locale, localizations) with a host catalog. dateLocales and
calendarLocale provide optional calendar-data overrides. Standalone
FormMatrixField and FormMatrixCellControl expose the same options with
dateEntryLabels for wording. Symbolic hints show the expected segment widths. Segments share one
outline, with locale-specific separators and accessible
segment names. Deleting all segments clears the value. Set bordered={false} when
the surrounding surface supplies the border; compact adapts height for matrix cells. disabled, required, invalid,
and describedBy support host forms and accessibility.
Incomplete or impossible dates stay local and do not replace the last complete
value. Hosts must use onDraftIssueChange to block saving/submitting while a
draft has an issue, even if an older complete value exists. The callback reports
"incomplete", "invalidDate", or undefined (no issue), and clears on unmount.
Hosts own error messages, when to show them, and the invalid/describedBy props.
Complete typed dates are emitted even when outside bounds: hosts must validate
semantic constraints separately. isDateDisabled only restricts calendar choices.
Clearing emits undefined; external value changes (including undo) replace the
local draft. There are no timezone conversions in stored values.
Regional date formatting
SurveyPlayer accepts an optional dateLocale, which defaults to session.locale:
<SurveyPlayer session={session} dateLocale="de-DE" />This keeps survey content, date placeholders, calendar month/day names, and validation
messages in English while using German date order, separators, and the first day
of the week. Date numeral input also follows dateLocale. Responses remain ISO
calendar strings. The option applies to input elements and form matrices; standalone
DateEntry and FormMatrixField expose regional-formatting options too.
Hosts can supply a participant's regional preference explicitly; the player does
not silently override it from browser settings. Changing dateLocale preserves
existing answers and incomplete date drafts.
Host presentation and portals
SurveyPlayer and SubmissionView accept itemPresentation="cards" | "dividers".
Cards remain the default. This changes item shells only, independently of
paged/single-page flow, visibility, validation, and recorded response data.
The player and item shells expose data-item-presentation for stable styling.
Hosts using Tailwind must retain the documented package @source entry.
Public CSS inputs (inherit from the player or a host wrapper):
| Input | Default | Purpose |
| ----------------------------------- | ------------------ | ----------------------------------- |
| --case-player-item-gap | 1rem | Space between player sections/items |
| --case-player-item-padding-block | 1rem | Item body block padding |
| --case-player-item-padding-inline | 1rem | Header and item body inline padding |
| --case-player-divider-color | var(--border) | Divider stroke color |
| --case-player-divider-width | 1px | Divider stroke width |
| --case-player-card-radius | var(--radius-xl) | Card corner radius |
| --case-player-card-border | var(--border) | Card border color |
| --case-player-card-background | var(--card) | Card background |
| --case-player-title-size | 1.125rem | Item title font size |
| --case-player-title-weight | 500 | Item title font weight |
| --case-player-subtitle-style | italic | Item subtitle font style |
| --case-button-font-weight | 500 | Player button label weight |
| --case-button-outline-border | primary at 40% | Next/submit outline border |
| --case-focus-ring-width | 3px | Focus ring width on player controls |
| --case-focus-ring-color | ring at 50% | Focus ring colour |
| --case-focus-ring-offset | 0px | Gap between control and focus ring |
| --case-focus-ring-offset-color | transparent | Colour of that gap |
Stable styling slots include survey-player-progress (the page indicator and
progress bar), survey-player-alert (page-level validation/load feedback), and
button with data-variant and data-size. Hosts can style states on these
slots; utility class names and their surrounding DOM are implementation details.
Optional shared control inputs inherit into player fields and host-owned portals:
| Input | Default | Purpose |
| ------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| --case-control-height | 2rem | Default input, input-group, select and button height |
| --case-control-font-size | Existing component scale (14px; text inputs 16px below md) | Field, choice/matrix and default button text |
| --case-control-line-height | Existing component line height | Labels and select/choice text |
| --case-control-indicator-size | 1rem | Visible radio and checkbox size; expanded hit areas remain |
| --case-calendar-cell-size | 1.75rem | Calendar day-cell size, independently of field height |
| --case-field-max-width-xs | 8rem | Input width for fields with placement.maxWidth: "xs" |
| --case-field-max-width-sm | 16rem | Input width for fields with placement.maxWidth: "sm" |
| --case-field-max-width-md | 24rem | Input width for fields with placement.maxWidth: "md" |
| --case-field-max-width-lg | 36rem | Input width for fields with placement.maxWidth: "lg" |
Field inputs fill the row, or their column when fields share a row. An element's
placement.maxWidth ("xs", "sm", "md" or "lg") caps only its input; its label,
help and messages keep the full width. The --case-field-max-width-* inputs set what
each size means.
Set --case-control-line-height as a unitless multiplier, such as 1.5, so it
scales with each component's font size; a fixed length can squeeze larger text.
Explicit compact button sizes and calendar captions retain their compact scale. Textareas retain their multiline minimum height. Calendar cells need a separate size so seven columns still fit on narrow phones. Set these variables only in the intended player/portal scope to leave authoring controls unchanged.
portalContainer optionally directs selects, date popovers, consent dialogs and
alerts into a host-owned element within the correct theme scope. Place that
container outside clipping/scrolling content where appropriate. The host owns
its lifecycle, stacking and theme variables. Omit it for existing body portals.
The optional SurveyPresentationProvider also scopes standalone fields:
<SurveyPresentationProvider portalContainer={portalElement}>
<SurveyPlayer session={session} itemPresentation="dividers" />
</SurveyPresentationProvider>Nested providers inherit omitted options; portalContainer={null} deliberately
resets to the library's default destination. Do not share the participant portal
container with unrelated editor dialogs when their surfaces differ.
