@case-framework/survey-editor-ui
v0.19.1
Published
React Survey Editor UI and optional assistant integration for CASE surveys.
Downloads
1,603
Readme
@case-framework/survey-editor-ui
Authoring UI for CASE surveys, including the SurveyEditor. Participant-facing
rendering is provided by the package dependency @case-framework/survey-ui.
For repository development and custom element registration, see Custom survey elements.
Integrating SurveyEditor into a host application
SurveyEditor deliberately does not render application-level controls such as
Save or Back. The host owns persistence, routing, and its header; the editor
owns survey mutations and undo/redo history.
The main editor export includes the assistant launcher UI. Host applications
must provide versions of ai and @ai-sdk/react compatible with the peer
ranges in package.json. The assistant's Mastra peers remain optional because
they are only needed by server integrations.
Use controllerRef for host-triggered commands and onHostStateChange to keep
host controls in sync with the editor:
import {
SurveyEditor,
type SurveyEditorController,
type SurveyEditorHostState,
} from "@case-framework/survey-editor-ui";
import { useRef, useState } from "react";
const controllerRef = useRef<SurveyEditorController | null>(null);
const [editorStatus, setEditorStatus] = useState<SurveyEditorHostState | null>(null);
const save = async () => {
const state = controllerRef.current?.getSerializedState();
if (!state) return;
await saveSurvey(state);
};
return (
<>
<HostHeader
saveDisabled={!editorStatus?.dirty}
undoDisabled={!editorStatus?.canUndo}
redoDisabled={!editorStatus?.canRedo}
onSave={save}
onUndo={() => controllerRef.current?.undo()}
onRedo={() => controllerRef.current?.redo()}
/>
<SurveyEditor
initialEditorState={initialEditorState}
controllerRef={controllerRef}
onHostStateChange={setEditorStatus}
onEditorStateChange={persistEditorState}
/>
</>
);onHostStateChange is immediate and reports dirty, canUndo, canRedo,
readOnly, revision, and sessionId. onEditorStateChange is the
serializable state notification and remains appropriate for autosave or local
draft persistence; configure persistDebounceMs when needed.
The editor retains its own Cmd/Ctrl+Z and Cmd/Ctrl+Shift+Z undo/redo shortcuts. Register Cmd/Ctrl+S in the host if the host supplies Save.
Localization
Use language for the editor UI and localizations for message overrides keyed by
language and namespace. Date controls localize automatically from DayPicker and
browser locale data. Editor bounds follow the editor language; participant and
translation-mode previews follow their survey language, including form matrices.
No host date translations or locale map are required. Optional dateEntry catalog
messages and dateLocales customize the defaults and also reach previews.
See the shared localization setup for fallback behavior and reusable participant catalogs. A separate host-owned simulator only needs the same options when the host wants custom wording or calendar data there too.
Composable elements
The editor retains its existing workspace, rich text, localization, response data, drag-and-drop, and assistant UI. Registered elements can be added directly as standalone content items or combined in layouts and full-width sections. Inline follow-ups share the same body editor. All edits use the normal mutation/history path. See Composable architecture.
Response data
The editor owns a survey-wide Response data screen, reached from the footer action and from variable search results. It is a three-pane workspace: scope navigation, a searchable Variables or projected Codebook table, and a coding inspector. Scopes cover all, computed, excluded, and attention variables as well as single items. Name and option-code edits are staged, previewed with their export examples, and applied as one ordinary undoable commit; leaving the screen with staged edits is guarded. Matrix cell names stay read-only here and are edited through the owning prefix/row/column controls.
Navigation uses {view: "response-data"}, optionally with responseSlotId to
reveal a specific variable. Item and inline preview locations also accept
responseSlotId to reveal the corresponding controls in the item editor.
Automatic coding suggestions are optional. Wrap the editor in the exported
ResponseSettingsSuggestionProvider to supply them:
import { ResponseSettingsSuggestionProvider } from "@case-framework/survey-editor-ui";
<ResponseSettingsSuggestionProvider value={suggestCoding}>
<SurveyEditor {...props} />
</ResponseSettingsSuggestionProvider>;The function receives the selected response slots and resolves to
{naming, settings}. The Suggest coding action appears only when a provider
is available; suggestions never bypass the shared preview and validation path.
The assistant integration wires this hook when the host enables it.
SurveyEditor styling in a host project
Tailwind CSS v4 / shadcn host
Do not import the complete @case-framework/survey-ui/css or
@case-framework/survey-editor-ui/css assets in a standard shadcn application.
Those generated stylesheets contain their own Tailwind base layer and global
theme variables, which can collide with the host's Preflight, :root, .dark,
and semantic tokens.
Register both packages in the host's existing global stylesheet instead:
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@case-framework/survey-editor-ui/editor.css";
@source "../node_modules/@case-framework/survey-ui/dist";
@source "../node_modules/@case-framework/survey-editor-ui/dist";The paths are relative to the stylesheet containing @source; adjust them for
the host's directory layout. Both sources are necessary because the editor
contains participant previews implemented by @case-framework/survey-ui.
The editor.css import provides complete, theme-free editor component styling.
Import it once, after shadcn/tailwind.css in the host's global stylesheet.
This asset includes editor defaults, opening animations, preview insertion and
drop-target spacing, and panel overflow behavior. The translation worklist's
sticky headers, selection states, excerpts, responsive layout, and arrival
highlight use Tailwind utilities generated from the sources above. The asset contains
no Tailwind base layer, global theme, or utility bundle. Keep the @source
entries above so the host generates the utility classes used by the components.
The host must supply its shadcn color and radius theme tokens, its own --font-sans
and --font-mono, and the extended radius tokens --radius-2xl, --radius-3xl,
and --radius-4xl as calc(var(--radius) + 8px), calc(var(--radius) + 12px),
and calc(var(--radius) + 16px) in @theme inline.
The older editor-defaults.css and editor-animations.css exports remain
available for compatibility, but importing only those two leaves out preview
insertion and translation worklist rules. Replace both imports with editor.css;
do not import all three together.
Layout
By default the workspace is a rounded card with the footer below it. For an editor
mounted edge to edge, such as directly below a host header, pass layout="flush":
<SurveyEditor layout="flush" />The editor root then carries data-case-layout="flush": the workspace has no outer
radius, top border or shadow, so the host header's bottom border stays the only
separator, and the footer becomes a status bar inside the workspace frame, with
--case-footer-border on top and its own inline padding. Colors are described in
Colors.
The --survey-editor-workspace-radius, --survey-editor-workspace-border-top-width,
--survey-editor-footer-padding-inline and --survey-editor-footer-padding-bottom
variables are deprecated. They still apply without layout="flush" for this
release and will be removed in the next one.
Colors
The editor takes its colors from the host's shadcn tokens, so a host theme alone
styles it in light and dark mode. Shared --case-* roles (such as
--case-accent and --case-surface-panel) recolor the editor and the Survey
Assistant together, and per-area variables (such as
--case-left-panel-background) change one part of the layout. Item and category
colors can be forced to one color or remapped per swatch with
--case-item-color and --case-item-color-<name>.
See Theming for every variable, its default, and recipes.
Standalone/non-Tailwind host
The complete precompiled assets remain available:
import "@case-framework/survey-ui/css";
import "@case-framework/survey-editor-ui/css";They are application-level stylesheets, not isolated component styles. Import each only once. They currently include global theme and base rules, so review their cascade before combining them with another CSS framework or design system.
Sources
- Tailwind: detecting classes in source files
documents
@sourcefor external component libraries and explains why dependencies are not scanned automatically. - Tailwind: Preflight documents the
global base styles included by
@import "tailwindcss". - shadcn: theming recommends application-owned semantic CSS variables.
- shadcn: Tailwind v4 documents the
@theme inline,:root, and.darkarrangement used by shadcn hosts. - shadcn: monorepo demonstrates that the shared UI stylesheet and theme configuration belong to the consuming workspace rather than being independently repeated by every component package.
Standalone rich text editing
RichTextEditor and RichTextBlockEditor work without SurveyEditor or a survey
configuration provider. They automatically supply default English translations,
tooltips, and confirmation dialogs. Wrap one or more editors in the exported
RichTextEditorProvider to configure their UI language or translation overrides:
import {
RichTextBlockEditor,
RichTextEditorProvider,
type RichTextEditorProps,
} from "@case-framework/survey-editor-ui";
import { useState } from "react";
function NoticeEditor() {
const [value, setValue] = useState<RichTextEditorProps["value"]>();
return (
<div className="survey-editor">
<RichTextEditorProvider language="nl">
<RichTextBlockEditor
aria-label="Notice content"
value={value}
onChange={(change) => setValue(change.value)}
toolbarMode="docked"
dockedToolbarVisibility="always"
styleControls={[
{ kind: "weight", value: "strong" },
{ kind: "italic", value: "italic" },
{ kind: "underline", value: "underline" },
]}
contentPolicy={{
allowLinks: false,
allowTemplateVariables: false,
allowedBlockTypes: { image: false, separator: false, infoBox: false },
}}
/>
</RichTextEditorProvider>
</div>
);
}Use this in a client component in Next.js. Apply the host styling setup above; the provider does not import CSS or install an application toaster.
language selects bundled English/Dutch UI messages, with English fallback.
localizations merges overrides using the existing editor message keys (for
example defaultEditors.imagePopover). An optional translate(key, values)
callback takes precedence when the host owns translation. Toolbar, block-menu, and link-editor labels use the richTextEditor message namespace.
Within a survey, rich text automatically inherits the survey's translator,
including custom catalogs. A nested provider can override it for a specific editor.
Formatting, toolbar modes, read-only behavior (editable), templates, links,
and block restrictions remain per-editor props. Asset resolution, registration,
and deletion are optional callbacks; no survey store is required. Content remains
the same serialized Lexical JSON (change.value), so existing documents and
renderers remain compatible. Content policies configure editing behavior; hosts
must still validate persisted documents against their own accepted content rules.
Document heading levels
RichTextContentPolicy.allowedHeadingLevels configures the heading choices in the
block toolbar, slash menu, and # shortcuts. It defaults to [1, 2]; existing
disallowed levels normalize to the nearest permitted shallower level (or the minimum
permitted level). An empty list converts headings to paragraphs while retaining content
and formatting. This applies to pasted content, loaded JSON, and serialized content. For notices, use [1, 2, 3, 4, 5] with
headingLevelOffset={1} on both RichTextBlockEditor and RichTextContentView.
Document level 1 then renders as HTML h2, through level 5 as h6. Choices that
would exceed HTML h6 are omitted. The offset changes rendering, not saved JSON.
The standalone editor defaults to offset 0; survey fields use offset 1 to match
the survey player. Keep an editor's offset stable while editing; changing it
recreates the Lexical editor.
In editable mode, correcting a supplied value to satisfy the heading policy calls
onChange once with the normalized editor value, even before the user types.
Controlled hosts should accept that value so saving matches the visible document.
Ordinary synchronization of an already-valid value and read-only normalization do
not emit this callback.
Editable starter wording
Explicit toolbox and Add actions write visible starter titles and list labels into only the selected content language. Exact locale wording is preferred, then the base language, then English. Existing content, imports, replay, and assistant wording are preserved; clearing a field does not regenerate its starter.
Hosts can override the authoringDefaults message namespace through the editor's
localizations prop, independently of its interface language. The keys are
question, section, field, option, statement, row, column, start, and
end. Numbered templates use {number}; the editor allocates an unused visible
label within that list. For example:
localizations={{
fr: {
authoringDefaults: {
question: "Question à rédiger",
option: "Option {number}",
},
},
}}The headless createElementStarterContent helper from
@case-framework/survey-elements returns the initial owner-content bundle for a
built-in element. It accepts optional starter-wording overrides and preserves
supplied roles, including explicitly empty ones. Apply that bundle alongside the
config in one normal editor action; the helper itself does not mutate a survey.
