Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(forms): show or skip a section based on earlier answers (#9436)

Wolf Mermelstein1beef1904afe
diff --git a/.sqlx/query-8decbb0d1133a6b0b2cdbd4aa8db612edd5f80b51f15f3a6394611c0c35c828d.json b/.sqlx/query-126aa04e7a90d91ce9567ac64615d9072f4dbd23e7d31686892bb30ba7f6d76e.json
similarity index 75%
rename from .sqlx/query-8decbb0d1133a6b0b2cdbd4aa8db612edd5f80b51f15f3a6394611c0c35c828d.json
rename to .sqlx/query-126aa04e7a90d91ce9567ac64615d9072f4dbd23e7d31686892bb30ba7f6d76e.json
index ae089355d1..20e5776587 100644
--- a/.sqlx/query-8decbb0d1133a6b0b2cdbd4aa8db612edd5f80b51f15f3a6394611c0c35c828d.json
+++ b/.sqlx/query-126aa04e7a90d91ce9567ac64615d9072f4dbd23e7d31686892bb30ba7f6d76e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, title, description, kind, gate_rules, gate_message, booking_target\n FROM form_sections WHERE form_id = $1\n ORDER BY position, id\n ",
+ "query": "\n SELECT id, title, description, kind, gate_rules, gate_message, booking_target, show_when\n FROM form_sections WHERE form_id = $1\n ORDER BY position, id\n ",
"describe": {
"columns": [
{
@@ -37,6 +37,11 @@
"ordinal": 6,
"name": "booking_target",
"type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "show_when",
+ "type_info": "Jsonb"
}
],
"parameters": {
@@ -51,8 +56,9 @@
false,
true,
false,
+ true,
true
]
},
- "hash": "8decbb0d1133a6b0b2cdbd4aa8db612edd5f80b51f15f3a6394611c0c35c828d"
+ "hash": "126aa04e7a90d91ce9567ac64615d9072f4dbd23e7d31686892bb30ba7f6d76e"
}
diff --git a/.sqlx/query-3ca697c1a82ac94298fc885391afed4afceeef8ca6cd5e2bfc074daa32d310a1.json b/.sqlx/query-3ca697c1a82ac94298fc885391afed4afceeef8ca6cd5e2bfc074daa32d310a1.json
deleted file mode 100644
index d18196c2ea..0000000000
--- a/.sqlx/query-3ca697c1a82ac94298fc885391afed4afceeef8ca6cd5e2bfc074daa32d310a1.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO form_sections (id, form_id, position, title, description, kind, gate_rules, gate_message, booking_target)\n SELECT section.id, $1, section.position, section.title, section.description,\n section.kind, section.rules::jsonb, section.message, section.booking_target::jsonb\n FROM UNNEST($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[], $8::text[], $9::text[])\n AS section(id, position, title, description, kind, rules, message, booking_target)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "UuidArray",
- "TextArray",
- "TextArray",
- "TextArray",
- "TextArray",
- "TextArray",
- "TextArray",
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "3ca697c1a82ac94298fc885391afed4afceeef8ca6cd5e2bfc074daa32d310a1"
-}
diff --git a/.sqlx/query-a0756b2d856b4b05efa7ec711dd299e0d125bb78fba3ed7af639f61255ab4579.json b/.sqlx/query-a0756b2d856b4b05efa7ec711dd299e0d125bb78fba3ed7af639f61255ab4579.json
new file mode 100644
index 0000000000..a39e710dab
--- /dev/null
+++ b/.sqlx/query-a0756b2d856b4b05efa7ec711dd299e0d125bb78fba3ed7af639f61255ab4579.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO form_sections (id, form_id, position, title, description, kind, gate_rules, gate_message, booking_target, show_when)\n SELECT section.id, $1, section.position, section.title, section.description,\n section.kind, section.rules::jsonb, section.message, section.booking_target::jsonb,\n section.show_when::jsonb\n FROM UNNEST($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[], $8::text[], $9::text[], $10::text[])\n AS section(id, position, title, description, kind, rules, message, booking_target, show_when)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a0756b2d856b4b05efa7ec711dd299e0d125bb78fba3ed7af639f61255ab4579"
+}
diff --git a/apps/docs/AI/mcp/tools/create-form.mdx b/apps/docs/AI/mcp/tools/create-form.mdx
index 15c4c74a7c..a93f5b3f1d 100644
--- a/apps/docs/AI/mcp/tools/create-form.mdx
+++ b/apps/docs/AI/mcp/tools/create-form.mdx
@@ -7,7 +7,7 @@ description: >-
# CreateForm
-Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating.
+Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. A questions section may set showWhen (rules like a gate's, referencing only questions of earlier sections) to branch: when earlier answers fail them the section is skipped, its questions are not required and their answers are not saved. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating.
## Parameters
diff --git a/apps/docs/AI/mcp/tools/edit-form.mdx b/apps/docs/AI/mcp/tools/edit-form.mdx
index 0028268fb6..6b5658055f 100644
--- a/apps/docs/AI/mcp/tools/edit-form.mdx
+++ b/apps/docs/AI/mcp/tools/edit-form.mdx
@@ -6,7 +6,7 @@ description: >-
# EditForm
-Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
+Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates, set or clear a questions section's showWhen (setShowWhen; skipped sections' questions are not required or saved) and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates and showWhen rules after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
## Parameters
diff --git a/apps/web/src/features/block-database/queries/forms-usage.ts b/apps/web/src/features/block-database/queries/forms-usage.ts
index 61e5c3473d..7e1ce33d79 100644
--- a/apps/web/src/features/block-database/queries/forms-usage.ts
+++ b/apps/web/src/features/block-database/queries/forms-usage.ts
@@ -88,7 +88,11 @@ export function useFormsAskingColumns(
.filter((form) =>
form.sections.some(
(section) =>
- section.kind === 'gate' && rulesName(section.rules, columnId)
+ (section.kind === 'gate' &&
+ rulesName(section.rules, columnId)) ||
+ (section.kind === 'questions' &&
+ !!section.showWhen &&
+ rulesName(section.showWhen, columnId))
)
)
.map((form) => form.form.name),
diff --git a/apps/web/src/features/block-form/components/builder/section-card.tsx b/apps/web/src/features/block-form/components/builder/section-card.tsx
index 9d185eedcf..55a93199ca 100644
--- a/apps/web/src/features/block-form/components/builder/section-card.tsx
+++ b/apps/web/src/features/block-form/components/builder/section-card.tsx
@@ -2,6 +2,7 @@ import ArrowBendDownRight from '@icon/system/regular/arrow-bend-down-right.svg';
import ArrowDown from '@icon/system/regular/arrow-down.svg';
import ArrowUp from '@icon/system/regular/arrow-up.svg';
import DotsThree from '@icon/system/regular/dots-three.svg';
+import GitBranch from '@icon/system/regular/git-branch.svg';
import ShieldCheck from '@icon/system/regular/shield-check.svg';
import Trash from '@icon/system/regular/trash.svg';
import { Button, cn, Dropdown } from '@ui';
@@ -17,6 +18,8 @@ export function SectionMenu(props: {
onMoveUp: () => void;
onMoveDown: () => void;
onDelete: () => void;
+ /** Offered on a questions section that may get a condition and has none. */
+ onAddCondition?: () => void;
}) {
return (
<Dropdown>
@@ -35,6 +38,14 @@ export function SectionMenu(props: {
<ArrowDown class="size-4" />
<span class="flex-1">Move down</span>
</Dropdown.Item>
+ <Show when={props.onAddCondition}>
+ {(onAddCondition) => (
+ <Dropdown.Item onSelect={onAddCondition()}>
+ <GitBranch class="size-4" />
+ <span class="flex-1">Show only when…</span>
+ </Dropdown.Item>
+ )}
+ </Show>
<Dropdown.Separator class="my-1 h-px bg-edge-divider" />
<Dropdown.Item class="text-failure-ink" onSelect={props.onDelete}>
<Trash class="size-4" />
@@ -75,6 +86,8 @@ export function SectionCard(props: {
menu: JSX.Element;
/** The other editors who selected this section. */
editors: JSX.Element;
+ /** The condition the section is shown on, when it has or is getting one. */
+ condition: JSX.Element;
routing: JSX.Element;
children: JSX.Element;
empty: boolean;
@@ -132,6 +145,7 @@ export function SectionCard(props: {
{props.menu}
</div>
</header>
+ {props.condition}
<div
data-form-section-list={props.sectionId}
class="flex flex-col divide-y divide-edge-divider"
@@ -146,6 +160,61 @@ export function SectionCard(props: {
);
}
+/**
+ * The condition a questions section is shown on: its sentence, the editor
+ * while open, and the repair for rules naming questions no longer before it.
+ */
+export function SectionCondition(props: {
+ sentence: string | undefined;
+ editing: boolean;
+ editor: JSX.Element;
+ /** Rules testing questions no longer asked before the section. */
+ brokenRules: number;
+ onRepair: () => void;
+ onEdit: () => void;
+ onRemove: () => void;
+}) {
+ return (
+ <div class="flex flex-col gap-2 border-b border-edge-divider px-4 py-3">
+ <div class="flex min-h-7 items-center gap-2">
+ <GitBranch class="size-3.5 text-ink-muted" aria-hidden="true" />
+ <span class="flex-1 text-xs font-medium text-ink-muted">
+ Show this section only
+ </span>
+ <Show when={!props.editing}>
+ <Button variant="ghost" size="sm" onClick={props.onEdit}>
+ Edit
+ </Button>
+ <Button variant="ghost" size="sm" onClick={props.onRemove}>
+ Remove
+ </Button>
+ </Show>
+ </div>
+ <Show when={props.sentence}>
+ <p class="font-mono text-xs leading-relaxed text-ink wrap-anywhere">
+ {props.sentence}
+ </p>
+ </Show>
+ <Show when={props.brokenRules > 0}>
+ <div
+ role="alert"
+ class="flex flex-wrap items-center gap-2 rounded-lg border border-failure/40 bg-failure-bg px-3 py-2 text-xs text-failure-ink"
+ >
+ <span class="flex-1">
+ {props.brokenRules === 1
+ ? 'A rule checks a question that is no longer before this section. Responses are refused until it is fixed.'
+ : `${props.brokenRules} rules check questions that are no longer before this section. Responses are refused until they are fixed.`}
+ </span>
+ <Button variant="secondary" size="sm" onClick={props.onRepair}>
+ Remove broken rules
+ </Button>
+ </div>
+ </Show>
+ <Show when={props.editing}>{props.editor}</Show>
+ </div>
+ );
+}
+
/**
* A gate: rules over earlier answers, evaluated on submit. Respondents never
* see the rules, only the message when one fails.
diff --git a/apps/web/src/features/block-form/core/answers.test.ts b/apps/web/src/features/block-form/core/answers.test.ts
index 106cf5f621..a5f5fa1275 100644
--- a/apps/web/src/features/block-form/core/answers.test.ts
+++ b/apps/web/src/features/block-form/core/answers.test.ts
@@ -32,6 +32,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -70,6 +71,7 @@ const layout: FormLayout = {
],
},
gateMessage: 'The offsite is for employees.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -80,6 +82,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -187,9 +190,9 @@ describe('nextStep', () => {
});
it('goes back over gates to the previous questions section', () => {
- expect(previousSectionIndex(layout, 2)).toBe(0);
- expect(previousSectionIndex(layout, 0)).toBeUndefined();
- expect(questionSectionIndices(layout)).toEqual([0, 2]);
+ expect(previousSectionIndex(layout, 2, {})).toBe(0);
+ expect(previousSectionIndex(layout, 0, {})).toBeUndefined();
+ expect(questionSectionIndices(layout, {})).toEqual([0, 2]);
});
});
@@ -349,6 +352,7 @@ describe('a booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
// A respondent's detail never carries the target.
bookingTarget: null,
questions: [],
@@ -358,8 +362,240 @@ describe('a booking step', () => {
it('is not a screen before submitting: the last questions section submits', () => {
expect(nextStep(booked, 2, {})).toEqual({ kind: 'submit' });
- expect(questionSectionIndices(booked)).toEqual([0, 2]);
+ expect(questionSectionIndices(booked, {})).toEqual([0, 2]);
expect(endsWithBooking(booked)).toBe(true);
expect(endsWithBooking(layout)).toBe(false);
});
});
+
+describe('a section shown only when earlier answers pass its condition', () => {
+ const ROLE = 'column-role';
+ const LANGUAGE = 'column-language';
+ const TOOL = 'column-tool';
+ const NOTE = 'column-note';
+ const ENGINEER = 'option-engineer';
+ const DESIGNER = 'option-designer';
+
+ const branching: FormLayout = {
+ sections: [
+ {
+ id: 'about',
+ title: 'About you',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-role',
+ columnId: ROLE,
+ helpText: '',
+ required: true,
+ widget: 'choice',
+ },
+ ],
+ },
+ {
+ id: 'engineering',
+ title: 'Engineering',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: ROLE,
+ test: {
+ kind: 'options',
+ operator: 'isAnyOf',
+ options: [ENGINEER],
+ },
+ },
+ ],
+ },
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-language',
+ columnId: LANGUAGE,
+ helpText: '',
+ required: true,
+ widget: 'short',
+ },
+ ],
+ },
+ {
+ id: 'design',
+ title: 'Design',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: ROLE,
+ test: {
+ kind: 'options',
+ operator: 'isAnyOf',
+ options: [DESIGNER],
+ },
+ },
+ ],
+ },
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-tool',
+ columnId: TOOL,
+ helpText: '',
+ required: true,
+ widget: 'short',
+ },
+ ],
+ },
+ {
+ id: 'fit',
+ title: 'Fit',
+ description: '',
+ kind: 'gate',
+ gateRules: {
+ conjunction: 'or',
+ conditions: [
+ {
+ kind: 'condition',
+ column: LANGUAGE,
+ test: { kind: 'text', operator: 'is', value: 'Rust' },
+ },
+ {
+ kind: 'condition',
+ column: TOOL,
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ gateMessage: 'Not a fit yet.',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [],
+ },
+ {
+ id: 'wrap-up',
+ title: 'Anything else',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-note',
+ columnId: NOTE,
+ helpText: '',
+ required: false,
+ widget: 'paragraph',
+ },
+ ],
+ },
+ ],
+ };
+
+ it('leads an engineer through the engineering section and a designer through the design one', () => {
+ expect(
+ nextStep(branching, 0, {
+ 'q-role': { type: 'options', value: [{ id: ENGINEER }] },
+ })
+ ).toEqual({ kind: 'section', index: 1 });
+ expect(
+ nextStep(branching, 1, {
+ 'q-role': { type: 'options', value: [{ id: ENGINEER }] },
+ 'q-language': { type: 'text', value: 'Rust' },
+ })
+ ).toEqual({ kind: 'section', index: 4 });
+ expect(
+ nextStep(branching, 0, {
+ 'q-role': { type: 'options', value: [{ id: DESIGNER }] },
+ })
+ ).toEqual({ kind: 'section', index: 2 });
+ expect(
+ nextStep(branching, 2, {
+ 'q-role': { type: 'options', value: [{ id: DESIGNER }] },
+ 'q-tool': { type: 'text', value: 'Figma' },
+ })
+ ).toEqual({ kind: 'section', index: 4 });
+ });
+
+ it('skips every conditional section for someone who left the question unanswered', () => {
+ expect(nextStep(branching, 0, {})).toEqual({
+ kind: 'stop',
+ sectionId: 'fit',
+ message: 'Not a fit yet.',
+ });
+ });
+
+ it('counts and steps back over only the sections shown', () => {
+ const engineer = {
+ 'q-role': { type: 'options' as const, value: [{ id: ENGINEER }] },
+ };
+ const designer = {
+ 'q-role': { type: 'options' as const, value: [{ id: DESIGNER }] },
+ };
+ expect(questionSectionIndices(branching, engineer)).toEqual([0, 1, 4]);
+ expect(questionSectionIndices(branching, designer)).toEqual([0, 2, 4]);
+ expect(previousSectionIndex(branching, 4, engineer)).toBe(1);
+ expect(previousSectionIndex(branching, 4, designer)).toBe(2);
+ expect(previousSectionIndex(branching, 2, designer)).toBe(0);
+ });
+
+ it('lets a gate read no answer typed into a section that is now skipped', () => {
+ // Answered as an engineer, then went back and chose designer.
+ expect(
+ nextStep(branching, 2, {
+ 'q-role': { type: 'options', value: [{ id: DESIGNER }] },
+ 'q-language': { type: 'text', value: 'Rust' },
+ })
+ ).toEqual({ kind: 'stop', sectionId: 'fit', message: 'Not a fit yet.' });
+ });
+
+ it('sends nothing from a skipped section on a first submission, and clears it on an edit', () => {
+ const answers = {
+ 'q-role': { type: 'options' as const, value: [{ id: DESIGNER }] },
+ 'q-language': { type: 'text' as const, value: 'Rust' },
+ 'q-tool': { type: 'text' as const, value: 'Figma' },
+ };
+ expect(submissionAnswers(branching, answers, 'create')).toEqual([
+ {
+ question: 'q-role',
+ value: { type: 'options', value: [{ id: DESIGNER }] },
+ },
+ { question: 'q-tool', value: { type: 'text', value: 'Figma' } },
+ ]);
+ expect(submissionAnswers(branching, answers, 'edit')).toEqual([
+ {
+ question: 'q-role',
+ value: { type: 'options', value: [{ id: DESIGNER }] },
+ },
+ { question: 'q-language', value: { type: 'clear' } },
+ { question: 'q-tool', value: { type: 'text', value: 'Figma' } },
+ { question: 'q-note', value: { type: 'clear' } },
+ ]);
+ });
+
+ it('reports a condition on a question no longer before it as an update in progress', () => {
+ const stale: FormLayout = {
+ sections: [
+ { ...branching.sections[0], questions: [] },
+ ...branching.sections.slice(1),
+ ],
+ };
+ expect(nextStep(stale, 0, {})).toEqual({ kind: 'updating' });
+ });
+});
diff --git a/apps/web/src/features/block-form/core/answers.ts b/apps/web/src/features/block-form/core/answers.ts
index d2cb845d67..8b61fa2191 100644
--- a/apps/web/src/features/block-form/core/answers.ts
+++ b/apps/web/src/features/block-form/core/answers.ts
@@ -1,5 +1,5 @@
import { match } from 'ts-pattern';
-import { brokenGateColumns } from './form-layout';
+import { brokenRuleColumns } from './form-layout';
import type {
FormAnswers,
FormCellValue,
@@ -125,19 +125,47 @@ export function sectionProblems(
});
}
-/** Answers by the column each question writes, as gates read them. */
-export function answersByColumn(
+/**
+ * The questions sections `answers` skip. In order, a section with a
+ * condition is shown only when the answers of the shown sections before it
+ * pass it, as strictly as a gate. Answers typed into a section skipped since
+ * stay in memory, but nothing reads or sends them.
+ */
+function skippedSections(
+ layout: FormLayout,
+ answers: FormAnswers
+): Set<string> {
+ const skipped = new Set<string>();
+ const byColumn = new Map<string, FormCellValue>();
+ for (const section of layout.sections) {
+ if (section.showWhen && !gatePasses(section.showWhen, byColumn)) {
+ skipped.add(section.id);
+ continue;
+ }
+ for (const question of section.questions) {
+ const value = answers[question.id];
+ if (isAnswered(value)) byColumn.set(question.columnId, trimmed(value));
+ }
+ }
+ return skipped;
+}
+
+/** Answers of the shown sections by the column each question writes, as gates read them. */
+function answersByColumn(
layout: FormLayout,
answers: FormAnswers
): Map<string, FormCellValue> {
// Exactly what a submission would carry, so a local gate check agrees
// with the server's.
+ const skipped = skippedSections(layout, answers);
const byColumn = new Map<string, FormCellValue>();
- for (const section of layout.sections)
+ for (const section of layout.sections) {
+ if (skipped.has(section.id)) continue;
for (const question of section.questions) {
const value = answers[question.id];
if (isAnswered(value)) byColumn.set(question.columnId, trimmed(value));
}
+ }
return byColumn;
}
@@ -145,28 +173,31 @@ export function answersByColumn(
export type FormStep =
| { kind: 'section'; index: number }
| { kind: 'stop'; sectionId: string; message: string }
- /** A gate tests a question no longer before it: the form is mid-edit. */
+ /** A gate or condition tests a question no longer before it: the form is mid-edit. */
| { kind: 'updating' }
| { kind: 'submit' };
/**
- * The next questions section after `from`, evaluating every gate passed on
- * the way. A failing gate stops the respondent there.
+ * The next shown questions section after `from`, evaluating every gate
+ * passed on the way. A failing gate stops the respondent there.
*/
export function nextStep(
layout: FormLayout,
from: number,
answers: FormAnswers
): FormStep {
+ const skipped = skippedSections(layout, answers);
const byColumn = answersByColumn(layout, answers);
for (let index = from + 1; index < layout.sections.length; index++) {
const section = layout.sections[index];
+ if (brokenRuleColumns(layout, section.id).length > 0)
+ return { kind: 'updating' };
const step = match(section.kind)
.returnType<FormStep | undefined>()
- .with('questions', () => ({ kind: 'section', index }))
+ .with('questions', () =>
+ skipped.has(section.id) ? undefined : { kind: 'section', index }
+ )
.with('gate', () => {
- if (brokenGateColumns(layout, section.id).length > 0)
- return { kind: 'updating' };
if (section.gateRules && !gatePasses(section.gateRules, byColumn))
return {
kind: 'stop',
@@ -188,36 +219,42 @@ export function endsWithBooking(layout: FormLayout): boolean {
return layout.sections.some((section) => section.kind === 'booking');
}
-/** The questions section before `from`, if any. */
+/** The shown questions section before `from`, if any. */
export function previousSectionIndex(
layout: FormLayout,
- from: number
+ from: number,
+ answers: FormAnswers
): number | undefined {
- for (let index = from - 1; index >= 0; index--)
- if (layout.sections[index].kind === 'questions') return index;
- return undefined;
+ const shown = questionSectionIndices(layout, answers);
+ return shown.findLast((index) => index < from);
}
-/** The questions sections, in order, as indices of the layout. */
-export function questionSectionIndices(layout: FormLayout): number[] {
+/** The questions sections `answers` show, in order, as indices of the layout. */
+export function questionSectionIndices(
+ layout: FormLayout,
+ answers: FormAnswers
+): number[] {
+ const skipped = skippedSections(layout, answers);
return layout.sections.flatMap((section, index) =>
- section.kind === 'questions' ? [index] : []
+ section.kind === 'questions' && !skipped.has(section.id) ? [index] : []
);
}
/**
- * The answers to send. A first submission carries what was answered; an edit
- * carries every question, clearing the ones emptied since.
+ * The answers to send. A first submission carries what was answered in the
+ * shown sections; an edit carries every question, clearing the ones emptied
+ * or skipped since.
*/
export function submissionAnswers(
layout: FormLayout,
answers: FormAnswers,
mode: 'create' | 'edit'
): SubmittedAnswer[] {
+ const skipped = skippedSections(layout, answers);
return layout.sections.flatMap((section) =>
section.questions.flatMap((question): SubmittedAnswer[] => {
const value = answers[question.id];
- if (isAnswered(value))
+ if (!skipped.has(section.id) && isAnswered(value))
return [{ question: question.id, value: trimmed(value) }];
return mode === 'edit'
? [{ question: question.id, value: { type: 'clear' } }]
diff --git a/apps/web/src/features/block-form/core/drop-target.test.ts b/apps/web/src/features/block-form/core/drop-target.test.ts
index 0ed32e8d32..b6df5d475e 100644
--- a/apps/web/src/features/block-form/core/drop-target.test.ts
+++ b/apps/web/src/features/block-form/core/drop-target.test.ts
@@ -117,6 +117,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: ['q1', 'q2'].map((id) => ({
id,
@@ -133,6 +134,7 @@ const layout: FormLayout = {
kind: 'gate',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -143,6 +145,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
diff --git a/apps/web/src/features/block-form/core/form-layout.test.ts b/apps/web/src/features/block-form/core/form-layout.test.ts
index 35ac9dacb8..2aaff3c58a 100644
--- a/apps/web/src/features/block-form/core/form-layout.test.ts
+++ b/apps/web/src/features/block-form/core/form-layout.test.ts
@@ -3,15 +3,15 @@ import {
addQuestion,
addSection,
bookingStep,
- brokenGateColumns,
+ brokenRuleColumns,
columnsNamed,
- gateColumns,
hiddenColumns,
moveQuestion,
moveSection,
pruneBrokenRules,
removeQuestion,
removeSection,
+ ruleColumns,
sectionInsertIndex,
swapQuestionColumn,
updateQuestion,
@@ -41,6 +41,7 @@ function offsite(): FormLayout {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -79,6 +80,7 @@ function offsite(): FormLayout {
],
},
gateMessage: 'The offsite is for employees.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -89,6 +91,7 @@ function offsite(): FormLayout {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -134,6 +137,7 @@ describe('addQuestion', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -311,11 +315,11 @@ describe('broken gate rules', () => {
layout.sections[0].questions = layout.sections[0].questions.filter(
(question) => question.id !== TEAM_QUESTION
);
- expect(brokenGateColumns(layout, GATE)).toEqual([TEAM_COLUMN]);
+ expect(brokenRuleColumns(layout, GATE)).toEqual([TEAM_COLUMN]);
const repaired = pruneBrokenRules(layout, GATE)._unsafeUnwrap();
expect(repaired.prunedConditions).toBe(1);
expect(repaired.layout.sections[1].gateRules?.conditions).toEqual([]);
- expect(brokenGateColumns(offsite(), GATE)).toEqual([]);
+ expect(brokenRuleColumns(offsite(), GATE)).toEqual([]);
});
it('keeps edits open around a gate whose question went in the grid', () => {
@@ -473,6 +477,7 @@ describe('sections', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -529,6 +534,7 @@ describe('sections', () => {
const layout = updateSection(offsite(), GATE, {
gateRules: rules,
gateMessage: 'Tell us your name',
+ showWhen: null,
})._unsafeUnwrap();
expect(layout.sections[1].gateRules).toEqual(rules);
expect(layout.sections[1].gateMessage).toBe('Tell us your name');
@@ -561,8 +567,8 @@ describe('sections', () => {
describe('reads', () => {
it('lists the columns a gate may test', () => {
- expect(gateColumns(offsite(), GATE)).toEqual([NAME_COLUMN, TEAM_COLUMN]);
- expect(gateColumns(offsite(), ABOUT)).toEqual([]);
+ expect(ruleColumns(offsite(), GATE)).toEqual([NAME_COLUMN, TEAM_COLUMN]);
+ expect(ruleColumns(offsite(), ABOUT)).toEqual([]);
});
it('lists the columns rules name, nested groups included, once each', () => {
@@ -642,6 +648,7 @@ describe('booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
},
@@ -659,6 +666,7 @@ describe('booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
},
@@ -671,6 +679,7 @@ describe('booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
});
@@ -692,6 +701,7 @@ describe('booking step', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -717,6 +727,7 @@ describe('booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: REVIEW_CALL,
questions: [],
},
@@ -753,6 +764,7 @@ describe('booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: REVIEW_CALL,
questions: [],
},
@@ -804,6 +816,7 @@ describe('booking step', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -856,3 +869,116 @@ describe('booking step', () => {
expect(removed.prunedConditions).toBe(0);
});
});
+
+describe('a section shown on a condition', () => {
+ /** About you → gate → Details, shown only when Team is Contractor. */
+ function conditional(): FormLayout {
+ const layout = offsite();
+ layout.sections[2].showWhen = {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: TEAM_COLUMN,
+ test: { kind: 'options', operator: 'isAnyOf', options: [CONTRACTOR] },
+ },
+ ],
+ };
+ return layout;
+ }
+
+ it('may test the questions of earlier sections only', () => {
+ expect(ruleColumns(conditional(), DETAILS)).toEqual([
+ NAME_COLUMN,
+ TEAM_COLUMN,
+ ]);
+ expect(
+ updateSection(conditional(), ABOUT, {
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: DIET_COLUMN,
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ })._unsafeUnwrapErr()
+ ).toEqual({
+ kind: 'condition-before-question',
+ sectionId: ABOUT,
+ columnId: DIET_COLUMN,
+ });
+ });
+
+ it('refuses to move the section or its question so the question no longer comes first', () => {
+ expect(moveSection(conditional(), DETAILS, 0)._unsafeUnwrapErr()).toEqual({
+ kind: 'condition-before-question',
+ sectionId: DETAILS,
+ columnId: TEAM_COLUMN,
+ });
+ const withoutGate: FormLayout = {
+ sections: conditional().sections.filter((section) => section.id !== GATE),
+ };
+ expect(
+ moveQuestion(withoutGate, TEAM_QUESTION, {
+ sectionId: DETAILS,
+ index: 0,
+ })._unsafeUnwrapErr()
+ ).toEqual({
+ kind: 'condition-before-question',
+ sectionId: DETAILS,
+ columnId: TEAM_COLUMN,
+ });
+ });
+
+ it('goes with the last question it tests, so the section is shown to everyone', () => {
+ const { layout, prunedConditions } = removeQuestion(
+ conditional(),
+ TEAM_QUESTION
+ )._unsafeUnwrap();
+ expect(prunedConditions).toBe(2);
+ expect(layout.sections[1].gateRules).toEqual({
+ conjunction: 'and',
+ conditions: [],
+ });
+ expect(layout.sections[2].showWhen).toBeNull();
+ });
+
+ it('names its broken columns and drops just those when repaired', () => {
+ const layout = conditional();
+ layout.sections[2].showWhen = {
+ conjunction: 'or',
+ conditions: [
+ {
+ kind: 'condition',
+ column: TEAM_COLUMN,
+ test: { kind: 'options', operator: 'isAnyOf', options: [CONTRACTOR] },
+ },
+ {
+ kind: 'condition',
+ column: NAME_COLUMN,
+ test: { kind: 'text', operator: 'is', value: 'Ada' },
+ },
+ ],
+ };
+ // The Team question went in the grid; the condition stayed.
+ layout.sections[0].questions = layout.sections[0].questions.filter(
+ (question) => question.id !== TEAM_QUESTION
+ );
+ expect(brokenRuleColumns(layout, DETAILS)).toEqual([TEAM_COLUMN]);
+ const repaired = pruneBrokenRules(layout, DETAILS)._unsafeUnwrap();
+ expect(repaired.prunedConditions).toBe(1);
+ expect(repaired.layout.sections[2].showWhen).toEqual({
+ conjunction: 'or',
+ conditions: [
+ {
+ kind: 'condition',
+ column: NAME_COLUMN,
+ test: { kind: 'text', operator: 'is', value: 'Ada' },
+ },
+ ],
+ });
+ });
+});
diff --git a/apps/web/src/features/block-form/core/form-layout.ts b/apps/web/src/features/block-form/core/form-layout.ts
index 55ee566e3d..53835adb66 100644
--- a/apps/web/src/features/block-form/core/form-layout.ts
+++ b/apps/web/src/features/block-form/core/form-layout.ts
@@ -26,6 +26,11 @@ export type LayoutRefusal =
kind: 'gate-before-question';
gateSectionId: string;
columnId: string;
+ }
+ | {
+ kind: 'condition-before-question';
+ sectionId: string;
+ columnId: string;
};
export type QuestionPatch = Partial<
@@ -35,11 +40,16 @@ export type QuestionPatch = Partial<
export type SectionPatch = Partial<
Pick<
FormSection,
- 'title' | 'description' | 'gateRules' | 'gateMessage' | 'bookingTarget'
+ | 'title'
+ | 'description'
+ | 'gateRules'
+ | 'gateMessage'
+ | 'showWhen'
+ | 'bookingTarget'
>
>;
-/** A layout edit that also dropped gate conditions naming columns it took off the form. */
+/** A layout edit that also dropped rule conditions naming columns it took off the form. */
export type PrunedLayout = { layout: FormLayout; prunedConditions: number };
function clamp(index: number, length: number) {
@@ -92,10 +102,19 @@ function replaceSection(
};
}
+/** A section's rules: a gate's, or the condition a questions section is shown on. */
+function sectionRules(section: FormSection): GateRules | null {
+ return match(section.kind)
+ .with('gate', () => section.gateRules)
+ .with('questions', () => section.showWhen)
+ .with('booking', () => null)
+ .exhaustive();
+}
+
/**
* Everything wrong with a layout: each booking step not last (of two, the
- * first is never last), then each column a gate names that is not asked
- * before it.
+ * first is never last), then each column a gate or condition names that is
+ * not asked before it.
*/
function layoutProblems(layout: FormLayout): LayoutRefusal[] {
const problems: LayoutRefusal[] = layout.sections.flatMap(
@@ -105,15 +124,20 @@ function layoutProblems(layout: FormLayout): LayoutRefusal[] {
: []
);
for (const section of layout.sections) {
- if (section.kind !== 'gate' || !section.gateRules) continue;
- const allowed = new Set(gateColumns(layout, section.id));
- for (const columnId of columnsNamed(section.gateRules))
- if (!allowed.has(columnId))
- problems.push({
- kind: 'gate-before-question',
- gateSectionId: section.id,
- columnId,
- });
+ for (const columnId of brokenRuleColumns(layout, section.id))
+ problems.push(
+ section.kind === 'gate'
+ ? {
+ kind: 'gate-before-question',
+ gateSectionId: section.id,
+ columnId,
+ }
+ : {
+ kind: 'condition-before-question',
+ sectionId: section.id,
+ columnId,
+ }
+ );
}
return problems;
}
@@ -162,16 +186,40 @@ function pruneRules(
return { rules: { conjunction: rules.conjunction, conditions }, pruned };
}
-function pruneGates(
+/**
+ * The section with its rules pruned. A condition left empty goes, so the
+ * section is always shown; a gate keeps its empty rules.
+ */
+function withPrunedRules(
+ section: FormSection,
+ columns: ReadonlySet<string>
+): { section: FormSection; pruned: number } {
+ const current = sectionRules(section);
+ if (!current) return { section, pruned: 0 };
+ const { rules, pruned } = pruneRules(current, columns);
+ if (pruned === 0) return { section, pruned };
+ return match(section.kind)
+ .with('gate', () => ({ section: { ...section, gateRules: rules }, pruned }))
+ .with('questions', () => ({
+ section: {
+ ...section,
+ showWhen: rules.conditions.length > 0 ? rules : null,
+ },
+ pruned,
+ }))
+ .with('booking', () => ({ section, pruned: 0 }))
+ .exhaustive();
+}
+
+function pruneSectionRules(
layout: FormLayout,
columns: ReadonlySet<string>
): PrunedLayout {
let prunedConditions = 0;
- const sections = layout.sections.map((section) => {
- if (!section.gateRules) return section;
- const { rules, pruned } = pruneRules(section.gateRules, columns);
+ const sections = layout.sections.map((before) => {
+ const { section, pruned } = withPrunedRules(before, columns);
prunedConditions += pruned;
- return pruned > 0 ? { ...section, gateRules: rules } : section;
+ return section;
});
return { layout: { sections }, prunedConditions };
}
@@ -224,7 +272,7 @@ export function removeQuestion(
...section,
questions: section.questions.filter((item) => item.id !== questionId),
}));
- return ok(pruneGates(without, new Set([found.question.columnId])));
+ return ok(pruneSectionRules(without, new Set([found.question.columnId])));
}
export function updateQuestion(
@@ -259,7 +307,7 @@ export function swapQuestionColumn(
item.id === questionId ? { ...item, columnId } : item
),
}));
- return ok(pruneGates(swapped, new Set([found.question.columnId])));
+ return ok(pruneSectionRules(swapped, new Set([found.question.columnId])));
}
/**
@@ -317,7 +365,7 @@ export function removeSection(
const section = layout.sections.find((item) => item.id === sectionId);
if (!section) return err({ kind: 'unknown-section', sectionId });
return ok(
- pruneGates(
+ pruneSectionRules(
{ sections: layout.sections.filter((item) => item.id !== sectionId) },
new Set(section.questions.map((question) => question.columnId))
)
@@ -346,8 +394,8 @@ export function questionNumbers(layout: FormLayout): Map<string, number> {
return numbers;
}
-/** Columns a gate may test: questions of the questions sections before it. */
-export function gateColumns(layout: FormLayout, sectionId: string): string[] {
+/** Columns a gate or condition may test: questions of the questions sections before it. */
+export function ruleColumns(layout: FormLayout, sectionId: string): string[] {
const index = layout.sections.findIndex((item) => item.id === sectionId);
if (index < 0) return [];
return layout.sections
@@ -359,36 +407,33 @@ export function gateColumns(layout: FormLayout, sectionId: string): string[] {
}
/**
- * Columns a gate's rules test that no earlier question asks: the question
+ * Columns a section's rules test that no earlier question asks: the question
* went in the grid (its column deleted or retyped) and the rule stayed.
*/
-export function brokenGateColumns(
+export function brokenRuleColumns(
layout: FormLayout,
sectionId: string
): string[] {
const section = layout.sections.find((item) => item.id === sectionId);
- if (!section?.gateRules) return [];
- const asked = new Set(gateColumns(layout, sectionId));
- return columnsNamed(section.gateRules).filter((column) => !asked.has(column));
+ const rules = section && sectionRules(section);
+ if (!rules) return [];
+ const asked = new Set(ruleColumns(layout, sectionId));
+ return columnsNamed(rules).filter((column) => !asked.has(column));
}
-/** The gate without its broken rules (see `brokenGateColumns`). */
+/** The section without its broken rules (see `brokenRuleColumns`). */
export function pruneBrokenRules(
layout: FormLayout,
sectionId: string
): Result<PrunedLayout, LayoutRefusal> {
- const section = layout.sections.find((item) => item.id === sectionId);
- if (!section) return err({ kind: 'unknown-section', sectionId });
- if (!section.gateRules) return ok({ layout, prunedConditions: 0 });
- const { rules, pruned } = pruneRules(
- section.gateRules,
- new Set(brokenGateColumns(layout, sectionId))
+ const found = layout.sections.find((item) => item.id === sectionId);
+ if (!found) return err({ kind: 'unknown-section', sectionId });
+ const { section, pruned } = withPrunedRules(
+ found,
+ new Set(brokenRuleColumns(layout, sectionId))
);
return ok({
- layout: replaceSection(layout, sectionId, (item) => ({
- ...item,
- gateRules: rules,
- })),
+ layout: replaceSection(layout, sectionId, () => section),
prunedConditions: pruned,
});
}
diff --git a/apps/web/src/features/block-form/core/form-model.ts b/apps/web/src/features/block-form/core/form-model.ts
index 6397d081c4..0454389240 100644
--- a/apps/web/src/features/block-form/core/form-model.ts
+++ b/apps/web/src/features/block-form/core/form-model.ts
@@ -5,8 +5,9 @@
*
* The shapes follow the service's wire types, but core never imports them.
* Sections are an editor projection: the wire's questions, gate or booking
- * union is flattened into one shape (a questions section has no rules; a
- * gate has no questions; only a booking step has a target), converted both
+ * union is flattened into one shape (only a gate has gate rules; only a
+ * questions section has questions or a condition; only a booking step has a
+ * target), converted both
* ways in `queries/form-detail.ts`. A form has at most one booking step, and
* it comes last.
*/
@@ -183,6 +184,11 @@ export type FormSection = {
/** Only a gate has rules; they name columns of earlier sections' questions. */
gateRules: GateRules | null;
gateMessage: string;
+ /**
+ * Only a questions section has one: it is shown only when the answers of
+ * earlier shown sections pass it, and skipped otherwise. Null: always shown.
+ */
+ showWhen: GateRules | null;
/**
* Only a booking step has a target, and only editors read it: respondents
* get it from an accepted submission (`UnlockedBooking`).
diff --git a/apps/web/src/features/block-form/core/layout-messages.test.ts b/apps/web/src/features/block-form/core/layout-messages.test.ts
index 2091954f4c..34d6d721db 100644
--- a/apps/web/src/features/block-form/core/layout-messages.test.ts
+++ b/apps/web/src/features/block-form/core/layout-messages.test.ts
@@ -19,6 +19,7 @@ function section(
kind,
gateRules: kind === 'gate' ? { conjunction: 'and', conditions: [] } : null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
};
@@ -54,6 +55,56 @@ describe('routingLine', () => {
});
});
+describe('routingLine past a section shown on a condition', () => {
+ const conditional: FormSection = {
+ ...section('contractors', 'questions'),
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: 'column-team',
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ };
+
+ it('names where a respondent goes when the section is skipped', () => {
+ expect(
+ routingLine(
+ {
+ sections: [
+ section('about', 'questions'),
+ conditional,
+ section('details', 'questions'),
+ ],
+ },
+ 'about'
+ )
+ ).toBe('Continue to section 2, or skip to section 3');
+ expect(
+ routingLine(
+ { sections: [section('about', 'questions'), conditional] },
+ 'about'
+ )
+ ).toBe('Continue to section 2, or submit');
+ expect(
+ routingLine(
+ {
+ sections: [
+ section('about', 'questions'),
+ conditional,
+ section('fit', 'gate'),
+ section('details', 'questions'),
+ ],
+ },
+ 'about'
+ )
+ ).toBe('Continue to section 2, or skip ahead');
+ });
+});
+
describe('placementDescription', () => {
it('numbers the target among question sections, as the cards do', () => {
expect(
diff --git a/apps/web/src/features/block-form/core/layout-messages.ts b/apps/web/src/features/block-form/core/layout-messages.ts
index 0f8c71532d..9f8c7da1c9 100644
--- a/apps/web/src/features/block-form/core/layout-messages.ts
+++ b/apps/web/src/features/block-form/core/layout-messages.ts
@@ -1,6 +1,6 @@
import { match } from 'ts-pattern';
import type { LayoutRefusal } from './form-layout';
-import type { FormLayout } from './form-model';
+import type { FormLayout, FormSection } from './form-model';
/** Names the builder shows for sections and columns. */
export type LayoutNames = {
@@ -52,10 +52,30 @@ export function routingLine(layout: FormLayout, sectionId: string): string {
: `${check}, then submit`;
return booking ? 'Submit, then book a time' : 'Submit form';
}
- const target = `section ${sectionPosition(layout, later[nextAt].id)}`;
- return gates > 0
- ? `${check}, then continue to ${target}`
- : `Continue to ${target}`;
+ const next = later[nextAt];
+ const target = `section ${sectionPosition(layout, next.id)}`;
+ const line =
+ gates > 0
+ ? `${check}, then continue to ${target}`
+ : `Continue to ${target}`;
+ return next.showWhen
+ ? `${line}, or ${skipLine(layout, later.slice(nextAt + 1))}`
+ : line;
+}
+
+/** Where a respondent goes past a skipped section, when one step says it; else "skip ahead". */
+function skipLine(layout: FormLayout, later: readonly FormSection[]): string {
+ const nextAt = later.findIndex((item) => item.kind === 'questions');
+ const between = nextAt < 0 ? later : later.slice(0, nextAt);
+ if (between.some((item) => item.kind === 'gate')) return 'skip ahead';
+ if (nextAt < 0)
+ return between.some((item) => item.kind === 'booking')
+ ? 'submit and book a time'
+ : 'submit';
+ const next = later[nextAt];
+ return next.showWhen
+ ? 'skip ahead'
+ : `skip to section ${sectionPosition(layout, next.id)}`;
}
/** Why a layout edit was refused, in the builder's words. */
@@ -69,6 +89,11 @@ export function layoutRefusalMessage(
({ gateSectionId, columnId }) =>
`“${names.section(gateSectionId)}” checks “${names.column(columnId)}”, so that question has to come before it.`
)
+ .with(
+ { kind: 'condition-before-question' },
+ ({ sectionId, columnId }) =>
+ `“${names.section(sectionId)}” is shown depending on “${names.column(columnId)}”, so that question has to come before it.`
+ )
.with(
{ kind: 'gate-section' },
() => 'A gate holds rules, not questions. Drop it in a section.'
diff --git a/apps/web/src/features/block-form/core/tally.test.ts b/apps/web/src/features/block-form/core/tally.test.ts
index c760e8b5fe..fd77c72d50 100644
--- a/apps/web/src/features/block-form/core/tally.test.ts
+++ b/apps/web/src/features/block-form/core/tally.test.ts
@@ -30,6 +30,7 @@ const lunch: FormDetail = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
diff --git a/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts b/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
index e12d18c9c7..828652e983 100644
--- a/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder-concurrency.test.ts
@@ -21,6 +21,7 @@ const startingLayout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
diff --git a/apps/web/src/features/block-form/primitives/create-builder-drag.test.ts b/apps/web/src/features/block-form/primitives/create-builder-drag.test.ts
index 9c803cc102..fcfe9bf7b4 100644
--- a/apps/web/src/features/block-form/primitives/create-builder-drag.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder-drag.test.ts
@@ -80,6 +80,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [question('q1'), question('q2'), question('q3')],
},
@@ -90,6 +91,7 @@ const layout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -194,6 +196,7 @@ it('drags a question type from the palette, creating it at the marked slot only
],
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
},
],
@@ -388,6 +391,7 @@ it('drags a new section from the sidebar into the form and creates it only on a
questions: [],
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
},
{
@@ -398,6 +402,7 @@ it('drags a new section from the sidebar into the form and creates it only on a
questions: [],
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
},
],
@@ -503,6 +508,7 @@ it('shows and announces a new section dropped below the booking step where it la
questions: [],
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
});
const formLayout: FormLayout = {
diff --git a/apps/web/src/features/block-form/primitives/create-builder.test.ts b/apps/web/src/features/block-form/primitives/create-builder.test.ts
index ce7a396a29..09c97d4f38 100644
--- a/apps/web/src/features/block-form/primitives/create-builder.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder.test.ts
@@ -84,6 +84,7 @@ const startingLayout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -122,6 +123,7 @@ const startingLayout: FormLayout = {
],
},
gateMessage: 'Employees only.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -132,6 +134,7 @@ const startingLayout: FormLayout = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -459,7 +462,7 @@ describe('createBuilder', () => {
builder.removeQuestion('q-team');
expect(builder.selectedId()).toBe('q-name');
expect(builder.layout()?.sections[1].gateRules?.conditions).toEqual([]);
- expect(notices).toEqual(['✓ Removed 1 gate rule that checked it.']);
+ expect(notices).toEqual(['✓ Removed 1 rule that checked it.']);
expect(calls).toEqual([]);
expect(builder.hiddenColumns().map((column) => column.name)).toEqual([
'Team',
@@ -469,6 +472,85 @@ describe('createBuilder', () => {
});
});
+ it('shows a section only on a condition, writes it to every editor, and takes it off again', async () => {
+ const { writes } = fakeWrites();
+ await createRoot(async (dispose) => {
+ const { builder, shared } = setup({ writes });
+ const contractorsOnly = {
+ conjunction: 'and' as const,
+ conditions: [
+ {
+ kind: 'condition' as const,
+ column: TEAM_COLUMN,
+ test: {
+ kind: 'options' as const,
+ operator: 'isAnyOf' as const,
+ options: [CONTRACTOR],
+ },
+ },
+ ],
+ };
+ expect(
+ builder.updateSection('details', { showWhen: contractorsOnly })
+ ).toBe(true);
+ expect(builder.layout()?.sections[2].showWhen).toEqual(contractorsOnly);
+ expect(shared.theirs().sections[2].showWhen).toEqual(contractorsOnly);
+ builder.updateSection('details', { showWhen: null });
+ expect(builder.layout()?.sections[2].showWhen).toBeNull();
+ expect(shared.theirs().sections[2].showWhen).toBeNull();
+ dispose();
+ });
+ });
+
+ it('refuses a condition on a question not asked before the section', async () => {
+ const { writes } = fakeWrites();
+ await createRoot(async (dispose) => {
+ const { builder, notices } = setup({ writes });
+ expect(
+ builder.updateSection('about', {
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: TEAM_COLUMN,
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ })
+ ).toBe(false);
+ expect(builder.layout()?.sections[0].showWhen).toBeNull();
+ expect(notices).toEqual([
+ '✗ “About you” is shown depending on “Team”, so that question has to come before it.',
+ ]);
+ dispose();
+ });
+ });
+
+ it('removes a question with the gate rule and the condition that checked it, showing the section to everyone', async () => {
+ const { writes } = fakeWrites();
+ await createRoot(async (dispose) => {
+ const { builder, notices } = setup({ writes });
+ builder.updateSection('details', {
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: TEAM_COLUMN,
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ });
+ builder.removeQuestion('q-team');
+ expect(builder.layout()?.sections[2].showWhen).toBeNull();
+ expect(notices).toEqual(['✓ Removed 2 rules that checked it.']);
+ dispose();
+ });
+ });
+
it('takes the question and the gate rules naming its column off the published form before deleting the column', async () => {
const order: string[] = [];
const { writes } = fakeWrites({
@@ -804,6 +886,7 @@ describe('the booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
});
diff --git a/apps/web/src/features/block-form/primitives/create-builder.ts b/apps/web/src/features/block-form/primitives/create-builder.ts
index 428b580861..a901b39367 100644
--- a/apps/web/src/features/block-form/primitives/create-builder.ts
+++ b/apps/web/src/features/block-form/primitives/create-builder.ts
@@ -332,8 +332,8 @@ export function createBuilder(options: BuilderOptions) {
if (committed && pruned > 0)
options.notify.success(
pruned === 1
- ? 'Removed 1 gate rule that checked it.'
- : `Removed ${pruned} gate rules that checked it.`
+ ? 'Removed 1 rule that checked it.'
+ : `Removed ${pruned} rules that checked it.`
);
return committed;
}
@@ -474,6 +474,7 @@ export function createBuilder(options: BuilderOptions) {
gateRules:
kind === 'gate' ? { conjunction: 'and', conditions: [] } : null,
gateMessage: kind === 'gate' ? DEFAULT_GATE_MESSAGE : '',
+ showWhen: null,
bookingTarget: null,
questions: [],
};
@@ -1015,6 +1016,7 @@ export function createBuilder(options: BuilderOptions) {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: target,
questions: [],
};
@@ -1038,8 +1040,8 @@ export function createBuilder(options: BuilderOptions) {
return commit((current) => moveLayoutSection(current, sectionId, index));
},
- /** Drop the gate's rules that test questions no longer asked before it. */
- repairGate(sectionId: string) {
+ /** Drop the section's rules that test questions no longer asked before it. */
+ repairRules(sectionId: string) {
commitPruned((current) => pruneBrokenRules(current, sectionId));
},
diff --git a/apps/web/src/features/block-form/primitives/create-respond.test.ts b/apps/web/src/features/block-form/primitives/create-respond.test.ts
index eee630324a..750f8f97d9 100644
--- a/apps/web/src/features/block-form/primitives/create-respond.test.ts
+++ b/apps/web/src/features/block-form/primitives/create-respond.test.ts
@@ -39,6 +39,7 @@ function offsite(): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -77,6 +78,7 @@ function offsite(): FormDetail {
],
},
gateMessage: 'The offsite is for employees.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -87,6 +89,7 @@ function offsite(): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -150,6 +153,7 @@ describe('createRespond', () => {
description: '',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -178,6 +182,7 @@ describe('createRespond', () => {
],
},
gateMessage: 'This invitation is for Ada.',
+ showWhen: null,
bookingTarget: null,
},
],
@@ -613,6 +618,7 @@ describe('createRespond', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
});
@@ -816,6 +822,282 @@ describe('createRespond', () => {
});
});
+ describe('a section shown on a condition', () => {
+ function branching(): FormDetail {
+ return {
+ form: {
+ id: 'form-2',
+ name: 'Offsite RSVP',
+ description: '',
+ ownerId: 'macro|[email protected]',
+ databaseId: 'database-1',
+ tableId: 'table-1',
+ audience: 'members',
+ status: 'open',
+ closesAt: null,
+ tallyVisible: false,
+ responsesVisible: false,
+ anonymous: false,
+ confirmationMessage: 'See you there.',
+ branding: { logoFileId: null, coverFileId: null, accentColor: null },
+ submittedColumnId: null,
+ respondentColumnId: null,
+ },
+ layout: {
+ sections: [
+ {
+ id: 'about',
+ title: 'About you',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-team',
+ columnId: TEAM,
+ helpText: '',
+ required: true,
+ widget: 'choice',
+ },
+ ],
+ },
+ {
+ id: 'contractors',
+ title: 'Your agency',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: TEAM,
+ test: {
+ kind: 'options',
+ operator: 'isAnyOf',
+ options: [CONTRACTOR],
+ },
+ },
+ ],
+ },
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-agency',
+ columnId: 'column-agency',
+ helpText: '',
+ required: true,
+ widget: 'short',
+ },
+ ],
+ },
+ {
+ id: 'details',
+ title: 'Details',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [
+ {
+ id: 'q-diet',
+ columnId: 'column-diet',
+ helpText: '',
+ required: true,
+ widget: 'paragraph',
+ },
+ ],
+ },
+ ],
+ },
+ columns: [
+ {
+ id: TEAM,
+ name: 'Team',
+ kind: { type: 'select', multi: false },
+ options: [
+ { id: CONTRACTOR, label: 'Contractor', color: null },
+ { id: EMPLOYEE, label: 'Employee', color: null },
+ ],
+ },
+ {
+ id: 'column-agency',
+ name: 'Agency',
+ kind: { type: 'text' },
+ options: [],
+ },
+ {
+ id: 'column-diet',
+ name: 'Diet',
+ kind: { type: 'text' },
+ options: [],
+ },
+ ],
+ access: 'view',
+ tableGone: false,
+ };
+ }
+
+ it('shows the section only while an earlier answer asks for it, keeps what was typed there, and never requires or sends it once skipped', async () => {
+ const sent: SubmittedAnswer[][] = [];
+ await createRoot(async (dispose) => {
+ const respond = createRespond({
+ detail: branching,
+ mine: () => null,
+ signedIn: () => true,
+ submit: (answers) => {
+ sent.push(answers);
+ return okAsync<SubmitOutcome, never>({
+ kind: 'submitted',
+ responseId: 'response-1',
+ booking: null,
+ });
+ },
+ editMine: () => errAsync({ message: 'unexpected' }),
+ mineFailed: () => false,
+ reloadMine: async () => {},
+ refetch: async () => {},
+ now,
+ });
+ expect(respond.view()).toMatchObject({
+ kind: 'answering',
+ position: 1,
+ total: 2,
+ });
+ respond.setAnswer('q-team', {
+ type: 'options',
+ value: [{ id: CONTRACTOR }],
+ });
+ expect(respond.view()).toMatchObject({ position: 1, total: 3 });
+ expect(respond.next()).toBe(true);
+ expect(respond.view()).toMatchObject({
+ kind: 'answering',
+ section: { id: 'contractors' },
+ position: 2,
+ total: 3,
+ isLast: false,
+ });
+ respond.setAnswer('q-agency', { type: 'text', value: 'Acme' });
+ respond.back();
+ respond.setAnswer('q-team', {
+ type: 'options',
+ value: [{ id: EMPLOYEE }],
+ });
+ expect(respond.next()).toBe(true);
+ expect(respond.view()).toMatchObject({
+ kind: 'answering',
+ section: { id: 'details' },
+ position: 2,
+ total: 2,
+ isLast: true,
+ });
+ respond.back();
+ expect(respond.view()).toMatchObject({ section: { id: 'about' } });
+ expect(respond.answers()['q-agency']).toEqual({
+ type: 'text',
+ value: 'Acme',
+ });
+ respond.next();
+ respond.setAnswer('q-diet', { type: 'text', value: 'None' });
+ await respond.submit();
+ expect(sent).toEqual([
+ [
+ {
+ question: 'q-team',
+ value: { type: 'options', value: [{ id: EMPLOYEE }] },
+ },
+ { question: 'q-diet', value: { type: 'text', value: 'None' } },
+ ],
+ ]);
+ expect(respond.view()).toEqual({
+ kind: 'confirmation',
+ answers: {
+ 'q-team': { type: 'options', value: [{ id: EMPLOYEE }] },
+ 'q-diet': { type: 'text', value: 'None' },
+ },
+ fresh: true,
+ alreadyResponded: false,
+ canEdit: true,
+ submittedAt: '2026-10-01T12:00:00.000Z',
+ booking: null,
+ });
+ dispose();
+ });
+ });
+
+ it('clears the answers of a section an edit skips', async () => {
+ const edits: SubmittedAnswer[][] = [];
+ const mine: MyResponse = {
+ status: 'submitted',
+ booking: null,
+ submittedAt: '2026-09-30T10:00:00Z',
+ answers: [
+ {
+ question: 'q-team',
+ value: { type: 'options', value: [{ id: CONTRACTOR }] },
+ },
+ { question: 'q-agency', value: { type: 'text', value: 'Acme' } },
+ { question: 'q-diet', value: { type: 'text', value: 'None' } },
+ ],
+ };
+ await createRoot(async (dispose) => {
+ const respond = createRespond({
+ detail: branching,
+ mine: () => mine,
+ signedIn: () => true,
+ submit: () => errAsync({ message: 'unexpected' }),
+ editMine: (answers) => {
+ edits.push(answers);
+ return okAsync({
+ kind: 'submitted',
+ responseId: 'response-1',
+ booking: null,
+ });
+ },
+ mineFailed: () => false,
+ reloadMine: async () => {},
+ refetch: async () => {},
+ now,
+ });
+ respond.editResponse();
+ expect(respond.view()).toMatchObject({
+ kind: 'answering',
+ position: 1,
+ total: 3,
+ });
+ respond.setAnswer('q-team', {
+ type: 'options',
+ value: [{ id: EMPLOYEE }],
+ });
+ respond.next();
+ expect(respond.view()).toMatchObject({
+ section: { id: 'details' },
+ position: 2,
+ total: 2,
+ });
+ await respond.submit();
+ expect(edits).toEqual([
+ [
+ {
+ question: 'q-team',
+ value: { type: 'options', value: [{ id: EMPLOYEE }] },
+ },
+ { question: 'q-agency', value: { type: 'clear' } },
+ { question: 'q-diet', value: { type: 'text', value: 'None' } },
+ ],
+ ]);
+ dispose();
+ });
+ });
+ });
+
describe('a booking step', () => {
const INTRO_CALL = { profileId: 'profile-1', eventTypeId: 'intro-call' };
const UNLOCKED = {
@@ -836,6 +1118,7 @@ describe('createRespond', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -919,6 +1202,7 @@ describe('createRespond', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: target,
questions: [],
});
diff --git a/apps/web/src/features/block-form/primitives/create-respond.ts b/apps/web/src/features/block-form/primitives/create-respond.ts
index 5080676bb8..ec5f1bf1d5 100644
--- a/apps/web/src/features/block-form/primitives/create-respond.ts
+++ b/apps/web/src/features/block-form/primitives/create-respond.ts
@@ -40,7 +40,7 @@ export type RespondView =
kind: 'answering';
/** Absent for a form that can be submitted without questions. */
section: FormSection | undefined;
- /** 1-based among questions sections. */
+ /** 1-based among the questions sections the answers so far show. */
position: number;
total: number;
isFirst: boolean;
@@ -227,7 +227,7 @@ export function createRespond(options: RespondOptions) {
if (current?.kind === 'stopped')
return { kind: 'stopped', message: current.message };
const sectionIndex = currentIndex();
- const indices = questionSectionIndices(layout());
+ const indices = questionSectionIndices(layout(), answers());
const section =
sectionIndex === undefined ? undefined : layout().sections[sectionIndex];
if (sectionIndex === undefined) {
@@ -245,8 +245,9 @@ export function createRespond(options: RespondOptions) {
total: indices.length,
isFirst:
sectionIndex === undefined ||
- previousSectionIndex(layout(), sectionIndex) === undefined,
- // Structural: a gate that would stop someone still shows "Next".
+ previousSectionIndex(layout(), sectionIndex, answers()) === undefined,
+ // A gate that would stop someone still shows "Next"; a section the
+ // answers so far skip does not.
isLast: position === indices.length,
submitting: submitting(),
uploading: uploads() > 0,
@@ -312,7 +313,7 @@ export function createRespond(options: RespondOptions) {
function back() {
const index = currentIndex();
if (index === undefined) return;
- const previous = previousSectionIndex(layout(), index);
+ const previous = previousSectionIndex(layout(), index, answers());
if (previous === undefined) return;
setProblems({});
showSection(previous);
@@ -351,7 +352,7 @@ export function createRespond(options: RespondOptions) {
? { kind: 'booking', booking: outcome.booking, preview: false }
: {
kind: 'confirmation',
- answers: { ...answers() },
+ answers: answersOf(sent),
submittedAt: options.now().toISOString(),
booking: null,
}
@@ -419,7 +420,12 @@ export function createRespond(options: RespondOptions) {
setPhase(
booking
? { kind: 'booking', booking, preview: true }
- : { kind: 'preview-complete', answers: { ...answers() } }
+ : {
+ kind: 'preview-complete',
+ answers: answersOf(
+ submissionAnswers(layout(), answers(), 'create')
+ ),
+ }
);
return;
}
diff --git a/apps/web/src/features/block-form/queries/form-collaboration.test.ts b/apps/web/src/features/block-form/queries/form-collaboration.test.ts
index e51e5b7a79..dda8549b5d 100644
--- a/apps/web/src/features/block-form/queries/form-collaboration.test.ts
+++ b/apps/web/src/features/block-form/queries/form-collaboration.test.ts
@@ -793,6 +793,65 @@ describe('form collaboration session', () => {
malformed.dispose();
});
+ it('reads a section’s nested condition, and refuses a malformed one', async () => {
+ const FOLLOW_UP = '0199b000-0000-7000-8000-000000000006';
+ const followUp = {
+ kind: 'questions',
+ id: FOLLOW_UP,
+ title: 'Follow-up',
+ description: '',
+ showWhen: {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'group',
+ conjunction: 'or',
+ conditions: [
+ {
+ kind: 'condition',
+ column: NAME_COLUMN,
+ test: { kind: 'presence', operator: 'isNotEmpty' },
+ },
+ ],
+ },
+ ],
+ },
+ questions: [],
+ };
+ const valid = open(
+ new FakeSurface({ sections: [...contactForm.sections, followUp] }),
+ 'valid'
+ );
+ await ready(valid);
+ expect(valid.session.layout()).toEqual({
+ sections: [...contactForm.sections, followUp],
+ });
+ valid.dispose();
+
+ const malformed = open(
+ new FakeSurface({
+ sections: [
+ ...contactForm.sections,
+ {
+ ...followUp,
+ showWhen: {
+ conjunction: 'and',
+ conditions: [{ kind: 'group', conjunction: 'xor' }],
+ },
+ },
+ ],
+ }),
+ 'malformed'
+ );
+ expect(
+ await until(malformed.session.state, (state) => state.kind === 'error')
+ ).toEqual({
+ kind: 'error',
+ message: 'This form was edited by a newer version of Macro.',
+ });
+ malformed.dispose();
+ });
+
it('fails to open when the server cannot prepare the form, without connecting', async () => {
const surface = new FakeSurface(contactForm);
let initializations = 0;
diff --git a/apps/web/src/features/block-form/queries/form-collaboration.ts b/apps/web/src/features/block-form/queries/form-collaboration.ts
index f3ecb65c6b..896b9d1a8a 100644
--- a/apps/web/src/features/block-form/queries/form-collaboration.ts
+++ b/apps/web/src/features/block-form/queries/form-collaboration.ts
@@ -263,7 +263,7 @@ function isGateSchema(section: SectionSchema): section is GateSchema {
const gateSchema =
putFormLayoutBody.shape.sections.element.options.find(isGateSchema);
if (!gateSchema) throw new Error('The form layout schema has no gate.');
-/** A gate's rules; the generated schema leaves nested groups unchecked. */
+/** A gate's rules or a section's condition; the generated schema leaves nested groups unchecked. */
const gateRules = gateSchema.shape.rules;
function isFilterGroup(value: unknown): value is FilterGroup {
@@ -283,7 +283,11 @@ function decodeSections(value: unknown): FormSection[] | undefined {
for (const section of parsed.data.sections) {
const decoded = match(section)
.returnType<FormSection | undefined>()
- .with({ kind: 'questions' }, (questions) => questions)
+ .with({ kind: 'questions' }, (questions) => {
+ const { showWhen, ...always } = questions;
+ if (showWhen === undefined) return always;
+ return isFilterGroup(showWhen) ? { ...always, showWhen } : undefined;
+ })
.with({ kind: 'booking' }, (booking) => booking)
.with({ kind: 'gate' }, (gate) => {
const { rules } = gate;
diff --git a/apps/web/src/features/block-form/queries/form-detail.test.ts b/apps/web/src/features/block-form/queries/form-detail.test.ts
index 60b0b8eee6..d9ba32a820 100644
--- a/apps/web/src/features/block-form/queries/form-detail.test.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.test.ts
@@ -18,6 +18,7 @@ it('refuses to send a gate without rules rather than inventing an empty rule gro
kind: 'gate',
gateRules: null,
gateMessage: 'Not this time.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -101,6 +102,68 @@ it('reads the shared layout document as the builder edits it, and writes it back
expect(toLayoutDocument(layout)).toEqual(document);
});
+it('reads the condition a section is shown on and writes it back, leaving it out of a section always shown', () => {
+ const document = {
+ sections: [
+ {
+ kind: 'questions' as const,
+ id: 'about',
+ title: 'About you',
+ description: '',
+ questions: [
+ {
+ id: 'q-team',
+ column: 'column-team',
+ helpText: '',
+ required: true,
+ widget: 'choice' as const,
+ },
+ ],
+ },
+ {
+ kind: 'questions' as const,
+ id: 'contractors',
+ title: 'Your agency',
+ description: '',
+ showWhen: {
+ conjunction: 'and' as const,
+ conditions: [
+ {
+ kind: 'condition' as const,
+ column: 'column-team',
+ test: {
+ kind: 'options' as const,
+ operator: 'isAnyOf' as const,
+ options: ['option-contractor'],
+ },
+ },
+ ],
+ },
+ questions: [],
+ },
+ ],
+ };
+ const layout = toFormLayout(document);
+ expect(layout.sections.map((section) => section.showWhen)).toEqual([
+ null,
+ {
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: 'column-team',
+ test: {
+ kind: 'options',
+ operator: 'isAnyOf',
+ options: ['option-contractor'],
+ },
+ },
+ ],
+ },
+ ]);
+ expect(toLayoutDocument(layout)).toEqual(document);
+});
+
describe('the booking step', () => {
const form = {
id: 'form-1',
@@ -149,6 +212,7 @@ describe('the booking step', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: { profileId: 'profile-1', eventTypeId: 'intro-call' },
questions: [],
},
@@ -205,6 +269,7 @@ describe('the booking step', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
diff --git a/apps/web/src/features/block-form/queries/form-detail.ts b/apps/web/src/features/block-form/queries/form-detail.ts
index 9ea7d2f643..04e95bab36 100644
--- a/apps/web/src/features/block-form/queries/form-detail.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.ts
@@ -55,6 +55,7 @@ function toSection(section: FormSectionDetail): FormSection {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: questions.showWhen ?? null,
bookingTarget: null,
questions: questions.questions.map((question) => ({
id: question.id,
@@ -71,6 +72,7 @@ function toSection(section: FormSectionDetail): FormSection {
kind: 'gate',
gateRules: gate.rules,
gateMessage: gate.message,
+ showWhen: null,
bookingTarget: null,
questions: [],
}))
@@ -81,6 +83,7 @@ function toSection(section: FormSectionDetail): FormSection {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
// Editors only: a respondent's detail withholds where it books.
bookingTarget: booking.target ? toBookingTarget(booking.target) : null,
questions: [],
@@ -92,6 +95,7 @@ function toSection(section: FormSectionDetail): FormSection {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
}));
@@ -161,6 +165,7 @@ export function toFormLayout(layout: WireFormLayout): FormLayout {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: questions.showWhen ?? null,
bookingTarget: null,
questions: questions.questions.map((question) => ({
id: question.id,
@@ -177,6 +182,7 @@ export function toFormLayout(layout: WireFormLayout): FormLayout {
kind: 'gate',
gateRules: gate.rules,
gateMessage: gate.message,
+ showWhen: null,
bookingTarget: null,
questions: [],
}))
@@ -187,6 +193,7 @@ export function toFormLayout(layout: WireFormLayout): FormLayout {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: toBookingTarget(booking.target),
questions: [],
}))
@@ -197,6 +204,7 @@ export function toFormLayout(layout: WireFormLayout): FormLayout {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
}))
@@ -230,6 +238,7 @@ export function toLayoutDocument(layout: FormLayout): WireFormLayout {
id: section.id,
title: section.title,
description: section.description,
+ ...(section.showWhen ? { showWhen: section.showWhen } : {}),
questions: section.questions.map((question) => ({
id: question.id,
column: question.columnId,
diff --git a/apps/web/src/features/block-form/queries/form-publication.test.ts b/apps/web/src/features/block-form/queries/form-publication.test.ts
index f3a53c7ae8..90ffa4cc79 100644
--- a/apps/web/src/features/block-form/queries/form-publication.test.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.test.ts
@@ -60,6 +60,15 @@ describe('publicationMessage', () => {
},
})
).toBe('“Name” must come before the gate that checks it.');
+ expect(
+ publicationMessage({
+ detail,
+ publicationError: {
+ kind: 'layout',
+ problem: { kind: 'conditionNamesLaterColumn', column: 'column' },
+ },
+ })
+ ).toBe('“Name” must come before the section shown depending on it.');
expect(
publicationMessage({
detail,
diff --git a/apps/web/src/features/block-form/queries/form-publication.ts b/apps/web/src/features/block-form/queries/form-publication.ts
index 3275fa57dd..973ea6e25a 100644
--- a/apps/web/src/features/block-form/queries/form-publication.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.ts
@@ -70,6 +70,16 @@ export function publicationMessage(
{ kind: 'gateRule' },
() => 'Review your gate rules; one no longer matches its question.'
)
+ .with(
+ { kind: 'conditionNamesLaterColumn' },
+ ({ column }) =>
+ `${columnName(column)} must come before the section shown depending on it.`
+ )
+ .with(
+ { kind: 'conditionRule' },
+ () =>
+ 'Review your section conditions; one no longer matches its question.'
+ )
.with(
{ kind: 'textTooLong' },
({ max }) => `Shorten the text to ${max} characters or fewer.`
diff --git a/apps/web/src/features/block-form/tests/fake-collaboration.ts b/apps/web/src/features/block-form/tests/fake-collaboration.ts
index 96ace36eb0..e2a3551b64 100644
--- a/apps/web/src/features/block-form/tests/fake-collaboration.ts
+++ b/apps/web/src/features/block-form/tests/fake-collaboration.ts
@@ -77,8 +77,10 @@ export function createFakeCollaboration(
// the same objects so the layouts compare by value.
const knownRules: GateRules[] = [];
const remember = (layout: FormLayout) => {
- for (const section of layout.sections)
+ for (const section of layout.sections) {
if (section.gateRules) knownRules.push(section.gateRules);
+ if (section.showWhen) knownRules.push(section.showWhen);
+ }
};
const rulesOf = (value: unknown): GateRules | null => {
const json = canonical(value);
@@ -97,6 +99,7 @@ export function createFakeCollaboration(
description: text(section.description),
gateRules: kind === 'gate' ? rulesOf(section.rules) : null,
gateMessage: text(section.message),
+ showWhen: kind === 'questions' ? rulesOf(section.showWhen) : null,
bookingTarget:
kind === 'booking' ? bookingTargetOf(section.target) : null,
questions: (section.questions ?? []).map((question) => ({
diff --git a/apps/web/src/features/block-form/views/builder-view.test.tsx b/apps/web/src/features/block-form/views/builder-view.test.tsx
index 4af975dff1..f478ac7be4 100644
--- a/apps/web/src/features/block-form/views/builder-view.test.tsx
+++ b/apps/web/src/features/block-form/views/builder-view.test.tsx
@@ -116,6 +116,7 @@ function rsvp(): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -612,6 +613,87 @@ describe('BuilderView', () => {
expect(screen.getByRole('textbox', { name: 'Filter value' })).toBe(value);
});
+ it('shows a later section only on a condition built in the filter editor, summarises it, and removes it', async () => {
+ const detail = rsvp();
+ detail.layout.sections.push({
+ id: 'logistics',
+ title: 'Logistics',
+ description: '',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ showWhen: null,
+ bookingTarget: null,
+ questions: [],
+ });
+ const mock = createMockFormContext({ detail, tableColumns: columns });
+ const context = {
+ ...mock.context,
+ ui: {
+ ...mock.context.ui,
+ renderConditionEditor: FormConditionEditor,
+ },
+ };
+ render(() => (
+ <FormProvider value={context}>
+ <BuilderView
+ source={mock.source}
+ detail={detail}
+ collaboration={mock.shared.collaboration}
+ trackWrites={() => {}}
+ onOpenDatabase={() => {}}
+ />
+ </FormProvider>
+ ));
+ // The first section has nothing before it to depend on.
+ const aboutMenu = screen.getByRole('button', { name: 'About you actions' });
+ aboutMenu.focus();
+ fireEvent.keyDown(aboutMenu, { key: 'ArrowDown' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(
+ screen.queryByRole('menuitem', { name: /Show only when/ })
+ ).toBeNull();
+ fireEvent.keyDown(document.activeElement ?? document.body, {
+ key: 'Escape',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ const trigger = screen.getByRole('button', { name: 'Logistics actions' });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ await vi.advanceTimersByTimeAsync(0);
+ const item = screen.getByRole('menuitem', { name: /Show only when/ });
+ item.focus();
+ fireEvent.keyDown(item, { key: 'Enter' });
+ await vi.advanceTimersByTimeAsync(100);
+ const logistics = screen.getByRole('region', { name: 'Logistics' });
+ fireEvent.click(
+ within(logistics).getByRole('button', { name: /Add condition/ })
+ );
+ await vi.advanceTimersByTimeAsync(100);
+ fireEvent.input(
+ within(logistics).getByRole('textbox', { name: 'Filter value' }),
+ { target: { value: 'Ada' } }
+ );
+ await vi.advanceTimersByTimeAsync(400);
+ expect(mock.calls.layouts.at(-1)?.sections[1].showWhen).toEqual({
+ conjunction: 'and',
+ conditions: [
+ {
+ kind: 'condition',
+ column: 'name',
+ test: { kind: 'text', operator: 'contains', value: 'Ada' },
+ },
+ ],
+ });
+ fireEvent.click(within(logistics).getByRole('button', { name: 'Done' }));
+ expect(logistics.textContent).toContain('IF Name contains “Ada”');
+ fireEvent.click(within(logistics).getByRole('button', { name: 'Remove' }));
+ await vi.advanceTimersByTimeAsync(400);
+ expect(mock.calls.layouts.at(-1)?.sections[1].showWhen).toBeNull();
+ expect(logistics.textContent).not.toContain('Show this section only');
+ });
+
it('offers Add question inside an empty section, where a phone can reach it', () => {
const detail = rsvp();
detail.layout.sections.push({
@@ -621,6 +703,7 @@ describe('BuilderView', () => {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
});
@@ -928,6 +1011,7 @@ describe('BuilderView', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
});
@@ -1003,6 +1087,7 @@ describe('BuilderView', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
},
@@ -1013,6 +1098,7 @@ describe('BuilderView', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: REVIEW_CALL,
questions: [],
}
@@ -1070,6 +1156,7 @@ describe('BuilderView', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: INTRO_CALL,
questions: [],
});
diff --git a/apps/web/src/features/block-form/views/builder-view.tsx b/apps/web/src/features/block-form/views/builder-view.tsx
index 0e7391a9f2..17ff288852 100644
--- a/apps/web/src/features/block-form/views/builder-view.tsx
+++ b/apps/web/src/features/block-form/views/builder-view.tsx
@@ -64,6 +64,7 @@ import {
GateCard,
RoutingFooter,
SectionCard,
+ SectionCondition,
SectionMenu,
} from '../components/builder/section-card';
import {
@@ -83,10 +84,10 @@ import type { Box, MeasuredSection } from '../core/drop-target';
import { placementOf, stepPlacement } from '../core/drop-target';
import {
bookingStep,
- brokenGateColumns,
- gateColumns,
+ brokenRuleColumns,
type QuestionPlacement,
questionNumbers,
+ ruleColumns,
} from '../core/form-layout';
import type {
FormBookingTarget,
@@ -94,6 +95,7 @@ import type {
FormDetail,
FormLayout,
FormSection,
+ GateRules,
SectionKind,
} from '../core/form-model';
import { availabilityLine, formAvailability } from '../core/form-status';
@@ -283,6 +285,43 @@ function BuilderCanvas(
</Show>
);
const [editingRules, setEditingRules] = createSignal<string>();
+ /** The filter editor over the questions before a section, for its gate rules or condition. */
+ const rulesEditor = (
+ sectionId: string,
+ rules: () => GateRules | null,
+ onChange: (rules: GateRules | null) => void
+ ) => (
+ <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3">
+ {
+ // Rendered once per opening, its props read live: a save must not
+ // remount the editor and drop a condition still being filled.
+ untrack(() =>
+ context.ui.renderConditionEditor({
+ get columns() {
+ return ruleColumns(layout(), sectionId).flatMap(
+ (columnId): FormColumn[] => {
+ const found = builder.column(columnId);
+ return found ? [found] : [];
+ }
+ );
+ },
+ get rules() {
+ return rules();
+ },
+ onChange,
+ })
+ )
+ }
+ <Button
+ size="sm"
+ variant="ghost"
+ class="self-end"
+ onClick={() => setEditingRules(undefined)}
+ >
+ Done
+ </Button>
+ </div>
+ );
const [choosingBooking, setChoosingBooking] = createSignal(false);
let afterMenuClose: (() => void) | undefined;
const sectionAddTriggers = new Map<string, HTMLButtonElement>();
@@ -762,6 +801,14 @@ function BuilderCanvas(
onMoveDown={() =>
builder.moveSection(sectionId, index() + 1)
}
+ onAddCondition={
+ section()?.kind === 'questions' &&
+ !section()?.showWhen &&
+ editingRules() !== sectionId &&
+ ruleColumns(layout(), sectionId).length > 0
+ ? () => setEditingRules(sectionId)
+ : undefined
+ }
onDelete={() => {
const current = section();
if (current)
@@ -823,13 +870,13 @@ function BuilderCanvas(
dragging={drag.isDragging(sectionTarget)}
editingRules={editingRules() === sectionId}
brokenRules={
- brokenGateColumns(layout(), sectionId).length
+ brokenRuleColumns(layout(), sectionId).length
}
- onRepair={() => builder.repairGate(sectionId)}
+ onRepair={() => builder.repairRules(sectionId)}
handle={handle()}
menu={menu()}
noQuestionsBefore={
- gateColumns(layout(), sectionId).length === 0
+ ruleColumns(layout(), sectionId).length === 0
}
onEditRules={() => setEditingRules(sectionId)}
onTitle={(title) =>
@@ -840,49 +887,17 @@ function BuilderCanvas(
gateMessage,
})
}
- ruleEditor={
- <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3">
- {
- // Rendered once per opening, its props read
- // live: a save must not remount the editor
- // and drop a condition still being filled.
- untrack(() =>
- context.ui.renderConditionEditor({
- get columns() {
- return gateColumns(
- layout(),
- sectionId
- ).flatMap(
- (columnId): FormColumn[] => {
- const found =
- builder.column(columnId);
- return found ? [found] : [];
- }
- );
- },
- get rules() {
- return current().gateRules;
- },
- onChange: (gateRules) =>
- builder.updateSection(sectionId, {
- gateRules: gateRules ?? {
- conjunction: 'and',
- conditions: [],
- },
- }),
- })
- )
- }
- <Button
- size="sm"
- variant="ghost"
- class="self-end"
- onClick={() => setEditingRules(undefined)}
- >
- Done
- </Button>
- </div>
- }
+ ruleEditor={rulesEditor(
+ sectionId,
+ () => current().gateRules,
+ (gateRules) =>
+ builder.updateSection(sectionId, {
+ gateRules: gateRules ?? {
+ conjunction: 'and',
+ conditions: [],
+ },
+ })
+ )}
/>
</Match>
<Match
@@ -998,6 +1013,47 @@ function BuilderCanvas(
handle={handle()}
menu={menu()}
editors={editors(sectionId, null)}
+ condition={
+ <Show
+ when={
+ current().showWhen ||
+ editingRules() === sectionId
+ }
+ >
+ <SectionCondition
+ sentence={rulesSentence(
+ current().showWhen,
+ builder.columns()
+ )}
+ editing={editingRules() === sectionId}
+ brokenRules={
+ brokenRuleColumns(layout(), sectionId)
+ .length
+ }
+ onRepair={() =>
+ builder.repairRules(sectionId)
+ }
+ onEdit={() => setEditingRules(sectionId)}
+ onRemove={() =>
+ builder.updateSection(sectionId, {
+ showWhen: null,
+ })
+ }
+ editor={rulesEditor(
+ sectionId,
+ () => current().showWhen,
+ (rules) =>
+ builder.updateSection(sectionId, {
+ showWhen:
+ rules &&
+ rules.conditions.length > 0
+ ? rules
+ : null,
+ })
+ )}
+ />
+ </Show>
+ }
onTitle={(title) =>
builder.updateSection(sectionId, { title })
}
diff --git a/apps/web/src/features/block-form/views/form-card-view.test.tsx b/apps/web/src/features/block-form/views/form-card-view.test.tsx
index ab150484bd..6866ace8bc 100644
--- a/apps/web/src/features/block-form/views/form-card-view.test.tsx
+++ b/apps/web/src/features/block-form/views/form-card-view.test.tsx
@@ -44,6 +44,7 @@ function lunchPoll(access: FormDetail['access']): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
diff --git a/apps/web/src/features/block-form/views/form-page-view.test.tsx b/apps/web/src/features/block-form/views/form-page-view.test.tsx
index 6f4f0975f7..ed18994fd6 100644
--- a/apps/web/src/features/block-form/views/form-page-view.test.tsx
+++ b/apps/web/src/features/block-form/views/form-page-view.test.tsx
@@ -69,6 +69,7 @@ const detail: FormDetail = {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
diff --git a/apps/web/src/features/block-form/views/respond-view.test.tsx b/apps/web/src/features/block-form/views/respond-view.test.tsx
index 1317e447d2..76913d0923 100644
--- a/apps/web/src/features/block-form/views/respond-view.test.tsx
+++ b/apps/web/src/features/block-form/views/respond-view.test.tsx
@@ -53,6 +53,7 @@ function offsite(): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -91,6 +92,7 @@ function offsite(): FormDetail {
],
},
gateMessage: 'The offsite is for employees.',
+ showWhen: null,
bookingTarget: null,
questions: [],
},
@@ -101,6 +103,7 @@ function offsite(): FormDetail {
kind: 'questions',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: null,
questions: [
{
@@ -607,6 +610,7 @@ describe('RespondView', () => {
kind: 'booking',
gateRules: null,
gateMessage: '',
+ showWhen: null,
bookingTarget: target,
questions: [],
},
diff --git a/apps/web/src/features/database/components/database-view-filters.tsx b/apps/web/src/features/database/components/database-view-filters.tsx
index 9cfdc583bb..84e1830878 100644
--- a/apps/web/src/features/database/components/database-view-filters.tsx
+++ b/apps/web/src/features/database/components/database-view-filters.tsx
@@ -70,8 +70,8 @@ export function FilterPanel(props: {
root={draft()}
/>
</div>
- <div class="mt-3 flex items-center justify-between">
- <div class="flex items-center gap-1">
+ <div class="mt-3 flex flex-wrap items-center justify-between gap-y-1">
+ <div class="flex flex-wrap items-center gap-1">
<Button
variant="ghost"
size="sm"
diff --git a/apps/web/src/features/database/core/forms-usage.test.ts b/apps/web/src/features/database/core/forms-usage.test.ts
index d64de03760..9019a6772a 100644
--- a/apps/web/src/features/database/core/forms-usage.test.ts
+++ b/apps/web/src/features/database/core/forms-usage.test.ts
@@ -43,16 +43,16 @@ describe('columnDeleteNote', () => {
);
});
- it('warns that forms whose gate checks the column stop taking responses', () => {
+ it('warns that forms whose gate or section condition checks the column stop taking responses', () => {
expect(
columnDeleteNote({ kind: 'known', names: ['RSVP'], gated: ['RSVP'] })
).toBe(
- 'Asked by “RSVP”: the question leaves the form with it. “RSVP” checks it in a gate, so it stops taking responses until the gate is fixed.'
+ 'Asked by “RSVP”: the question leaves the form with it. “RSVP” checks it in a gate or section condition, so it stops taking responses until the rule is fixed.'
);
expect(
columnDeleteNote({ kind: 'known', names: [], gated: ['Lunch'] })
).toBe(
- '“Lunch” checks it in a gate, so it stops taking responses until the gate is fixed.'
+ '“Lunch” checks it in a gate or section condition, so it stops taking responses until the rule is fixed.'
);
});
});
diff --git a/apps/web/src/features/database/core/forms-usage.ts b/apps/web/src/features/database/core/forms-usage.ts
index a1714fc34b..63e28eecdb 100644
--- a/apps/web/src/features/database/core/forms-usage.ts
+++ b/apps/web/src/features/database/core/forms-usage.ts
@@ -11,7 +11,7 @@ export type FormsUsage =
kind: 'known';
/** Forms asking it as a question (tables: forms writing to it). */
names: readonly string[];
- /** Forms whose gate rules test it. */
+ /** Forms whose gate or section-condition rules test it. */
gated: readonly string[];
};
@@ -50,7 +50,7 @@ export function columnDeleteNote(usage: FormsUsage): string | undefined {
? `Asked by ${quoted(names)}: the question leaves the form with it.`
: undefined,
gated.length > 0
- ? `${quoted(gated)} ${gated.length === 1 ? 'checks' : 'check'} it in a gate, so ${gated.length === 1 ? 'it stops' : 'they stop'} taking responses until the gate is fixed.`
+ ? `${quoted(gated)} ${gated.length === 1 ? 'checks' : 'check'} it in a gate or section condition, so ${gated.length === 1 ? 'it stops' : 'they stop'} taking responses until the rule is fixed.`
: undefined,
].filter((line) => line !== undefined);
return lines.length > 0 ? lines.join(' ') : undefined;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
index 73198ed124..0f157ca57c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/poll-card.tsx
@@ -90,6 +90,7 @@ function pollDetail(
gateRules: null,
gateMessage: '',
bookingTarget: null,
+ showWhen: null,
questions: [
{
id: 'question',
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 781f2490e3..15a0bd92ba 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -2915,6 +2915,560 @@ export const CreateForm = z.object({
})
.strict()
),
+ showWhen: z
+ .union([
+ z
+ .object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z
+ .object({
+ question: z.union([
+ z.object({ key: z.string() }).strict(),
+ z
+ .object({ id: z.string().uuid() })
+ .strict(),
+ ]),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z
+ .object({
+ test: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal(
+ 'doesNotContain'
+ ),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal(
+ 'greaterThan'
+ ),
+ z.literal(
+ 'greaterThanOrEqual'
+ ),
+ z.literal('lessThan'),
+ z.literal(
+ 'lessThanOrEqual'
+ ),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal(
+ 'doesNotContain'
+ ),
+ z.literal('endsBefore'),
+ z.literal(
+ 'endsOnOrAfter'
+ ),
+ z.literal(
+ 'startsAfter'
+ ),
+ z.literal(
+ 'startsOnOrBefore'
+ ),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(
+ z.string().uuid()
+ ),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors =
+ schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(
+ x
+ )
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('value'),
+ })
+ .strict(),
+ z
+ .object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [
+ ...errors,
+ result.error,
+ ]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length -
+ errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(
+ z.union([
+ z
+ .object({ key: z.string() })
+ .strict(),
+ z
+ .object({
+ id: z.string().uuid(),
+ })
+ .strict(),
+ ])
+ ),
+ kind: z.literal('options'),
+ })
+ .strict(),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('condition'),
+ })
+ .strict(),
+ z
+ .object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(z.any()),
+ kind: z.literal('group'),
+ })
+ .strict(),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ })
+ ),
+ })
+ .strict(),
+ z.null(),
+ ])
+ .optional(),
kind: z.literal('questions'),
})
.strict(),
@@ -3619,6 +4173,391 @@ export const MutationResult = z.object({
.optional(),
})
),
+ showWhen: z
+ .union([
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.intersection(
+ z.object({
+ column: z.string().uuid(),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('greaterThan'),
+ z.literal('greaterThanOrEqual'),
+ z.literal('lessThan'),
+ z.literal('lessThanOrEqual'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('endsBefore'),
+ z.literal('endsOnOrAfter'),
+ z.literal('startsAfter'),
+ z.literal('startsOnOrBefore'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(z.string().uuid()),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('condition') })
+ ),
+ z.intersection(
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.any(),
+ }),
+ z.object({ kind: z.literal('group') })
+ ),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ })
+ ),
+ }),
+ z.null(),
+ ])
+ .optional(),
kind: z.literal('questions'),
}),
z.object({
@@ -4139,8 +5078,10 @@ export const MutationResult = z.object({
z.literal('ScreeningTooDeep'),
z.literal('TooManyConditions'),
z.literal('GateReferencesLaterQuestion'),
+ z.literal('ShowWhenReferencesLaterQuestion'),
z.literal('UnknownOption'),
z.literal('InvalidGateRule'),
+ z.literal('InvalidShowWhenRule'),
z.literal('ConcurrentFieldChange'),
z.literal('InvalidEdit'),
z.literal('Forbidden'),
@@ -5488,62 +6429,769 @@ export const EditForm = z.object({
z
.object({
sectionId: z.string().uuid(),
- target: z.object({
- profileId: z.string().uuid(),
- eventTypeId: z.string().uuid(),
- }),
- qualification: z.any().superRefine((x, ctx) => {
- const schemas = [z.literal('advisory'), z.literal('required')];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
- ((result) =>
- result.error ? [...errors, result.error] : errors)(
- schema.safeParse(x)
- ),
- []
- );
- if (schemas.length - errors.length !== 1) {
- ctx.addIssue({
- path: ctx.path,
- code: 'invalid_union',
- unionErrors: errors,
- message: 'Invalid input: Should pass single schema',
- });
- }
- }),
- kind: z.literal('setBookingTarget'),
- })
- .strict(),
- z
- .object({
- section: z.any().superRefine((x, ctx) => {
- const schemas = [
+ showWhen: z
+ .union([
z.object({
- id: z.string().uuid(),
- title: z.string(),
- description: z.string(),
- questions: z.array(
- z.object({
- id: z.string().uuid(),
- column: z.string().uuid(),
- helpText: z.string(),
- required: z.boolean(),
- widget: z
- .union([
- z.any().superRefine((x, ctx) => {
- const schemas = [
- z.literal('short'),
- z.literal('paragraph'),
- z.literal('datetime'),
- z.literal('date'),
- z.literal('url'),
- z.literal('file'),
- z.literal('choice'),
- z.literal('dropdown'),
- z.literal('checkboxes'),
- ];
- const errors = schemas.reduce<z.ZodError[]>(
- (errors, schema) =>
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.intersection(
+ z.object({
+ column: z.string().uuid(),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('greaterThan'),
+ z.literal('greaterThanOrEqual'),
+ z.literal('lessThan'),
+ z.literal('lessThanOrEqual'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string().datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('endsBefore'),
+ z.literal('endsOnOrAfter'),
+ z.literal('startsAfter'),
+ z.literal('startsOnOrBefore'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string().datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(z.string().uuid()),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('condition') })
+ ),
+ z.intersection(
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.any(),
+ }),
+ z.object({ kind: z.literal('group') })
+ ),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ })
+ ),
+ }),
+ z.null(),
+ ])
+ .optional(),
+ kind: z.literal('setShowWhen'),
+ })
+ .strict(),
+ z
+ .object({
+ sectionId: z.string().uuid(),
+ target: z.object({
+ profileId: z.string().uuid(),
+ eventTypeId: z.string().uuid(),
+ }),
+ qualification: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('advisory'), z.literal('required')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('setBookingTarget'),
+ })
+ .strict(),
+ z
+ .object({
+ section: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ id: z.string().uuid(),
+ title: z.string(),
+ description: z.string(),
+ questions: z.array(
+ z.object({
+ id: z.string().uuid(),
+ column: z.string().uuid(),
+ helpText: z.string(),
+ required: z.boolean(),
+ widget: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('short'),
+ z.literal('paragraph'),
+ z.literal('datetime'),
+ z.literal('date'),
+ z.literal('url'),
+ z.literal('file'),
+ z.literal('choice'),
+ z.literal('dropdown'),
+ z.literal('checkboxes'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ })
+ ),
+ showWhen: z
+ .union([
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.intersection(
+ z.object({
+ column: z.string().uuid(),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('greaterThan'),
+ z.literal('greaterThanOrEqual'),
+ z.literal('lessThan'),
+ z.literal('lessThanOrEqual'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('endsBefore'),
+ z.literal('endsOnOrAfter'),
+ z.literal('startsAfter'),
+ z.literal('startsOnOrBefore'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(z.string().uuid()),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('condition') })
+ ),
+ z.intersection(
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.any(),
+ }),
+ z.object({ kind: z.literal('group') })
+ ),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
((result) =>
result.error
? [...errors, result.error]
@@ -5559,12 +7207,12 @@ export const EditForm = z.object({
'Invalid input: Should pass single schema',
});
}
- }),
- z.null(),
- ])
- .optional(),
- })
- ),
+ })
+ ),
+ }),
+ z.null(),
+ ])
+ .optional(),
kind: z.literal('questions'),
}),
z.object({
@@ -13938,6 +15586,391 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
.optional(),
})
),
+ showWhen: z
+ .union([
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.intersection(
+ z.object({
+ column: z.string().uuid(),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('greaterThan'),
+ z.literal('greaterThanOrEqual'),
+ z.literal('lessThan'),
+ z.literal('lessThanOrEqual'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('endsBefore'),
+ z.literal('endsOnOrAfter'),
+ z.literal('startsAfter'),
+ z.literal('startsOnOrBefore'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(z.string().uuid()),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('condition') })
+ ),
+ z.intersection(
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.any(),
+ }),
+ z.object({ kind: z.literal('group') })
+ ),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ })
+ ),
+ }),
+ z.null(),
+ ])
+ .optional(),
kind: z.literal('questions'),
}),
z.object({
@@ -14633,15 +16666,399 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
.union([
z.any().superRefine((x, ctx) => {
const schemas = [
- z.literal('short'),
- z.literal('paragraph'),
- z.literal('datetime'),
- z.literal('date'),
- z.literal('url'),
- z.literal('file'),
- z.literal('choice'),
- z.literal('dropdown'),
- z.literal('checkboxes'),
+ z.literal('short'),
+ z.literal('paragraph'),
+ z.literal('datetime'),
+ z.literal('date'),
+ z.literal('url'),
+ z.literal('file'),
+ z.literal('choice'),
+ z.literal('dropdown'),
+ z.literal('checkboxes'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ })
+ ),
+ showWhen: z
+ .union([
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('and'), z.literal('or')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.array(
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.intersection(
+ z.object({
+ column: z.string().uuid(),
+ test: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isEmpty'),
+ z.literal('isNotEmpty'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ kind: z.literal('presence'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('startsWith'),
+ z.literal('endsWith'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.string(),
+ kind: z.literal('text'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('is'),
+ z.literal('isNot'),
+ z.literal('greaterThan'),
+ z.literal('greaterThanOrEqual'),
+ z.literal('lessThan'),
+ z.literal('lessThanOrEqual'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z.number(),
+ kind: z.literal('number'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('before'),
+ z.literal('after'),
+ z.literal('onOrBefore'),
+ z.literal('onOrAfter'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('date'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('contains'),
+ z.literal('doesNotContain'),
+ z.literal('endsBefore'),
+ z.literal('endsOnOrAfter'),
+ z.literal('startsAfter'),
+ z.literal('startsOnOrBefore'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ value: z
+ .string()
+ .datetime({ offset: true }),
+ kind: z.literal('dateRange'),
+ }),
+ z.object({
+ checked: z.boolean(),
+ kind: z.literal('checkbox'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ options: z.array(z.string().uuid()),
+ kind: z.literal('options'),
+ }),
+ z.object({
+ operator: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('isAnyOf'),
+ z.literal('isNoneOf'),
+ z.literal('hasAny'),
+ z.literal('hasAll'),
+ z.literal('hasNone'),
+ ];
+ const errors = schemas.reduce<
+ z.ZodError[]
+ >(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (
+ schemas.length - errors.length !==
+ 1
+ ) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entities: z.array(z.string()),
+ kind: z.literal('entities'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
+ z.object({ kind: z.literal('condition') })
+ ),
+ z.intersection(
+ z.object({
+ conjunction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('and'),
+ z.literal('or'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error
+ ? [...errors, result.error]
+ : errors)(schema.safeParse(x)),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message:
+ 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ conditions: z.any(),
+ }),
+ z.object({ kind: z.literal('group') })
+ ),
];
const errors = schemas.reduce<z.ZodError[]>(
(errors, schema) =>
@@ -14660,12 +17077,12 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
'Invalid input: Should pass single schema',
});
}
- }),
- z.null(),
- ])
- .optional(),
- })
- ),
+ })
+ ),
+ }),
+ z.null(),
+ ])
+ .optional(),
kind: z.literal('questions'),
}),
z.object({
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index cf264bfed0..b6fe4476b0 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -496,6 +496,13 @@ export type Section =
* Ordered questions.
*/
questions: Question2Question[];
+ /**
+ * Show this section only when earlier answers pass these rules,
+ * which reference questions of earlier sections like a gate's.
+ * A skipped section's questions are not required and their answers
+ * are not saved. Omitted means always shown.
+ */
+ showWhen?: Rules | null;
kind: 'questions';
}
| {
@@ -652,7 +659,7 @@ export type Widget =
*/
export type Conjunction = 'and' | 'or';
/**
- * One screening condition or nested nonempty group.
+ * One gate or show-when condition, or a nested nonempty group.
*/
export type Rule =
| {
@@ -913,6 +920,13 @@ export type FormSection =
* Its questions, in order.
*/
questions: QuestionLayout[];
+ /**
+ * When to show it: the rules answers of earlier shown sections must
+ * pass, naming only their columns. A section whose rules fail is
+ * skipped: its questions are not required and their answers are
+ * not written. Absent, it is always shown.
+ */
+ showWhen?: FilterGroup | null;
kind: 'questions';
}
| {
@@ -984,8 +998,10 @@ export type Code =
| 'ScreeningTooDeep'
| 'TooManyConditions'
| 'GateReferencesLaterQuestion'
+ | 'ShowWhenReferencesLaterQuestion'
| 'UnknownOption'
| 'InvalidGateRule'
+ | 'InvalidShowWhenRule'
| 'ConcurrentFieldChange'
| 'InvalidEdit'
| 'Forbidden'
@@ -1231,6 +1247,15 @@ export type Change =
rules: FilterGroup;
kind: 'setGateRules';
}
+ | {
+ sectionId: FormSectionId;
+ /**
+ * Nonempty AND/OR tree referencing earlier sections' question
+ * columns; null makes the section always shown.
+ */
+ showWhen?: FilterGroup | null;
+ kind: 'setShowWhen';
+ }
| {
sectionId: FormSectionId;
target: BookingTarget;
@@ -4559,6 +4584,12 @@ export type FormSectionDetail =
* Its questions, in order.
*/
questions: FormQuestionDetail[];
+ /**
+ * When to show it, from earlier shown sections' answers; absent,
+ * it is always shown. Sent to every caller so a respondent's page
+ * can skip it.
+ */
+ showWhen?: FilterGroup | null;
kind: 'questions';
}
| {
@@ -7670,7 +7701,7 @@ export interface CreateDocumentResponse {
documentId: string;
}
/**
- * Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating.
+ * Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. A questions section may set showWhen (rules like a gate's, referencing only questions of earlier sections) to branch: when earlier answers fail them the section is skipped, its questions are not required and their answers are not saved. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating.
*/
export interface CreateForm {
/**
@@ -7733,7 +7764,8 @@ export interface OptionDraft {
label: string;
}
/**
- * Gates support AND/OR, at most eight levels and 200 conditions.
+ * Gate and show-when rules support AND/OR, at most eight levels and 200
+ * conditions across the form.
*/
export interface Rules {
conjunction: Conjunction;
@@ -9182,7 +9214,7 @@ export interface EditDocumentResponse {
clarification?: string | null;
}
/**
- * Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
+ * Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates, set or clear a questions section's showWhen (setShowWhen; skipped sections' questions are not required or saved) and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates and showWhen rules after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
*/
export interface EditForm {
formId: FormId;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionDetailOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionDetailOneOf.ts
index e920aee668..08c92b2731 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionDetailOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionDetailOneOf.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
+import type { FilterGroup } from './filterGroup';
import type { FormQuestionDetail } from './formQuestionDetail';
import type { FormSectionDetailOneOfKind } from './formSectionDetailOneOfKind';
@@ -19,6 +20,10 @@ export type FormSectionDetailOneOf = {
kind: FormSectionDetailOneOfKind;
/** Its questions, in order. */
questions: FormQuestionDetail[];
+ /** When to show it, from earlier shown sections' answers; absent,
+it is always shown. Sent to every caller so a respondent's page
+can skip it. */
+ showWhen?: FilterGroup;
/** Its title. */
title: string;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionOneOf.ts
index 9b25fb8203..9c74cdbcc8 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formSectionOneOf.ts
@@ -4,6 +4,8 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+
+import type { FilterGroup } from './filterGroup';
import type { FormSectionOneOfKind } from './formSectionOneOfKind';
import type { QuestionLayout } from './questionLayout';
@@ -18,6 +20,11 @@ export type FormSectionOneOf = {
kind: FormSectionOneOfKind;
/** Its questions, in order. */
questions: QuestionLayout[];
+ /** When to show it: the rules answers of earlier shown sections must
+pass, naming only their columns. A section whose rules fail is
+skipped: its questions are not required and their answers are
+not written. Absent, it is always shown. */
+ showWhen?: FilterGroup;
/** Its title; may be empty. */
title: string;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 0a26ee1963..10f9b20cbc 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1339,8 +1339,12 @@ export * from './layoutProblemOneOfNine';
export * from './layoutProblemOneOfNineKind';
export * from './layoutProblemOneOfOnefive';
export * from './layoutProblemOneOfOnefiveKind';
+export * from './layoutProblemOneOfOnenine';
+export * from './layoutProblemOneOfOnenineKind';
export * from './layoutProblemOneOfOneone';
export * from './layoutProblemOneOfOneoneKind';
+export * from './layoutProblemOneOfOneseven';
+export * from './layoutProblemOneOfOnesevenKind';
export * from './layoutProblemOneOfOnethree';
export * from './layoutProblemOneOfOnethreeKind';
export * from './layoutProblemOneOfSeven';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblem.ts
index 6832544c33..3b9d39d88f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblem.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblem.ts
@@ -8,7 +8,9 @@ import type { LayoutProblemOneOf } from './layoutProblemOneOf';
import type { LayoutProblemOneOfFive } from './layoutProblemOneOfFive';
import type { LayoutProblemOneOfNine } from './layoutProblemOneOfNine';
import type { LayoutProblemOneOfOnefive } from './layoutProblemOneOfOnefive';
+import type { LayoutProblemOneOfOnenine } from './layoutProblemOneOfOnenine';
import type { LayoutProblemOneOfOneone } from './layoutProblemOneOfOneone';
+import type { LayoutProblemOneOfOneseven } from './layoutProblemOneOfOneseven';
import type { LayoutProblemOneOfOnethree } from './layoutProblemOneOfOnethree';
import type { LayoutProblemOneOfSeven } from './layoutProblemOneOfSeven';
import type { LayoutProblemOneOfThree } from './layoutProblemOneOfThree';
@@ -24,4 +26,6 @@ export type LayoutProblem =
| LayoutProblemOneOfNine
| LayoutProblemOneOfOneone
| LayoutProblemOneOfOnethree
- | LayoutProblemOneOfOnefive;
+ | LayoutProblemOneOfOnefive
+ | LayoutProblemOneOfOneseven
+ | LayoutProblemOneOfOnenine;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefive.ts
index fc7ad803f3..58b0652e4d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefive.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefive.ts
@@ -7,13 +7,10 @@
import type { LayoutProblemOneOfOnefiveKind } from './layoutProblemOneOfOnefiveKind';
/**
- * A text is longer than allowed.
+ * A section's show-when rules test a column no earlier section asks.
*/
export type LayoutProblemOneOfOnefive = {
+ /** The column. */
+ column: string;
kind: LayoutProblemOneOfOnefiveKind;
- /**
- * The longest allowed.
- * @minimum 0
- */
- max: number;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefiveKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefiveKind.ts
index bc40d8d7fe..bef072b884 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefiveKind.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnefiveKind.ts
@@ -10,5 +10,5 @@ export type LayoutProblemOneOfOnefiveKind =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const LayoutProblemOneOfOnefiveKind = {
- textTooLong: 'textTooLong',
+ conditionNamesLaterColumn: 'conditionNamesLaterColumn',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenine.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenine.ts
new file mode 100644
index 0000000000..9b2c9f13f6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenine.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { LayoutProblemOneOfOnenineKind } from './layoutProblemOneOfOnenineKind';
+
+/**
+ * A text is longer than allowed.
+ */
+export type LayoutProblemOneOfOnenine = {
+ kind: LayoutProblemOneOfOnenineKind;
+ /**
+ * The longest allowed.
+ * @minimum 0
+ */
+ max: number;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenineKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenineKind.ts
new file mode 100644
index 0000000000..a96e182c77
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnenineKind.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LayoutProblemOneOfOnenineKind =
+ (typeof LayoutProblemOneOfOnenineKind)[keyof typeof LayoutProblemOneOfOnenineKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const LayoutProblemOneOfOnenineKind = {
+ textTooLong: 'textTooLong',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOneseven.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOneseven.ts
new file mode 100644
index 0000000000..62a85325a2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOneseven.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { LayoutProblemOneOfOnesevenKind } from './layoutProblemOneOfOnesevenKind';
+
+/**
+ * A section's show-when rule does not fit its column.
+ */
+export type LayoutProblemOneOfOneseven = {
+ kind: LayoutProblemOneOfOnesevenKind;
+ /** Why. */
+ reason: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnesevenKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnesevenKind.ts
new file mode 100644
index 0000000000..cc81329476
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/layoutProblemOneOfOnesevenKind.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LayoutProblemOneOfOnesevenKind =
+ (typeof LayoutProblemOneOfOnesevenKind)[keyof typeof LayoutProblemOneOfOnesevenKind];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const LayoutProblemOneOfOnesevenKind = {
+ conditionRule: 'conditionRule',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 169ef96ee4..2607ef134e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -23440,6 +23440,205 @@ export const getFormResponse = zod
.describe("A question with its column's facts.")
)
.describe('Its questions, in order.'),
+ showWhen: zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe('Whether a cell is empty.'),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ kind: zod.enum(['dateRange']),
+ operator: zod
+ .enum([
+ 'contains',
+ 'doesNotContain',
+ 'endsBefore',
+ 'endsOnOrAfter',
+ 'startsAfter',
+ 'startsOnOrBefore',
+ ])
+ .describe(
+ "How a date-range cell stands to a day: the whole day starting at the\ntest's date-time, so a range from 1 PM to 5 PM contains its day."
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The start of the day compared against.'
+ ),
+ })
+ .describe('A date-range column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .optional()
+ .describe('Conditions joined by one conjunction.'),
title: zod.string().describe('Its title.'),
})
.describe('Questions asked together.'),
@@ -24143,18 +24342,7 @@ export const collaborateFormResponse = zod
.describe("A question with its column's facts.")
)
.describe('Its questions, in order.'),
- title: zod.string().describe('Its title.'),
- })
- .describe('Questions asked together.'),
- zod
- .object({
- description: zod.string().describe('Its description.'),
- id: zod.uuid().describe('The section.'),
- kind: zod.enum(['gate']),
- message: zod
- .string()
- .describe('What a stopped respondent reads.'),
- rules: zod
+ showWhen: zod
.object({
conditions: zod
.array(
@@ -24353,53 +24541,265 @@ export const collaborateFormResponse = zod
.enum(['and', 'or'])
.describe("How a group's conditions combine."),
})
+ .optional()
.describe('Conditions joined by one conjunction.'),
title: zod.string().describe('Its title.'),
})
- .describe(
- "A check of earlier answers. The rules are sent to every caller so a\nrespondent's page can stop them before submitting; respondents are\nnever shown them."
- ),
+ .describe('Questions asked together.'),
zod
.object({
description: zod.string().describe('Its description.'),
id: zod.uuid().describe('The section.'),
- kind: zod.enum(['booking']),
- target: zod
+ kind: zod.enum(['gate']),
+ message: zod
+ .string()
+ .describe('What a stopped respondent reads.'),
+ rules: zod
.object({
- eventTypeId: zod
- .uuid()
- .describe('The event type to book.'),
- profileId: zod
- .uuid()
- .describe(
- 'The scheduling profile that owns the event.'
- ),
- })
- .optional()
- .describe(
- 'An existing native Macro scheduling event offered after an accepted response.'
- ),
- title: zod.string().describe('Its title.'),
- })
- .describe(
- 'A booking step. Its destination is withheld from respondents until\ntheir response has passed every gate and been accepted.'
- ),
- ])
- .describe('One section of a form as it reads.')
- )
- .describe('Its sections, in order.'),
- tableGone: zod
- .boolean()
- .describe(
- 'Whether its database is in the trash, so it has no table to show or\nwrite: its sections keep no questions and it takes no responses.'
- ),
- })
- .describe('A form with its layout, as the caller may see it.'),
- publicationError: zod
- .union([
- zod
- .object({
- kind: zod.enum(['invalidDraft']),
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ kind: zod.enum(['dateRange']),
+ operator: zod
+ .enum([
+ 'contains',
+ 'doesNotContain',
+ 'endsBefore',
+ 'endsOnOrAfter',
+ 'startsAfter',
+ 'startsOnOrBefore',
+ ])
+ .describe(
+ "How a date-range cell stands to a day: the whole day starting at the\ntest's date-time, so a range from 1 PM to 5 PM contains its day."
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The start of the day compared against.'
+ ),
+ })
+ .describe('A date-range column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .describe('Conditions joined by one conjunction.'),
+ title: zod.string().describe('Its title.'),
+ })
+ .describe(
+ "A check of earlier answers. The rules are sent to every caller so a\nrespondent's page can stop them before submitting; respondents are\nnever shown them."
+ ),
+ zod
+ .object({
+ description: zod.string().describe('Its description.'),
+ id: zod.uuid().describe('The section.'),
+ kind: zod.enum(['booking']),
+ target: zod
+ .object({
+ eventTypeId: zod
+ .uuid()
+ .describe('The event type to book.'),
+ profileId: zod
+ .uuid()
+ .describe(
+ 'The scheduling profile that owns the event.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'An existing native Macro scheduling event offered after an accepted response.'
+ ),
+ title: zod.string().describe('Its title.'),
+ })
+ .describe(
+ 'A booking step. Its destination is withheld from respondents until\ntheir response has passed every gate and been accepted.'
+ ),
+ ])
+ .describe('One section of a form as it reads.')
+ )
+ .describe('Its sections, in order.'),
+ tableGone: zod
+ .boolean()
+ .describe(
+ 'Whether its database is in the trash, so it has no table to show or\nwrite: its sections keep no questions and it takes no responses.'
+ ),
+ })
+ .describe('A form with its layout, as the caller may see it.'),
+ publicationError: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['invalidDraft']),
})
.describe(
'The draft contains unsupported or malformed layout records. An explicit\nlayout replacement can repair it without replacing its document history.'
@@ -24456,6 +24856,22 @@ export const collaborateFormResponse = zod
reason: zod.string().describe('Why.'),
})
.describe("A gate's rule does not fit its column."),
+ zod
+ .object({
+ column: zod.uuid().describe('The column.'),
+ kind: zod.enum(['conditionNamesLaterColumn']),
+ })
+ .describe(
+ "A section's show-when rules test a column no earlier section asks."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['conditionRule']),
+ reason: zod.string().describe('Why.'),
+ })
+ .describe(
+ "A section's show-when rule does not fit its column."
+ ),
zod
.object({
kind: zod.enum(['textTooLong']),
@@ -24536,33 +24952,232 @@ export const putFormLayoutBody = zod
id: zod
.uuid()
.describe(
- 'The question, under an id the client mints; answers name it.'
- ),
- required: zod
- .boolean()
- .describe('Whether a response must answer it.'),
- widget: zod.union([
- zod.null(),
- zod
- .enum([
- 'short',
- 'paragraph',
- 'datetime',
- 'date',
- 'url',
- 'file',
- 'choice',
- 'dropdown',
- 'checkboxes',
- ])
- .describe(
- 'How a question is asked. Each column kind takes a few, the first its\ndefault; kinds asked one way only (numbers, checkboxes, date ranges,\nentity and row pickers) take none.'
- ),
- ]),
- })
- .describe('How one column of the table is asked.')
- )
- .describe('Its questions, in order.'),
+ 'The question, under an id the client mints; answers name it.'
+ ),
+ required: zod
+ .boolean()
+ .describe('Whether a response must answer it.'),
+ widget: zod.union([
+ zod.null(),
+ zod
+ .enum([
+ 'short',
+ 'paragraph',
+ 'datetime',
+ 'date',
+ 'url',
+ 'file',
+ 'choice',
+ 'dropdown',
+ 'checkboxes',
+ ])
+ .describe(
+ 'How a question is asked. Each column kind takes a few, the first its\ndefault; kinds asked one way only (numbers, checkboxes, date ranges,\nentity and row pickers) take none.'
+ ),
+ ]),
+ })
+ .describe('How one column of the table is asked.')
+ )
+ .describe('Its questions, in order.'),
+ showWhen: zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe('Whether a cell is empty.'),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ kind: zod.enum(['dateRange']),
+ operator: zod
+ .enum([
+ 'contains',
+ 'doesNotContain',
+ 'endsBefore',
+ 'endsOnOrAfter',
+ 'startsAfter',
+ 'startsOnOrBefore',
+ ])
+ .describe(
+ "How a date-range cell stands to a day: the whole day starting at the\ntest's date-time, so a range from 1 PM to 5 PM contains its day."
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The start of the day compared against.'
+ ),
+ })
+ .describe('A date-range column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .optional()
+ .describe('Conditions joined by one conjunction.'),
title: zod.string().describe('Its title; may be empty.'),
})
.describe('Questions asked together.'),
@@ -25103,6 +25718,207 @@ export const putFormLayoutResponse = zod
.describe("A question with its column's facts.")
)
.describe('Its questions, in order.'),
+ showWhen: zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ kind: zod.enum(['dateRange']),
+ operator: zod
+ .enum([
+ 'contains',
+ 'doesNotContain',
+ 'endsBefore',
+ 'endsOnOrAfter',
+ 'startsAfter',
+ 'startsOnOrBefore',
+ ])
+ .describe(
+ "How a date-range cell stands to a day: the whole day starting at the\ntest's date-time, so a range from 1 PM to 5 PM contains its day."
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The start of the day compared against.'
+ ),
+ })
+ .describe('A date-range column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .optional()
+ .describe('Conditions joined by one conjunction.'),
title: zod.string().describe('Its title.'),
})
.describe('Questions asked together.'),
@@ -25416,6 +26232,22 @@ export const putFormLayoutResponse = zod
reason: zod.string().describe('Why.'),
})
.describe("A gate's rule does not fit its column."),
+ zod
+ .object({
+ column: zod.uuid().describe('The column.'),
+ kind: zod.enum(['conditionNamesLaterColumn']),
+ })
+ .describe(
+ "A section's show-when rules test a column no earlier section asks."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['conditionRule']),
+ reason: zod.string().describe('Why.'),
+ })
+ .describe(
+ "A section's show-when rule does not fit its column."
+ ),
zod
.object({
kind: zod.enum(['textTooLong']),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 3b885c2a8e..80485a4a3b 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -32821,6 +32821,10 @@
},
"description": "Its questions, in order."
},
+ "showWhen": {
+ "$ref": "#/components/schemas/FilterGroup",
+ "description": "When to show it: the rules answers of earlier shown sections must\npass, naming only their columns. A section whose rules fail is\nskipped: its questions are not required and their answers are\nnot written. Absent, it is always shown."
+ },
"title": {
"type": "string",
"description": "Its title; may be empty."
@@ -32924,6 +32928,10 @@
},
"description": "Its questions, in order."
},
+ "showWhen": {
+ "$ref": "#/components/schemas/FilterGroup",
+ "description": "When to show it, from earlier shown sections' answers; absent,\nit is always shown. Sent to every caller so a respondent's page\ncan skip it."
+ },
"title": {
"type": "string",
"description": "Its title."
@@ -35496,6 +35504,37 @@
}
}
},
+ {
+ "type": "object",
+ "description": "A section's show-when rules test a column no earlier section asks.",
+ "required": ["column", "kind"],
+ "properties": {
+ "column": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The column."
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["conditionNamesLaterColumn"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A section's show-when rule does not fit its column.",
+ "required": ["reason", "kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["conditionRule"]
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why."
+ }
+ }
+ },
{
"type": "object",
"description": "A text is longer than allowed.",
diff --git a/crates/forms/AGENTS.md b/crates/forms/AGENTS.md
index a4f0e4d52c..c31cccbd1c 100644
--- a/crates/forms/AGENTS.md
+++ b/crates/forms/AGENTS.md
@@ -39,6 +39,11 @@ service.
- Add a layout field: `src/domain/authoring/models.rs` → `src/domain/authoring/edit.rs`
→ `src/domain/authoring/validate.rs` → `src/outbound/collaborative_layout.rs`.
- Add an AI authoring tool: `src/inbound/toolset.rs` → `src/domain/authoring/workflow.rs`.
+- Change section rules (gates, a questions section's `showWhen` branching):
+ `models_forms` → `src/domain/service/layout.rs` (`validate_layout`,
+ `gates_fit_table`) → `src/domain/service/answers.rs` (`evaluate`) →
+ `src/domain/authoring/validate.rs` → `src/outbound/pg_forms_repo/layout.rs`.
+ A skipped section's answers are ignored and count as unanswered.
- Add a submission rule: `src/domain/service.rs` (`submit`/`answers` modules)
→ `src/outbound/pg_forms_repo.rs`.
diff --git a/crates/forms/src/domain/authoring/edit.rs b/crates/forms/src/domain/authoring/edit.rs
index 9d32cb79b6..22c47c417d 100644
--- a/crates/forms/src/domain/authoring/edit.rs
+++ b/crates/forms/src/domain/authoring/edit.rs
@@ -186,6 +186,18 @@ fn apply_step(latest: &FormLayout, change: &Change) -> Result<FormLayout, Author
};
*target = rules.clone();
}
+ Change::SetShowWhen {
+ section_id,
+ show_when,
+ } => {
+ let FormSection::Questions {
+ show_when: target, ..
+ } = section_mut(&mut next, *section_id)?
+ else {
+ return Err(invalid("Select a questions section."));
+ };
+ *target = show_when.clone();
+ }
Change::SetBookingTarget {
section_id,
target,
diff --git a/crates/forms/src/domain/authoring/edit/test.rs b/crates/forms/src/domain/authoring/edit/test.rs
index cd10c2314a..e123fc82a3 100644
--- a/crates/forms/src/domain/authoring/edit/test.rs
+++ b/crates/forms/src/domain/authoring/edit/test.rs
@@ -17,6 +17,7 @@ fn help_text_edit_changes_only_requested_fields_in_the_current_layout() {
required: false,
widget: None,
}],
+ show_when: None,
}],
};
let mut latest = base.clone();
@@ -66,12 +67,14 @@ fn a_batch_can_move_then_edit_a_question_without_losing_either_change() {
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Questions {
id: second,
title: String::new(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
};
@@ -106,6 +109,7 @@ fn a_batch_can_add_then_edit_a_question() {
title: String::new(),
description: String::new(),
questions: vec![],
+ show_when: None,
}],
};
let changes = vec![
@@ -134,3 +138,112 @@ fn a_batch_can_add_then_edit_a_question() {
};
assert!(questions[0].required);
}
+
+#[test]
+fn show_when_is_set_kept_by_unrelated_edits_cleared_by_null_and_only_on_questions_sections() {
+ use models_databases::views::{
+ Conjunction, FilterCondition, FilterGroup, FilterNode, FilterTest, PresenceOperator,
+ };
+ let first = FormSectionId::new();
+ let second = FormSectionId::new();
+ let gate = FormSectionId::new();
+ let column = ColumnId::new();
+ let rules = FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column,
+ test: FilterTest::Presence {
+ operator: PresenceOperator::IsNotEmpty,
+ },
+ })],
+ };
+ let base = FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: first,
+ title: "About you".into(),
+ description: String::new(),
+ questions: vec![QuestionLayout {
+ id: FormQuestionId::new(),
+ column,
+ help_text: String::new(),
+ required: false,
+ widget: None,
+ }],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: second,
+ title: "Follow-up".into(),
+ description: String::new(),
+ questions: vec![],
+ show_when: None,
+ },
+ FormSection::Gate {
+ id: gate,
+ title: String::new(),
+ description: String::new(),
+ rules: rules.clone(),
+ message: "No".into(),
+ },
+ ],
+ };
+
+ let set = apply(
+ &base,
+ &[
+ Change::SetShowWhen {
+ section_id: second,
+ show_when: Some(rules.clone()),
+ },
+ Change::SetSectionText {
+ section_id: second,
+ title: Some("More".into()),
+ description: None,
+ message: None,
+ },
+ ],
+ )
+ .unwrap();
+
+ assert_eq!(
+ set.sections[1],
+ FormSection::Questions {
+ id: second,
+ title: "More".into(),
+ description: String::new(),
+ questions: vec![],
+ show_when: Some(rules.clone()),
+ }
+ );
+ let cleared = apply(
+ &set,
+ &[Change::SetShowWhen {
+ section_id: second,
+ show_when: None,
+ }],
+ )
+ .unwrap();
+ assert_eq!(
+ cleared.sections[1],
+ FormSection::Questions {
+ id: second,
+ title: "More".into(),
+ description: String::new(),
+ questions: vec![],
+ show_when: None,
+ }
+ );
+ assert_eq!(
+ apply(
+ &base,
+ &[Change::SetShowWhen {
+ section_id: gate,
+ show_when: Some(rules),
+ }],
+ )
+ .unwrap_err()
+ .code,
+ Code::InvalidEdit
+ );
+}
diff --git a/crates/forms/src/domain/authoring/models.rs b/crates/forms/src/domain/authoring/models.rs
index 8203795a5d..367f9c4488 100644
--- a/crates/forms/src/domain/authoring/models.rs
+++ b/crates/forms/src/domain/authoring/models.rs
@@ -93,7 +93,7 @@ pub enum Predicate {
options: Vec<Reference<OptionId>>,
},
}
-/// One screening condition or nested nonempty group.
+/// One gate or show-when condition, or a nested nonempty group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
pub enum Rule {
@@ -107,7 +107,8 @@ pub enum Rule {
/// Nested conjunction.
Group(Rules),
}
-/// Gates support AND/OR, at most eight levels and 200 conditions.
+/// Gate and show-when rules support AND/OR, at most eight levels and 200
+/// conditions across the form.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Rules {
@@ -146,6 +147,12 @@ pub enum Section {
description: String,
/// Ordered questions.
questions: Vec<Question>,
+ /// Show this section only when earlier answers pass these rules,
+ /// which reference questions of earlier sections like a gate's.
+ /// A skipped section's questions are not required and their answers
+ /// are not saved. Omitted means always shown.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ show_when: Option<Rules>,
},
/// Stop respondents whose previous answers fail.
Gate {
@@ -317,6 +324,16 @@ pub enum Change {
/// Nonempty AND/OR tree referencing earlier questions' columns.
rules: models_databases::views::FilterGroup,
},
+ /// Set or clear when a questions section is shown, using saved
+ /// column/option ids from ReadForm. A skipped section's questions are
+ /// not required and their answers are not saved.
+ SetShowWhen {
+ /// Existing questions section.
+ section_id: FormSectionId,
+ /// Nonempty AND/OR tree referencing earlier sections' question
+ /// columns; null makes the section always shown.
+ show_when: Option<models_databases::views::FilterGroup>,
+ },
/// Replace the final booking destination after authorized Scheduling validation.
SetBookingTarget {
/// Existing booking section.
@@ -445,10 +462,14 @@ pub enum Code {
TooManyConditions,
/// GateReferencesLaterQuestion: see the accompanying path and corrective message.
GateReferencesLaterQuestion,
+ /// A section's show-when rules reference a question of its own or a later section.
+ ShowWhenReferencesLaterQuestion,
/// UnknownOption: see the accompanying path and corrective message.
UnknownOption,
/// InvalidGateRule: see the accompanying path and corrective message.
InvalidGateRule,
+ /// A section's show-when rule does not fit its question's column.
+ InvalidShowWhenRule,
/// ConcurrentFieldChange: see the accompanying path and corrective message.
ConcurrentFieldChange,
/// InvalidEdit: see the accompanying path and corrective message.
diff --git a/crates/forms/src/domain/authoring/validate.rs b/crates/forms/src/domain/authoring/validate.rs
index 662f9a5c29..5c3a326c84 100644
--- a/crates/forms/src/domain/authoring/validate.rs
+++ b/crates/forms/src/domain/authoring/validate.rs
@@ -25,6 +25,42 @@ pub struct Prepared {
fn fail(code: Code, path: &str, message: &str) -> AuthoringError {
AuthoringError::new(code, path, message)
}
+/// What a set of rules decides, which names its refusals.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum RulesOf {
+ /// A gate's rules: who may continue.
+ Gate,
+ /// A questions section's show-when rules: whether it is shown.
+ ShowWhen,
+}
+impl RulesOf {
+ fn path(self) -> &'static str {
+ match self {
+ RulesOf::Gate => "rules",
+ RulesOf::ShowWhen => "showWhen",
+ }
+ }
+ fn later_question(self) -> AuthoringError {
+ match self {
+ RulesOf::Gate => fail(
+ Code::GateReferencesLaterQuestion,
+ "rules",
+ "Gates may only reference questions in earlier sections.",
+ ),
+ RulesOf::ShowWhen => fail(
+ Code::ShowWhenReferencesLaterQuestion,
+ "showWhen",
+ "showWhen may only reference questions in earlier sections, not its own.",
+ ),
+ }
+ }
+ fn invalid_rule(self, reason: String) -> AuthoringError {
+ match self {
+ RulesOf::Gate => AuthoringError::new(Code::InvalidGateRule, "rules", reason),
+ RulesOf::ShowWhen => AuthoringError::new(Code::InvalidShowWhenRule, "showWhen", reason),
+ }
+ }
+}
/// Validate bounded text using the same character units as Forms.
pub fn text(value: &str, max: usize, path: &str) -> Result<(), AuthoringError> {
if value.chars().count() > max {
@@ -94,7 +130,32 @@ pub fn prepare(draft: &Draft, existing: &[Column]) -> Result<Prepared, Authoring
let id = FormSectionId::new();
result.keys.sections.insert(section_key.clone(), id);
let resolved = match section {
- Section::Questions { questions, .. } => {
+ Section::Questions {
+ questions,
+ show_when,
+ ..
+ } => {
+ let show_when = show_when
+ .as_ref()
+ .map(|rules| {
+ let rules = resolve_rules(
+ rules,
+ &earlier,
+ 0,
+ &mut condition_count,
+ RulesOf::ShowWhen,
+ )?;
+ check_rules(
+ &rules,
+ &earlier
+ .values()
+ .map(|(_, c, _)| c.clone())
+ .collect::<Vec<_>>(),
+ RulesOf::ShowWhen,
+ )?;
+ Ok::<_, AuthoringError>(rules)
+ })
+ .transpose()?;
let mut placements = vec![];
for question in questions {
key(
@@ -250,17 +311,19 @@ pub fn prepare(draft: &Draft, existing: &[Column]) -> Result<Prepared, Authoring
title: title.clone(),
description: description.clone(),
questions: placements,
+ show_when,
}
}
Section::Gate { rules, message, .. } => {
text(message, 10_000, section_key)?;
- let rules = resolve_rules(rules, &earlier, 0, &mut condition_count)?;
+ let rules = resolve_rules(rules, &earlier, 0, &mut condition_count, RulesOf::Gate)?;
check_rules(
&rules,
&earlier
.values()
.map(|(_, c, _)| c.clone())
.collect::<Vec<_>>(),
+ RulesOf::Gate,
)?;
FormSection::Gate {
id,
@@ -307,18 +370,26 @@ fn resolve_rules(
earlier: &References,
depth: usize,
count: &mut usize,
+ of: RulesOf,
) -> Result<FilterGroup, AuthoringError> {
if rules.conditions.is_empty() {
return Err(fail(
Code::EmptyScreeningGroup,
- "rules",
- "Add a condition or remove the gate; an empty group qualifies everyone.",
+ of.path(),
+ match of {
+ RulesOf::Gate => {
+ "Add a condition or remove the gate; an empty group qualifies everyone."
+ }
+ RulesOf::ShowWhen => {
+ "Add a condition or omit showWhen; an empty group always shows the section."
+ }
+ },
));
}
if depth >= 8 {
return Err(fail(
Code::ScreeningTooDeep,
- "rules",
+ of.path(),
"Use at most eight levels.",
));
}
@@ -327,14 +398,14 @@ fn resolve_rules(
.iter()
.map(|rule| match rule {
Rule::Group(group) => {
- resolve_rules(group, earlier, depth + 1, count).map(FilterNode::Group)
+ resolve_rules(group, earlier, depth + 1, count, of).map(FilterNode::Group)
}
Rule::Condition { question, test } => {
*count += 1;
if *count > 200 {
return Err(fail(
Code::TooManyConditions,
- "rules",
+ of.path(),
"Use at most 200 conditions.",
));
}
@@ -344,13 +415,7 @@ fn resolve_rules(
earlier.values().find(|(question, _, _)| question == id)
}
}
- .ok_or_else(|| {
- fail(
- Code::GateReferencesLaterQuestion,
- "rules.question",
- "Reference a question in an earlier section.",
- )
- })?;
+ .ok_or_else(|| of.later_question())?;
let (_, column, options_by_key) = found;
let test = match test {
Predicate::Value { test } => test.clone(),
@@ -363,7 +428,7 @@ fn resolve_rules(
options_by_key.get(key).copied().ok_or_else(|| {
fail(
Code::UnknownOption,
- "rules.options",
+ of.path(),
"Use an option key declared on this question.",
)
})
@@ -386,7 +451,7 @@ fn resolve_rules(
})
}
/// Validate canonical rules against the current schema, including option membership.
-pub fn check_rules(rules: &FilterGroup, columns: &[Column]) -> Result<(), AuthoringError> {
+fn check_rules(rules: &FilterGroup, columns: &[Column], of: RulesOf) -> Result<(), AuthoringError> {
let schema = columns
.iter()
.map(|c| {
@@ -412,7 +477,7 @@ pub fn check_rules(rules: &FilterGroup, columns: &[Column]) -> Result<(), Author
&ViewLayout::Table { columns: vec![] },
&schema,
)
- .map_err(|e| AuthoringError::new(Code::InvalidGateRule, "rules", e.to_string()))
+ .map_err(|e| of.invalid_rule(e.to_string()))
}
fn finite_number(label: &str) -> Option<f64> {
@@ -466,8 +531,15 @@ pub fn canonical_preserving(
.sections
.iter()
.map(|section| match section {
- FormSection::Gate { rules, .. } => rules.conditions().len(),
- _ => 0,
+ FormSection::Gate { rules, .. }
+ | FormSection::Questions {
+ show_when: Some(rules),
+ ..
+ } => rules.conditions().len(),
+ FormSection::Questions {
+ show_when: None, ..
+ }
+ | FormSection::Booking { .. } => 0,
})
.sum()
};
@@ -495,10 +567,20 @@ pub fn canonical_preserving(
title,
description,
questions,
+ show_when,
..
} => {
text(title, 200, "section.title")?;
text(description, 10_000, "section.description")?;
+ if let Some(rules) = show_when {
+ let unchanged = previous.is_some_and(|layout| {
+ layout.sections.iter().any(|old| {
+ matches!(old, FormSection::Questions { id, show_when: Some(previous_rules), .. }
+ if *id == section.id() && previous_rules == rules)
+ })
+ });
+ rules_fit(rules, unchanged, &asked, columns, RulesOf::ShowWhen)?;
+ }
for q in questions {
count += 1;
if count > 500 && count > previous_questions.len() {
@@ -568,22 +650,7 @@ pub fn canonical_preserving(
text(message, 10_000, "gate.message")?;
let unchanged_rules = previous.is_some_and(|layout| layout.sections.iter().any(|old| matches!(old,
FormSection::Gate { id, rules: previous_rules, .. } if *id == section.id() && previous_rules == rules)));
- if !unchanged_rules {
- let mut conditions = 0;
- nonempty(rules, 0, &mut conditions)?;
- }
- if rules
- .conditions()
- .iter()
- .any(|c| !asked.contains(&c.column))
- {
- return Err(fail(
- Code::GateReferencesLaterQuestion,
- "rules",
- "Gates may only reference questions in earlier sections.",
- ));
- }
- check_rules(rules, columns)?;
+ rules_fit(rules, unchanged_rules, &asked, columns, RulesOf::Gate)?;
}
FormSection::Booking {
title, description, ..
@@ -602,31 +669,60 @@ pub fn canonical_preserving(
}
Ok(())
}
-fn nonempty(rules: &FilterGroup, depth: usize, count: &mut usize) -> Result<(), AuthoringError> {
+/// Check canonical rules over the columns `asked` before their section:
+/// authored rules must be nonempty and bounded (rules an editor left
+/// `unchanged` keep whatever shape they have), and every rule names an
+/// earlier question and fits its column.
+fn rules_fit(
+ rules: &FilterGroup,
+ unchanged: bool,
+ asked: &HashSet<ColumnId>,
+ columns: &[Column],
+ of: RulesOf,
+) -> Result<(), AuthoringError> {
+ if !unchanged {
+ let mut conditions = 0;
+ nonempty(rules, 0, &mut conditions, of)?;
+ }
+ if rules
+ .conditions()
+ .iter()
+ .any(|c| !asked.contains(&c.column))
+ {
+ return Err(of.later_question());
+ }
+ check_rules(rules, columns, of)
+}
+fn nonempty(
+ rules: &FilterGroup,
+ depth: usize,
+ count: &mut usize,
+ of: RulesOf,
+) -> Result<(), AuthoringError> {
if rules.conditions.is_empty() {
return Err(fail(
Code::EmptyScreeningGroup,
- "rules",
+ of.path(),
"Remove the empty group or add a condition.",
));
}
if depth >= 8 {
return Err(fail(
Code::ScreeningTooDeep,
- "rules",
+ of.path(),
"Use at most eight levels.",
));
}
for node in &rules.conditions {
match node {
- FilterNode::Group(g) => nonempty(g, depth + 1, count)?,
+ FilterNode::Group(g) => nonempty(g, depth + 1, count, of)?,
FilterNode::Condition(_) => *count += 1,
}
}
if *count > 200 {
return Err(fail(
Code::TooManyConditions,
- "rules",
+ of.path(),
"Use at most 200 conditions.",
));
}
@@ -674,6 +770,7 @@ pub fn additions(
widget: None,
})
.collect(),
+ show_when: None,
}],
};
let prepared = prepare(&draft, existing)?;
diff --git a/crates/forms/src/domain/authoring/validate/test.rs b/crates/forms/src/domain/authoring/validate/test.rs
index 61feef9a15..c4aff34720 100644
--- a/crates/forms/src/domain/authoring/validate/test.rs
+++ b/crates/forms/src/domain/authoring/validate/test.rs
@@ -96,6 +96,7 @@ fn review_regression_preserving_human_content_keeps_authoring_limits() {
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Gate {
id: FormSectionId::new(),
@@ -192,3 +193,165 @@ fn review_regression_preserving_human_content_keeps_authoring_limits() {
"an existing over-limit layout can still be shared or restricted"
);
}
+
+#[test]
+fn show_when_resolves_earlier_keys_and_refuses_its_own_or_later_questions() {
+ let draft: Draft = serde_json::from_value(json!({"sections":[
+ {"kind":"questions","key":"about","questions":[
+ {"key":"role","column":{"kind":"new","name":"Role","type":{"type":"select","multi":false},"options":[
+ {"key":"employee","label":"Employee"},{"key":"contractor","label":"Contractor"}]},"required":true}]},
+ {"kind":"questions","key":"logistics","questions":[
+ {"key":"diet","column":{"kind":"new","name":"Diet","type":{"type":"text"}},"required":true}],
+ "showWhen":{"conjunction":"and","conditions":[{"kind":"condition","question":{"key":"role"},
+ "test":{"kind":"options","operator":"isAnyOf","options":[{"key":"employee"}]}}]}}
+ ]})).unwrap();
+
+ let plan = prepare(&draft, &[]).unwrap();
+
+ let FormSection::Questions { show_when, .. } = &plan.layout.sections[1] else {
+ panic!("questions")
+ };
+ assert_eq!(
+ show_when,
+ &Some(FilterGroup {
+ conjunction: models_databases::views::Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: plan.keys.columns["role"],
+ test: FilterTest::Options {
+ operator: models_databases::views::SetOperator::IsAnyOf,
+ options: vec![plan.keys.options["role"]["employee"]],
+ },
+ })],
+ })
+ );
+ let FormSection::Questions { show_when, .. } = &plan.layout.sections[0] else {
+ panic!("questions")
+ };
+ assert_eq!(show_when, &None);
+
+ // The section's own question is not earlier.
+ let mut own: Draft = draft.clone();
+ let Section::Questions { show_when, .. } = &mut own.sections[1] else {
+ panic!("questions")
+ };
+ let Some(rules) = show_when else {
+ panic!("showWhen")
+ };
+ rules.conditions = vec![Rule::Condition {
+ question: Reference::Key { key: "diet".into() },
+ test: Predicate::Value {
+ test: FilterTest::Presence {
+ operator: models_databases::views::PresenceOperator::IsEmpty,
+ },
+ },
+ }];
+ let error = prepare(&own, &[]).unwrap_err();
+ assert_eq!(error.code, Code::ShowWhenReferencesLaterQuestion);
+ assert_eq!(error.path, "showWhen");
+
+ // A text test does not fit a select.
+ let mut misfit: Draft = draft.clone();
+ let Section::Questions { show_when, .. } = &mut misfit.sections[1] else {
+ panic!("questions")
+ };
+ let Some(rules) = show_when else {
+ panic!("showWhen")
+ };
+ rules.conditions = vec![Rule::Condition {
+ question: Reference::Key { key: "role".into() },
+ test: Predicate::Value {
+ test: FilterTest::Text {
+ operator: models_databases::views::TextOperator::Is,
+ value: "Employee".into(),
+ },
+ },
+ }];
+ assert_eq!(
+ prepare(&misfit, &[]).unwrap_err().code,
+ Code::InvalidShowWhenRule
+ );
+}
+
+#[test]
+fn a_canonical_show_when_must_name_an_earlier_section_and_an_unchanged_one_is_kept() {
+ use models_forms::{Audience, FormQuestionId, FormSectionId, QuestionLayout};
+ let role = Column {
+ id: ColumnId::new(),
+ name: "Role".into(),
+ kind: ColumnKind::Text,
+ options: vec![],
+ };
+ let diet = Column {
+ id: ColumnId::new(),
+ name: "Diet".into(),
+ kind: ColumnKind::Text,
+ options: vec![],
+ };
+ let on = |column: ColumnId| FilterGroup {
+ conjunction: models_databases::views::Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column,
+ test: FilterTest::Text {
+ operator: models_databases::views::TextOperator::Is,
+ value: "Employee".into(),
+ },
+ })],
+ };
+ let layout = |show_when: Option<FilterGroup>| FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: FormSectionId::from_uuid(uuid::Uuid::from_u128(1)),
+ title: String::new(),
+ description: String::new(),
+ questions: vec![QuestionLayout {
+ id: FormQuestionId::from_uuid(uuid::Uuid::from_u128(2)),
+ column: role.id,
+ help_text: String::new(),
+ required: false,
+ widget: None,
+ }],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: FormSectionId::from_uuid(uuid::Uuid::from_u128(3)),
+ title: String::new(),
+ description: String::new(),
+ questions: vec![QuestionLayout {
+ id: FormQuestionId::from_uuid(uuid::Uuid::from_u128(4)),
+ column: diet.id,
+ help_text: String::new(),
+ required: false,
+ widget: None,
+ }],
+ show_when,
+ },
+ ],
+ };
+ let columns = vec![role.clone(), diet.clone()];
+
+ assert!(canonical(&layout(Some(on(role.id))), &columns, &[], Audience::Members).is_ok());
+ assert_eq!(
+ canonical(&layout(Some(on(diet.id))), &columns, &[], Audience::Members)
+ .unwrap_err()
+ .code,
+ Code::ShowWhenReferencesLaterQuestion
+ );
+ let empty = FilterGroup {
+ conjunction: models_databases::views::Conjunction::And,
+ conditions: vec![],
+ };
+ assert_eq!(
+ canonical(
+ &layout(Some(empty.clone())),
+ &columns,
+ &[],
+ Audience::Members
+ )
+ .unwrap_err()
+ .code,
+ Code::EmptyScreeningGroup
+ );
+ // An empty group an editor saved stays editable around.
+ let saved = layout(Some(empty));
+ assert!(canonical_preserving(&saved, &columns, &[], Audience::Members, Some(&saved)).is_ok());
+}
diff --git a/crates/forms/src/domain/authoring/workflow/edit.rs b/crates/forms/src/domain/authoring/workflow/edit.rs
index 51eb57f24a..ac7779c12e 100644
--- a/crates/forms/src/domain/authoring/workflow/edit.rs
+++ b/crates/forms/src/domain/authoring/workflow/edit.rs
@@ -120,15 +120,27 @@ fn schema_dependencies(
}
}
}
- Change::SetGateRules { rules, .. } => {
- ids.extend(rules.conditions().iter().map(|c| c.column))
- }
+ Change::SetGateRules { rules, .. }
+ | Change::SetShowWhen {
+ show_when: Some(rules),
+ ..
+ } => ids.extend(rules.conditions().iter().map(|c| c.column)),
Change::AddQuestion { question, .. } => {
ids.insert(question.column);
}
Change::AddSection { section, .. } => match section {
- FormSection::Questions { questions, .. } => {
- ids.extend(questions.iter().map(|q| q.column))
+ FormSection::Questions {
+ questions,
+ show_when,
+ ..
+ } => {
+ ids.extend(questions.iter().map(|q| q.column));
+ ids.extend(
+ show_when
+ .iter()
+ .flat_map(|rules| rules.conditions())
+ .map(|c| c.column),
+ );
}
FormSection::Gate { rules, .. } => {
ids.extend(rules.conditions().iter().map(|c| c.column))
diff --git a/crates/forms/src/domain/collaboration/test.rs b/crates/forms/src/domain/collaboration/test.rs
index 1c029bbd50..6c35bbb4a0 100644
--- a/crates/forms/src/domain/collaboration/test.rs
+++ b/crates/forms/src/domain/collaboration/test.rs
@@ -60,6 +60,7 @@ fn fixture_layout() -> FormLayout {
widget: None,
},
],
+ show_when: None,
},
FormSection::Gate {
id: SCREENING,
@@ -82,6 +83,7 @@ fn fixture_layout() -> FormLayout {
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
}
@@ -118,12 +120,14 @@ fn shared_layout() -> FormLayout {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
}
diff --git a/crates/forms/src/domain/collaboration/test/booking_order.rs b/crates/forms/src/domain/collaboration/test/booking_order.rs
index 0241ea8c02..30057295cd 100644
--- a/crates/forms/src/domain/collaboration/test/booking_order.rs
+++ b/crates/forms/src/domain/collaboration/test/booking_order.rs
@@ -27,6 +27,7 @@ fn contact() -> FormSection {
required: false,
widget: None,
}],
+ show_when: None,
}
}
@@ -36,6 +37,7 @@ fn details() -> FormSection {
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
}
}
@@ -45,6 +47,7 @@ fn travel() -> FormSection {
title: "Travel".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
}
}
@@ -200,6 +203,7 @@ fn concurrent_booking_steps_both_read_last_and_stay_repairable() {
required: false,
widget: None,
}],
+ show_when: None,
};
let rename = replace_layout(&merged, &renamed).unwrap();
assert_eq!(merge(&merged, &[&rename.update]), renamed);
@@ -226,6 +230,7 @@ fn concurrent_booking_steps_both_read_last_and_stay_repairable() {
required: false,
widget: None,
}],
+ show_when: None,
},
details(),
intro_booking(),
diff --git a/crates/forms/src/domain/collaboration/test/concurrent_deletes.rs b/crates/forms/src/domain/collaboration/test/concurrent_deletes.rs
index 5d5962bbef..03f152a424 100644
--- a/crates/forms/src/domain/collaboration/test/concurrent_deletes.rs
+++ b/crates/forms/src/domain/collaboration/test/concurrent_deletes.rs
@@ -27,12 +27,14 @@ fn a_deleted_question_stays_deleted_when_moved_concurrently() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -62,6 +64,7 @@ fn a_deleted_question_stays_deleted_when_moved_concurrently() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
@@ -74,6 +77,7 @@ fn a_deleted_question_stays_deleted_when_moved_concurrently() {
required: true,
widget: None,
}],
+ show_when: None,
},
],
},
@@ -110,12 +114,14 @@ fn a_deleted_question_stays_deleted_when_moved_concurrently() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -144,12 +150,14 @@ fn a_deleted_question_stays_deleted_when_moved_concurrently() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
};
@@ -210,6 +218,7 @@ fn a_deleted_section_stays_deleted_when_reordered_concurrently() {
widget: None,
},
],
+ show_when: None,
}],
},
)
@@ -223,6 +232,7 @@ fn a_deleted_section_stays_deleted_when_reordered_concurrently() {
title: "Details first".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
FormSection::Questions {
id: CONTACT,
@@ -251,6 +261,7 @@ fn a_deleted_section_stays_deleted_when_reordered_concurrently() {
widget: None,
},
],
+ show_when: None,
},
],
},
@@ -291,6 +302,7 @@ fn a_deleted_section_stays_deleted_when_reordered_concurrently() {
widget: None,
},
],
+ show_when: None,
}],
}
);
@@ -329,6 +341,7 @@ fn a_question_moved_into_a_concurrently_deleted_section_is_left_out() {
widget: None,
},
],
+ show_when: None,
}],
},
)
@@ -357,6 +370,7 @@ fn a_question_moved_into_a_concurrently_deleted_section_is_left_out() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
@@ -369,6 +383,7 @@ fn a_question_moved_into_a_concurrently_deleted_section_is_left_out() {
required: false,
widget: None,
}],
+ show_when: None,
},
],
},
@@ -408,6 +423,7 @@ fn a_question_moved_into_a_concurrently_deleted_section_is_left_out() {
widget: None,
},
],
+ show_when: None,
}],
}
);
diff --git a/crates/forms/src/domain/collaboration/test/concurrent_edits.rs b/crates/forms/src/domain/collaboration/test/concurrent_edits.rs
index 19f6e96723..4170cf4948 100644
--- a/crates/forms/src/domain/collaboration/test/concurrent_edits.rs
+++ b/crates/forms/src/domain/collaboration/test/concurrent_edits.rs
@@ -34,12 +34,14 @@ fn concurrent_edits_of_different_fields_and_the_same_text_both_survive() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -76,12 +78,14 @@ fn concurrent_edits_of_different_fields_and_the_same_text_both_survive() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -123,12 +127,14 @@ fn concurrent_edits_of_different_fields_and_the_same_text_both_survive() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
}
@@ -176,12 +182,14 @@ fn questions_inserted_into_the_same_slot_both_survive() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -226,12 +234,14 @@ fn questions_inserted_into_the_same_slot_both_survive() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -280,6 +290,7 @@ fn a_question_moved_across_sections_keeps_a_concurrent_edit() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
@@ -292,6 +303,7 @@ fn a_question_moved_across_sections_keeps_a_concurrent_edit() {
required: false,
widget: None,
}],
+ show_when: None,
},
],
},
@@ -328,12 +340,14 @@ fn a_question_moved_across_sections_keeps_a_concurrent_edit() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -368,6 +382,7 @@ fn a_question_moved_across_sections_keeps_a_concurrent_edit() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
@@ -380,6 +395,7 @@ fn a_question_moved_across_sections_keeps_a_concurrent_edit() {
required: true,
widget: None,
}],
+ show_when: None,
},
],
}
@@ -420,12 +436,14 @@ fn a_question_reordered_within_its_section_keeps_a_concurrent_edit() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -462,12 +480,14 @@ fn a_question_reordered_within_its_section_keeps_a_concurrent_edit() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -509,12 +529,14 @@ fn a_question_reordered_within_its_section_keeps_a_concurrent_edit() {
widget: Some(Widget::Paragraph),
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
}
@@ -553,12 +575,14 @@ fn the_same_reorder_made_twice_concurrently_moves_rather_than_duplicates() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
};
diff --git a/crates/forms/src/domain/collaboration/test/reading.rs b/crates/forms/src/domain/collaboration/test/reading.rs
index 2ba78d6139..40d2567d12 100644
--- a/crates/forms/src/domain/collaboration/test/reading.rs
+++ b/crates/forms/src/domain/collaboration/test/reading.rs
@@ -65,6 +65,7 @@ fn reading_refuses_an_update_missing_its_history() {
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
}],
},
)
@@ -236,6 +237,7 @@ fn a_newer_revision_includes_an_older_one() {
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
}],
},
)
@@ -260,6 +262,7 @@ fn concurrent_revisions_include_neither_other() {
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
}],
},
)
@@ -273,12 +276,14 @@ fn concurrent_revisions_include_neither_other() {
title: "Contact".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "More".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
diff --git a/crates/forms/src/domain/collaboration/test/replacement_repair.rs b/crates/forms/src/domain/collaboration/test/replacement_repair.rs
index 1ce63883cd..e56decbc90 100644
--- a/crates/forms/src/domain/collaboration/test/replacement_repair.rs
+++ b/crates/forms/src/domain/collaboration/test/replacement_repair.rs
@@ -49,12 +49,14 @@ fn repaired_layout() -> FormLayout {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "More details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
}
diff --git a/crates/forms/src/domain/collaboration/test/seeding.rs b/crates/forms/src/domain/collaboration/test/seeding.rs
index 7c1ffa63a1..dcd38d1a57 100644
--- a/crates/forms/src/domain/collaboration/test/seeding.rs
+++ b/crates/forms/src/domain/collaboration/test/seeding.rs
@@ -95,12 +95,14 @@ fn seeding_refuses_a_section_named_twice() {
title: "Contact".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
FormSection::Questions {
id: CONTACT,
title: "Again".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
};
@@ -125,6 +127,7 @@ fn seeding_refuses_a_question_named_twice() {
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
@@ -137,6 +140,7 @@ fn seeding_refuses_a_question_named_twice() {
required: false,
widget: None,
}],
+ show_when: None,
},
],
};
@@ -179,12 +183,14 @@ fn replacing_writes_only_what_changed() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
};
@@ -270,12 +276,14 @@ fn replacing_keeps_section_fields_the_layout_does_not_model() {
widget: None,
},
],
+ show_when: None,
},
FormSection::Questions {
id: DETAILS,
title: "Details".to_owned(),
description: String::new(),
questions: vec![],
+ show_when: None,
},
],
},
@@ -350,3 +358,84 @@ fn texts_and_movable_lists_are_the_container_types() {
};
let _: (LoroText, LoroMovableList) = (help_text, document.get_movable_list("sectionOrder"));
}
+
+#[test]
+fn show_when_rules_survive_seeding_merge_with_a_concurrent_rename_and_clear_by_key() {
+ let shown_after_contact = FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: NAME_COLUMN,
+ test: FilterTest::Text {
+ operator: TextOperator::Is,
+ value: "Ada".to_owned(),
+ },
+ })],
+ };
+ let branching = FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: CONTACT,
+ title: "Contact".to_owned(),
+ description: String::new(),
+ questions: vec![QuestionLayout {
+ id: NAME,
+ column: NAME_COLUMN,
+ help_text: String::new(),
+ required: true,
+ widget: None,
+ }],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: DETAILS,
+ title: "Details".to_owned(),
+ description: String::new(),
+ questions: vec![],
+ show_when: Some(shown_after_contact.clone()),
+ },
+ ],
+ };
+ let snapshot = seed_layout(&branching).unwrap();
+ assert_eq!(read_layout(&snapshot).unwrap().layout, branching);
+
+ // One editor renames the section while another clears its rules.
+ let mut renamed = branching.clone();
+ let FormSection::Questions { title, .. } = &mut renamed.sections[1] else {
+ panic!("the second section asks questions");
+ };
+ *title = "More details".to_owned();
+ let mut always_shown = branching.clone();
+ let FormSection::Questions { show_when, .. } = &mut always_shown.sections[1] else {
+ panic!("the second section asks questions");
+ };
+ *show_when = None;
+ let rename = replace_layout(&snapshot, &renamed).unwrap();
+ let clear = replace_layout(&snapshot, &always_shown).unwrap();
+
+ let merged = merge(&snapshot, &[&rename.update, &clear.update]);
+
+ assert_eq!(
+ merged,
+ FormLayout {
+ sections: vec![
+ branching.sections[0].clone(),
+ FormSection::Questions {
+ id: DETAILS,
+ title: "More details".to_owned(),
+ description: String::new(),
+ questions: vec![],
+ show_when: None,
+ },
+ ],
+ }
+ );
+ let cleared = LoroDoc::from_snapshot(&snapshot).unwrap();
+ cleared.import(&clear.update).unwrap();
+ let Some(loro::ValueOrContainer::Container(loro::Container::Map(details))) = cleared
+ .get_map("sections")
+ .get(&DETAILS.as_uuid().to_string())
+ else {
+ panic!("the section is not a map");
+ };
+ assert!(details.get("showWhen").is_none());
+}
diff --git a/crates/forms/src/domain/service/answers.rs b/crates/forms/src/domain/service/answers.rs
index 6994b95468..98307aba39 100644
--- a/crates/forms/src/domain/service/answers.rs
+++ b/crates/forms/src/domain/service/answers.rs
@@ -1,7 +1,8 @@
//! A submission's answers against a form's layout: shape and required
-//! checks, labels resolved to options, and the gates, walked in section
-//! order. The databases service stays the authority on whether a value fits
-//! its column; this checks only what the form must decide itself.
+//! checks, labels resolved to options, the sections skipped by their
+//! show-when rules, and the gates, walked in section order. The databases
+//! service stays the authority on whether a value fits its column; this
+//! checks only what the form must decide itself.
use std::collections::HashMap;
@@ -17,7 +18,7 @@ use crate::domain::models::{
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Evaluation {
/// Every gate passed: each question of the form in layout order, with
- /// its answer or `None` when unanswered.
+ /// its answer or `None` when unanswered or its section was skipped.
Passed(Vec<AnsweredQuestion>),
/// A gate stopped the respondent.
Stopped {
@@ -40,9 +41,14 @@ pub(super) struct AnsweredQuestion {
}
/// Check `answers` against `layout` over the table's `columns` and run the
-/// gates. Required questions are checked section by section up to the first
-/// gate that stops the respondent; sections after it are never reached, so
-/// their questions need no answers.
+/// gates, walking the sections in order. A questions section with show-when
+/// rules is shown only when the answers of earlier shown sections pass
+/// them; otherwise it is skipped: its questions need no answers, and
+/// answers given to them are ignored, neither checked nor written, so they
+/// count as unanswered. Gates and later rules see only shown sections'
+/// answers. Required questions are checked section by section up to the
+/// first gate that stops the respondent; sections after it are never
+/// reached, so their questions need no answers.
pub(super) fn evaluate(
layout: &FormLayout,
columns: &HashMap<ColumnId, QuestionColumn>,
@@ -61,15 +67,14 @@ pub(super) fn evaluate(
.map(|column| (question.id, column))
})
.collect();
- let mut given: HashMap<FormQuestionId, Option<CellValue>> = HashMap::new();
+ let mut given: HashMap<FormQuestionId, &CellValue> = HashMap::new();
for answer in answers {
- let column = asked
- .get(&answer.question)
- .ok_or(FormError::UnknownQuestion {
+ if !asked.contains_key(&answer.question) {
+ return Err(FormError::UnknownQuestion {
question: answer.question,
- })?;
- let value = normalized(answer.question, column, &answer.value)?;
- if given.insert(answer.question, value).is_some() {
+ });
+ }
+ if given.insert(answer.question, &answer.value).is_some() {
return Err(FormError::RepeatedAnswer {
question: answer.question,
});
@@ -81,13 +86,23 @@ pub(super) fn evaluate(
for section in &layout.sections {
match section {
FormSection::Booking { .. } => {}
- FormSection::Questions { questions, .. } => {
+ FormSection::Questions {
+ questions,
+ show_when,
+ ..
+ } => {
+ let shown = show_when
+ .as_ref()
+ .is_none_or(|rules| eval::matches(rules, &cells));
for question in questions {
- if !asked.contains_key(&question.id) {
+ let Some(column) = asked.get(&question.id) else {
continue;
- }
- let value = given.remove(&question.id).flatten();
- if question.required && value.is_none() {
+ };
+ let value = match given.get(&question.id) {
+ Some(value) if shown => normalized(question.id, column, value)?,
+ Some(_) | None => None,
+ };
+ if shown && question.required && value.is_none() {
return Err(FormError::MissingAnswer {
question: question.id,
});
diff --git a/crates/forms/src/domain/service/create.rs b/crates/forms/src/domain/service/create.rs
index 6c71aedd46..580ef07f26 100644
--- a/crates/forms/src/domain/service/create.rs
+++ b/crates/forms/src/domain/service/create.rs
@@ -330,6 +330,7 @@ where
title: String::new(),
description: String::new(),
questions: vec![],
+ show_when: None,
}],
};
self.store_new_form(
@@ -436,6 +437,7 @@ where
title: String::new(),
description: String::new(),
questions,
+ show_when: None,
}],
};
self.store_new_form(
diff --git a/crates/forms/src/domain/service/layout.rs b/crates/forms/src/domain/service/layout.rs
index 0439240985..cb9dcec40e 100644
--- a/crates/forms/src/domain/service/layout.rs
+++ b/crates/forms/src/domain/service/layout.rs
@@ -106,6 +106,7 @@ pub(super) fn form_detail(
title,
description,
questions,
+ show_when,
} => FormSectionDetail::Questions {
id,
title,
@@ -126,6 +127,7 @@ pub(super) fn form_detail(
})
})
.collect(),
+ show_when,
},
FormSection::Gate {
id,
@@ -152,9 +154,9 @@ pub(super) fn form_detail(
/// Check a layout against the form's table as a whole: every column is the
/// table's, asked once and not written by the form itself; every widget fits
-/// its column and a public form asks for no file; every gate tests only
-/// columns asked before it, as a view filter would test them; ids are
-/// unique and texts within bounds.
+/// its column and a public form asks for no file; every gate and every
+/// section's show-when rules test only columns asked before it, as a view
+/// filter would test them; ids are unique and texts within bounds.
pub(super) fn validate_layout(
layout: &FormLayout,
form: &Form,
@@ -194,10 +196,14 @@ pub(super) fn validate_layout(
title,
description,
questions,
+ show_when,
} => {
unique(*id.as_uuid())?;
within(title, MAX_TITLE_LENGTH)?;
within(description, MAX_TEXT_LENGTH)?;
+ if let Some(rules) = show_when {
+ condition_fits(rules, &asked, &columns)?;
+ }
for question in questions {
unique(*question.id.as_uuid())?;
within(&question.help_text, MAX_TEXT_LENGTH)?;
@@ -213,7 +219,7 @@ pub(super) fn validate_layout(
.ok_or(LayoutProblem::UnknownColumn {
column: question.column,
})?;
- // A gate only reads `asked` at its own section, so a
+ // Rules read `asked` only at a section's start, so a
// column is asked from here on as soon as it is seen.
if !asked.insert(question.column) {
return Err(LayoutProblem::RepeatedColumn {
@@ -282,13 +288,41 @@ fn gate_fits(
asked: &HashSet<ColumnId>,
columns: &HashMap<ColumnId, QuestionColumn>,
) -> Result<(), LayoutProblem> {
- for condition in rules.conditions() {
- if !asked.contains(&condition.column) {
- return Err(LayoutProblem::GateNamesLaterColumn {
- column: condition.column,
- });
- }
+ if let Some(column) = later_column(rules, asked) {
+ return Err(LayoutProblem::GateNamesLaterColumn { column });
}
+ rules_fit(rules, asked, columns).map_err(|reason| LayoutProblem::GateRule { reason })
+}
+
+/// Check a section's show-when rules against the columns asked before it,
+/// as a gate's are checked.
+fn condition_fits(
+ rules: &FilterGroup,
+ asked: &HashSet<ColumnId>,
+ columns: &HashMap<ColumnId, QuestionColumn>,
+) -> Result<(), LayoutProblem> {
+ if let Some(column) = later_column(rules, asked) {
+ return Err(LayoutProblem::ConditionNamesLaterColumn { column });
+ }
+ rules_fit(rules, asked, columns).map_err(|reason| LayoutProblem::ConditionRule { reason })
+}
+
+/// The first column `rules` test that is not among `asked`.
+fn later_column(rules: &FilterGroup, asked: &HashSet<ColumnId>) -> Option<ColumnId> {
+ rules
+ .conditions()
+ .into_iter()
+ .map(|condition| condition.column)
+ .find(|column| !asked.contains(column))
+}
+
+/// Whether each test of `rules` fits its column, among those `asked`, as a
+/// view filter's would; why not, when one does not.
+fn rules_fit(
+ rules: &FilterGroup,
+ asked: &HashSet<ColumnId>,
+ columns: &HashMap<ColumnId, QuestionColumn>,
+) -> Result<(), String> {
let earlier: Vec<SchemaColumn> = asked
.iter()
.filter_map(|column| columns.get(column))
@@ -302,15 +336,14 @@ fn gate_fits(
&ViewLayout::Table { columns: vec![] },
&earlier,
)
- .map_err(|problem| LayoutProblem::GateRule {
- reason: problem.to_string(),
- })
+ .map_err(|problem| problem.to_string())
}
-/// Check a stored layout's gates against the table as it is now: a column
-/// deleted or retyped in the grid can leave a gate naming a question the
-/// form no longer asks, or testing a column as it no longer is. Such a gate
-/// would stop every respondent, so responding is refused instead until an
+/// Check a stored layout's gates and show-when rules against the table as
+/// it is now: a column deleted or retyped in the grid can leave rules naming
+/// a question the form no longer asks, or testing a column as it no longer
+/// is. Such a gate would stop every respondent, and such a section would be
+/// skipped for all of them, so responding is refused instead until an
/// editor repairs the layout.
pub(super) fn gates_fit_table(
layout: &FormLayout,
@@ -320,12 +353,21 @@ pub(super) fn gates_fit_table(
for section in &layout.sections {
match section {
FormSection::Booking { .. } => {}
- FormSection::Questions { questions, .. } => asked.extend(
- questions
- .iter()
- .map(|question| question.column)
- .filter(|column| columns.contains_key(column)),
- ),
+ FormSection::Questions {
+ questions,
+ show_when,
+ ..
+ } => {
+ if let Some(rules) = show_when {
+ condition_fits(rules, &asked, columns)?;
+ }
+ asked.extend(
+ questions
+ .iter()
+ .map(|question| question.column)
+ .filter(|column| columns.contains_key(column)),
+ );
+ }
FormSection::Gate { rules, .. } => gate_fits(rules, &asked, columns)?,
}
}
diff --git a/crates/forms/src/domain/service/submit.rs b/crates/forms/src/domain/service/submit.rs
index 006a441261..26f728d964 100644
--- a/crates/forms/src/domain/service/submit.rs
+++ b/crates/forms/src/domain/service/submit.rs
@@ -164,7 +164,7 @@ fn unlocked_booking(layout: &FormLayout) -> Option<UnlockedBooking> {
}
/// Whether a saved row's answers pass the form as it is now: every required
-/// question answered and every gate passed.
+/// question of a shown section answered and every gate passed.
fn still_passes(
layout: &FormLayout,
columns: &HashMap<ColumnId, QuestionColumn>,
diff --git a/crates/forms/src/domain/service/test.rs b/crates/forms/src/domain/service/test.rs
index 4efe2f9a58..b5a8ef9159 100644
--- a/crates/forms/src/domain/service/test.rs
+++ b/crates/forms/src/domain/service/test.rs
@@ -25,8 +25,10 @@ use crate::domain::models::{
};
mod anonymous;
+mod authoring_branching;
mod authoring_workflow;
mod booking;
+mod branching;
mod catalog;
mod create;
mod drafts;
@@ -193,6 +195,7 @@ fn rsvp_layout() -> FormLayout {
widget: Some(Widget::Date),
},
],
+ show_when: None,
},
FormSection::Gate {
id: ELIGIBILITY,
@@ -230,6 +233,7 @@ fn rsvp_layout() -> FormLayout {
widget: None,
},
],
+ show_when: None,
},
],
}
diff --git a/crates/forms/src/domain/service/test/authoring_branching.rs b/crates/forms/src/domain/service/test/authoring_branching.rs
new file mode 100644
index 0000000000..8a0ef22857
--- /dev/null
+++ b/crates/forms/src/domain/service/test/authoring_branching.rs
@@ -0,0 +1,176 @@
+//! AI authoring of branching: a created section's show-when rules name
+//! earlier questions by key, a read returns them, and edits that do not
+//! mention them keep them.
+use super::authoring_workflow::{Access, Editor};
+use super::*;
+use crate::domain::authoring::ports::FormsAuthoringService;
+use crate::domain::authoring::workflow::AuthoringWorkflow;
+use crate::domain::authoring::*;
+use serde_json::json;
+
+#[tokio::test]
+async fn a_created_show_when_reads_back_and_survives_an_edit_that_does_not_mention_it() {
+ let world = world();
+ let workflow = AuthoringWorkflow {
+ core: Arc::new(service(&world)),
+ databases: Arc::new(FakeDatabases(world.clone())),
+ booking: (),
+ access: Access(world.clone()),
+ editor: Editor,
+ app_origin: "https://macro.test".into(),
+ };
+ let intent: Create = serde_json::from_value(json!({
+ "name": "Offsite", "source": {"kind":"new"},
+ "draft": {"sections":[
+ {"kind":"questions","key":"about","questions":[
+ {"key":"role","column":{"kind":"new","name":"Role","type":{"type":"select","multi":false},"options":[
+ {"key":"employee","label":"Employee"},{"key":"contractor","label":"Contractor"}]},"required":true}
+ ]},
+ {"kind":"questions","key":"logistics","title":"Logistics","questions":[
+ {"key":"diet","column":{"kind":"new","name":"Diet","type":{"type":"text"}},"required":true}
+ ],"showWhen":{"conjunction":"and","conditions":[
+ {"kind":"condition","question":{"key":"role"},"test":{"kind":"options","operator":"isAnyOf","options":[{"key":"employee"}]}}
+ ]}}
+ ]}
+ }))
+ .unwrap();
+
+ let created = workflow.create_form(viewer(OWNER), intent).await.unwrap();
+
+ assert_eq!(
+ created.state,
+ MutationState::Completed,
+ "{:?}",
+ created.diagnostics
+ );
+ let form_id = created.form_id;
+ let logistics = created.keys.sections["logistics"];
+ let expected = FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: created.keys.columns["role"],
+ test: FilterTest::Options {
+ operator: SetOperator::IsAnyOf,
+ options: vec![created.keys.options["role"]["employee"]],
+ },
+ })],
+ };
+ let ReadResult::Authoring { saved, .. } = workflow
+ .read_form(
+ viewer(OWNER),
+ Read {
+ form_id,
+ view: ReadView::Authoring,
+ include_summary: false,
+ },
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("authoring");
+ };
+ let FormSection::Questions { show_when, .. } = &saved.layout.sections[1] else {
+ panic!("questions");
+ };
+ assert_eq!(show_when, &Some(expected.clone()));
+
+ let renamed = workflow
+ .edit_form(
+ viewer(OWNER),
+ Edit {
+ form_id,
+ changes: vec![Change::SetSectionText {
+ section_id: logistics,
+ title: Some("Travel".into()),
+ description: None,
+ message: None,
+ }],
+ new_columns: vec![],
+ description: None,
+ confirmation_message: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ renamed.state,
+ MutationState::Completed,
+ "{:?}",
+ renamed.diagnostics
+ );
+ let FormSection::Questions {
+ title, show_when, ..
+ } = &renamed.saved.as_ref().unwrap().layout.sections[1]
+ else {
+ panic!("questions");
+ };
+ assert_eq!(title, "Travel");
+ assert_eq!(show_when, &Some(expected));
+
+ let cleared = workflow
+ .edit_form(
+ viewer(OWNER),
+ Edit {
+ form_id,
+ changes: vec![Change::SetShowWhen {
+ section_id: logistics,
+ show_when: None,
+ }],
+ new_columns: vec![],
+ description: None,
+ confirmation_message: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let FormSection::Questions { show_when, .. } =
+ &cleared.saved.as_ref().unwrap().layout.sections[1]
+ else {
+ panic!("questions");
+ };
+ assert_eq!(show_when, &None);
+}
+
+#[tokio::test]
+async fn an_edit_naming_the_sections_own_question_in_show_when_is_refused_before_any_write() {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ let workflow = AuthoringWorkflow {
+ core: Arc::new(service(&world)),
+ databases: Arc::new(FakeDatabases(world.clone())),
+ booking: (),
+ access: Access(world.clone()),
+ editor: Editor,
+ app_origin: "https://macro.test".into(),
+ };
+
+ let refused = workflow
+ .edit_form(
+ viewer(OWNER),
+ Edit {
+ form_id: RSVP_FORM,
+ changes: vec![Change::SetShowWhen {
+ section_id: LOGISTICS,
+ show_when: Some(FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: DIET,
+ test: FilterTest::Presence {
+ operator: models_databases::views::PresenceOperator::IsEmpty,
+ },
+ })],
+ }),
+ }],
+ new_columns: vec![],
+ description: None,
+ confirmation_message: None,
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(refused.code, Code::ShowWhenReferencesLaterQuestion);
+ assert_eq!(world.lock().unwrap().layouts[&RSVP_FORM], rsvp_layout());
+}
diff --git a/crates/forms/src/domain/service/test/authoring_workflow.rs b/crates/forms/src/domain/service/test/authoring_workflow.rs
index 87f637a030..001cd6852b 100644
--- a/crates/forms/src/domain/service/test/authoring_workflow.rs
+++ b/crates/forms/src/domain/service/test/authoring_workflow.rs
@@ -8,7 +8,7 @@ use crate::domain::authoring::{
use crate::domain::collaboration;
use serde_json::json;
-struct Access(Shared);
+pub(super) struct Access(pub(super) Shared);
impl AuthoringAccess for Access {
async fn receipt<L: RequiredPermission>(
&self,
@@ -743,6 +743,7 @@ async fn review_regression_metadata_edit_preserves_human_reference_questions_and
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Gate {
id: FormSectionId::new(),
@@ -833,6 +834,7 @@ async fn review_regression_sharing_preserves_human_reference_questions_and_empty
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Gate {
id: FormSectionId::new(),
@@ -1240,7 +1242,7 @@ async fn crdt_merge_refuses_to_strand_a_concurrently_added_screening_rule() {
}
/// Test codec; production uses the Cloudflare worker through the same port.
-struct Editor;
+pub(super) struct Editor;
impl crate::domain::authoring::ports::AuthoringEditor for Editor {
async fn prepare_edit(
&self,
@@ -1284,6 +1286,7 @@ async fn crdt_merge_revalidates_authoring_limits_after_a_concurrent_addition() {
title: String::new(),
description: String::new(),
questions: vec![],
+ show_when: None,
};
let mut human = saved.layout.clone();
human.sections.push(section());
diff --git a/crates/forms/src/domain/service/test/booking.rs b/crates/forms/src/domain/service/test/booking.rs
index 4ff3f187e7..e5489c8d6a 100644
--- a/crates/forms/src/domain/service/test/booking.rs
+++ b/crates/forms/src/domain/service/test/booking.rs
@@ -162,6 +162,7 @@ async fn an_accepted_response_unlocks_the_booking_step_and_a_stopped_one_never_s
widget: Some(Widget::Date),
},
],
+ show_when: None,
},
FormSection::Gate {
id: ELIGIBILITY,
diff --git a/crates/forms/src/domain/service/test/branching.rs b/crates/forms/src/domain/service/test/branching.rs
new file mode 100644
index 0000000000..fe414b5ecd
--- /dev/null
+++ b/crates/forms/src/domain/service/test/branching.rs
@@ -0,0 +1,512 @@
+//! Branching: a questions section shown only when earlier answers pass its
+//! show-when rules. A skipped section asks nothing: its required questions
+//! need no answer, answers sent for it are neither checked nor written, and
+//! later gates and rules never see them.
+
+use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
+use models_databases::views::{PresenceOperator, TextOperator};
+use models_databases::{
+ CellValue, CellWrite, DatabaseOp, EntityKind, EntityRef, OptionRef, RowChange, RowChanges,
+ RowsChange,
+};
+
+use super::*;
+use crate::domain::models::{
+ Answer, FormError, FormSectionDetail, LayoutProblem, Submission, SubmissionOutcome,
+};
+use crate::domain::ports::FormsService;
+
+const PLUS_ONES_FULL: &str = "Plus ones are full.";
+
+/// About you (Team and Start date, required); Logistics, shown only to
+/// employees (Diet required, Plus one optional); then a gate stopping
+/// anyone bringing a plus one.
+fn branching_layout() -> FormLayout {
+ FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: ABOUT_YOU,
+ title: "About you".into(),
+ description: "".into(),
+ questions: vec![
+ QuestionLayout {
+ id: TEAM_QUESTION,
+ column: TEAM,
+ help_text: "".into(),
+ required: true,
+ widget: None,
+ },
+ QuestionLayout {
+ id: START_QUESTION,
+ column: START_DATE,
+ help_text: "".into(),
+ required: true,
+ widget: None,
+ },
+ ],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: LOGISTICS,
+ title: "Logistics".into(),
+ description: "".into(),
+ questions: vec![
+ QuestionLayout {
+ id: DIET_QUESTION,
+ column: DIET,
+ help_text: "".into(),
+ required: true,
+ widget: None,
+ },
+ QuestionLayout {
+ id: PLUS_ONE_QUESTION,
+ column: PLUS_ONE,
+ help_text: "".into(),
+ required: false,
+ widget: None,
+ },
+ ],
+ show_when: Some(FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: TEAM,
+ test: FilterTest::Options {
+ operator: SetOperator::IsAnyOf,
+ options: vec![EMPLOYEE],
+ },
+ })],
+ }),
+ },
+ FormSection::Gate {
+ id: ELIGIBILITY,
+ title: "Plus ones".into(),
+ description: "".into(),
+ rules: FilterGroup {
+ conjunction: Conjunction::Or,
+ conditions: vec![
+ FilterNode::Condition(FilterCondition {
+ column: PLUS_ONE,
+ test: FilterTest::Presence {
+ operator: PresenceOperator::IsEmpty,
+ },
+ }),
+ FilterNode::Condition(FilterCondition {
+ column: PLUS_ONE,
+ test: FilterTest::Checkbox { checked: false },
+ }),
+ ],
+ },
+ message: PLUS_ONES_FULL.into(),
+ },
+ ],
+ }
+}
+
+fn seed_branching(world: &Shared) {
+ seed_rsvp(world, Audience::Members);
+ world
+ .lock()
+ .unwrap()
+ .layouts
+ .insert(RSVP_FORM, branching_layout());
+}
+
+async fn submit_as(
+ world: &Shared,
+ user: &'static str,
+ answers: Vec<Answer>,
+) -> Result<SubmissionOutcome, FormError> {
+ service(world)
+ .submit_response(
+ form_receipt::<ViewAccessLevel>(RSVP_FORM, user, AccessLevel::View),
+ Submission { answers },
+ )
+ .await
+}
+
+#[tokio::test]
+async fn a_skipped_section_needs_no_answers_and_its_answers_are_neither_checked_written_nor_gated()
+{
+ let world = world();
+ seed_branching(&world);
+
+ // A contractor skips Logistics: Diet, required there, is unanswered; a
+ // number sent for the text Diet is not refused; and the checked Plus
+ // one is not seen by the gate, so it does not stop them.
+ let outcome = submit_as(
+ &world,
+ VIEWER,
+ vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(CONTRACTOR)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ Answer {
+ question: DIET_QUESTION,
+ value: CellValue::Number(3.0),
+ },
+ Answer {
+ question: PLUS_ONE_QUESTION,
+ value: CellValue::Boolean(true),
+ },
+ ],
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(outcome, SubmissionOutcome::Submitted { .. }));
+ let world = world.lock().unwrap();
+ assert_eq!(
+ world.batches[0].ops,
+ vec![DatabaseOp::Rows {
+ table: RSVP_TABLE,
+ change: RowsChange::Insert {
+ rows: vec![vec![
+ CellWrite {
+ column: TEAM,
+ value: CellValue::Options(vec![OptionRef::Id(CONTRACTOR)]),
+ },
+ CellWrite {
+ column: START_DATE,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ CellWrite {
+ column: SUBMITTED,
+ value: CellValue::Date(start_of_tests()),
+ },
+ CellWrite {
+ column: RESPONDENT,
+ value: CellValue::Entities(vec![EntityRef {
+ entity_type: EntityKind::User,
+ entity_id: VIEWER.into(),
+ }]),
+ },
+ ]],
+ },
+ }]
+ );
+}
+
+#[tokio::test]
+async fn a_shown_section_asks_its_questions_and_later_gates_see_its_answers() {
+ let world = world();
+ seed_branching(&world);
+ let employee = |diet: Option<&str>, plus_one: bool| {
+ let mut answers = vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(EMPLOYEE)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ Answer {
+ question: PLUS_ONE_QUESTION,
+ value: CellValue::Boolean(plus_one),
+ },
+ ];
+ if let Some(diet) = diet {
+ answers.push(Answer {
+ question: DIET_QUESTION,
+ value: CellValue::Text(diet.into()),
+ });
+ }
+ answers
+ };
+
+ // An employee is shown Logistics, so its required Diet must be answered.
+ assert!(matches!(
+ submit_as(&world, VIEWER, employee(None, false)).await,
+ Err(FormError::MissingAnswer {
+ question: DIET_QUESTION
+ })
+ ));
+ // Its Plus one is seen by the gate.
+ assert_eq!(
+ submit_as(&world, VIEWER, employee(Some("Vegan"), true))
+ .await
+ .unwrap(),
+ SubmissionOutcome::Stopped {
+ section: ELIGIBILITY,
+ message: PLUS_ONES_FULL.into(),
+ }
+ );
+ let outcome = submit_as(&world, VIEWER, employee(Some("Vegan"), false))
+ .await
+ .unwrap();
+
+ assert!(matches!(outcome, SubmissionOutcome::Submitted { .. }));
+ let world = world.lock().unwrap();
+ assert_eq!(
+ world.batches[0].ops,
+ vec![DatabaseOp::Rows {
+ table: RSVP_TABLE,
+ change: RowsChange::Insert {
+ rows: vec![vec![
+ CellWrite {
+ column: TEAM,
+ value: CellValue::Options(vec![OptionRef::Id(EMPLOYEE)]),
+ },
+ CellWrite {
+ column: START_DATE,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ CellWrite {
+ column: DIET,
+ value: CellValue::Text("Vegan".into()),
+ },
+ CellWrite {
+ column: PLUS_ONE,
+ value: CellValue::Boolean(false),
+ },
+ CellWrite {
+ column: SUBMITTED,
+ value: CellValue::Date(start_of_tests()),
+ },
+ CellWrite {
+ column: RESPONDENT,
+ value: CellValue::Entities(vec![EntityRef {
+ entity_type: EntityKind::User,
+ entity_id: VIEWER.into(),
+ }]),
+ },
+ ]],
+ },
+ }]
+ );
+}
+
+#[tokio::test]
+async fn an_edit_that_skips_a_section_clears_its_saved_answers() {
+ let world = world();
+ seed_branching(&world);
+ let SubmissionOutcome::Submitted { row, .. } = submit_as(
+ &world,
+ VIEWER,
+ vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(EMPLOYEE)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ Answer {
+ question: DIET_QUESTION,
+ value: CellValue::Text("Vegan".into()),
+ },
+ ],
+ )
+ .await
+ .unwrap() else {
+ panic!("the first response is saved");
+ };
+
+ // Now a contractor: Logistics is skipped, so Diet is cleared even
+ // though the page sent it again.
+ service(&world)
+ .edit_my_response(
+ form_receipt::<ViewAccessLevel>(RSVP_FORM, VIEWER, AccessLevel::View),
+ Submission {
+ answers: vec![
+ Answer {
+ question: TEAM_QUESTION,
+ value: CellValue::Options(vec![OptionRef::Id(CONTRACTOR)]),
+ },
+ Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ },
+ Answer {
+ question: DIET_QUESTION,
+ value: CellValue::Text("Vegan".into()),
+ },
+ ],
+ },
+ )
+ .await
+ .unwrap();
+
+ let world = world.lock().unwrap();
+ assert_eq!(
+ world.batches[1].ops,
+ vec![DatabaseOp::Rows {
+ table: RSVP_TABLE,
+ change: RowsChange::Update {
+ changes: RowChanges::PerRow {
+ rows: vec![RowChange {
+ row,
+ cells: vec![
+ CellWrite {
+ column: TEAM,
+ value: CellValue::Options(vec![OptionRef::Id(CONTRACTOR)]),
+ },
+ CellWrite {
+ column: START_DATE,
+ value: CellValue::Date(
+ Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()
+ ),
+ },
+ CellWrite {
+ column: DIET,
+ value: CellValue::Clear,
+ },
+ CellWrite {
+ column: PLUS_ONE,
+ value: CellValue::Clear,
+ },
+ ],
+ }],
+ },
+ },
+ }]
+ );
+}
+
+#[tokio::test]
+async fn show_when_rules_may_test_only_columns_of_earlier_sections_as_a_view_filter_would() {
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ let shown_when = |column: ColumnId, test: FilterTest| FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: ABOUT_YOU,
+ title: "".into(),
+ description: "".into(),
+ questions: vec![QuestionLayout {
+ id: TEAM_QUESTION,
+ column: TEAM,
+ help_text: "".into(),
+ required: false,
+ widget: None,
+ }],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: LOGISTICS,
+ title: "".into(),
+ description: "".into(),
+ questions: vec![QuestionLayout {
+ id: DIET_QUESTION,
+ column: DIET,
+ help_text: "".into(),
+ required: false,
+ widget: None,
+ }],
+ show_when: Some(FilterGroup {
+ conjunction: Conjunction::And,
+ conditions: vec![FilterNode::Condition(FilterCondition { column, test })],
+ }),
+ },
+ ],
+ };
+ let put = |layout: FormLayout| {
+ let forms = service(&world);
+ async move {
+ forms
+ .put_layout(
+ form_receipt::<EditAccessLevel>(RSVP_FORM, EDITOR, AccessLevel::Edit),
+ layout,
+ )
+ .await
+ }
+ };
+
+ // Diet is the section's own question.
+ assert!(matches!(
+ put(shown_when(
+ DIET,
+ FilterTest::Text {
+ operator: TextOperator::Contains,
+ value: "vegan".into(),
+ }
+ ))
+ .await,
+ Err(FormError::InvalidLayout(
+ LayoutProblem::ConditionNamesLaterColumn { column: DIET }
+ ))
+ ));
+ // Notes is never asked.
+ assert!(matches!(
+ put(shown_when(
+ NOTES,
+ FilterTest::Text {
+ operator: TextOperator::Contains,
+ value: "x".into(),
+ }
+ ))
+ .await,
+ Err(FormError::InvalidLayout(
+ LayoutProblem::ConditionNamesLaterColumn { column: NOTES }
+ ))
+ ));
+ // A text test does not fit a select column.
+ assert!(matches!(
+ put(shown_when(
+ TEAM,
+ FilterTest::Text {
+ operator: TextOperator::Is,
+ value: "Employee".into(),
+ }
+ ))
+ .await,
+ Err(FormError::InvalidLayout(
+ LayoutProblem::ConditionRule { .. }
+ ))
+ ));
+ let fits = shown_when(
+ TEAM,
+ FilterTest::Options {
+ operator: SetOperator::IsAnyOf,
+ options: vec![EMPLOYEE],
+ },
+ );
+ let saved = put(fits.clone()).await.unwrap();
+
+ let FormSection::Questions {
+ show_when: expected,
+ ..
+ } = &fits.sections[1]
+ else {
+ panic!("the second section asks questions");
+ };
+ let FormSectionDetail::Questions { show_when, .. } = &saved.detail.sections[1] else {
+ panic!("the second section asks questions");
+ };
+ assert_eq!(show_when, expected);
+ assert_eq!(world.lock().unwrap().layouts[&RSVP_FORM], fits);
+}
+
+#[tokio::test]
+async fn a_show_when_rule_on_a_deleted_column_refuses_responses_before_any_write() {
+ let world = world();
+ seed_branching(&world);
+ // The gate tests Plus one, not Team; only the show-when rule breaks.
+ world.lock().unwrap().database_mut(RSVP_DATABASE).tables[0]
+ .columns
+ .retain(|column| column.id != TEAM);
+
+ let refused = submit_as(
+ &world,
+ VIEWER,
+ vec![Answer {
+ question: START_QUESTION,
+ value: CellValue::Date(Utc.with_ymd_and_hms(2026, 8, 17, 0, 0, 0).unwrap()),
+ }],
+ )
+ .await;
+
+ assert!(matches!(
+ refused,
+ Err(FormError::InvalidLayout(
+ LayoutProblem::ConditionNamesLaterColumn { column: TEAM }
+ ))
+ ));
+ assert!(world.lock().unwrap().batches.is_empty());
+}
diff --git a/crates/forms/src/domain/service/test/create.rs b/crates/forms/src/domain/service/test/create.rs
index ae76fdfec2..275e10eb97 100644
--- a/crates/forms/src/domain/service/test/create.rs
+++ b/crates/forms/src/domain/service/test/create.rs
@@ -136,6 +136,7 @@ async fn a_form_over_a_table_asks_every_column_and_adds_the_managed_ones() {
widget: Some(Widget::Choice),
},
],
+ show_when: None,
}],
}
);
diff --git a/crates/forms/src/domain/service/test/drafts.rs b/crates/forms/src/domain/service/test/drafts.rs
index f78271e2a7..453eec693e 100644
--- a/crates/forms/src/domain/service/test/drafts.rs
+++ b/crates/forms/src/domain/service/test/drafts.rs
@@ -83,6 +83,7 @@ async fn the_builder_initializes_an_editor_only_durable_layout() {
required: true,
widget: None,
}],
+ show_when: None,
}],
};
world
diff --git a/crates/forms/src/domain/service/test/end_to_end.rs b/crates/forms/src/domain/service/test/end_to_end.rs
index a43332d8cd..30fb787505 100644
--- a/crates/forms/src/domain/service/test/end_to_end.rs
+++ b/crates/forms/src/domain/service/test/end_to_end.rs
@@ -95,6 +95,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
title: "".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
}
);
@@ -273,6 +274,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
widget: Some(Widget::Date),
},
],
+ show_when: None,
},
FormSection::Gate {
id: ELIGIBILITY,
@@ -311,6 +313,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
required: false,
widget: Some(Widget::Paragraph),
}],
+ show_when: None,
},
],
},
@@ -357,6 +360,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
widget: Some(Widget::Date),
},
],
+ show_when: None,
},
FormSectionDetail::Gate {
id: ELIGIBILITY,
@@ -397,6 +401,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
required: false,
widget: Some(Widget::Paragraph),
}],
+ show_when: None,
},
]
);
diff --git a/crates/forms/src/domain/service/test/layout.rs b/crates/forms/src/domain/service/test/layout.rs
index 78444715da..ac9476d1f9 100644
--- a/crates/forms/src/domain/service/test/layout.rs
+++ b/crates/forms/src/domain/service/test/layout.rs
@@ -94,6 +94,7 @@ fn with_questions(questions: Vec<QuestionLayout>) -> FormLayout {
title: "".into(),
description: "".into(),
questions,
+ show_when: None,
}],
}
}
@@ -261,6 +262,7 @@ async fn a_layout_asking_a_column_twice_or_reusing_an_id_is_refused() {
title: "".into(),
description: "".into(),
questions: vec![question(7, TEAM, None)],
+ show_when: None,
}],
};
assert!(matches!(
@@ -332,6 +334,7 @@ async fn a_gate_may_test_only_columns_asked_before_it_as_a_view_filter_would() {
title: "".into(),
description: "".into(),
questions: vec![question(1, TEAM, None), question(2, START_DATE, None)],
+ show_when: None,
},
FormSection::Gate {
id: ELIGIBILITY,
@@ -348,6 +351,7 @@ async fn a_gate_may_test_only_columns_asked_before_it_as_a_view_filter_would() {
title: "".into(),
description: "".into(),
questions: vec![question(3, DIET, None)],
+ show_when: None,
},
],
};
@@ -440,6 +444,7 @@ async fn texts_longer_than_allowed_are_refused() {
title: "x".repeat(201),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
};
assert!(matches!(
diff --git a/crates/forms/src/domain/service/test/liveness.rs b/crates/forms/src/domain/service/test/liveness.rs
index 16ef89ea37..32fd1bc5e0 100644
--- a/crates/forms/src/domain/service/test/liveness.rs
+++ b/crates/forms/src/domain/service/test/liveness.rs
@@ -111,6 +111,7 @@ async fn refused_changes_and_no_op_lifecycle_calls_ping_nobody() {
required: false,
widget: None,
}],
+ show_when: None,
}],
},
)
diff --git a/crates/forms/src/domain/service/test/names.rs b/crates/forms/src/domain/service/test/names.rs
index 4e3c83cfdc..f7938876a4 100644
--- a/crates/forms/src/domain/service/test/names.rs
+++ b/crates/forms/src/domain/service/test/names.rs
@@ -358,6 +358,7 @@ async fn renaming_the_database_renames_its_form_wherever_the_form_is_read() {
title: "".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
},
)
diff --git a/crates/forms/src/domain/service/test/races.rs b/crates/forms/src/domain/service/test/races.rs
index ef7bfa2045..08d9a9bd06 100644
--- a/crates/forms/src/domain/service/test/races.rs
+++ b/crates/forms/src/domain/service/test/races.rs
@@ -36,6 +36,7 @@ fn asking_for_a_file() -> FormLayout {
required: false,
widget: Some(Widget::File),
}],
+ show_when: None,
}],
}
}
@@ -140,6 +141,7 @@ async fn a_layout_reusing_another_forms_id_is_a_repeated_id_and_the_old_layout_s
title: "Someone else's".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
},
);
@@ -153,6 +155,7 @@ async fn a_layout_reusing_another_forms_id_is_a_repeated_id_and_the_old_layout_s
title: "Mine".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
},
)
diff --git a/crates/forms/src/domain/service/test/schema_changes.rs b/crates/forms/src/domain/service/test/schema_changes.rs
index ae5ebc815e..5e0d62af38 100644
--- a/crates/forms/src/domain/service/test/schema_changes.rs
+++ b/crates/forms/src/domain/service/test/schema_changes.rs
@@ -63,6 +63,7 @@ fn layout_of(detail: &FormDetail) -> FormLayout {
title,
description,
questions,
+ show_when,
} => FormSection::Questions {
id: *id,
title: title.clone(),
@@ -77,6 +78,7 @@ fn layout_of(detail: &FormDetail) -> FormLayout {
widget: question.widget,
})
.collect(),
+ show_when: show_when.clone(),
},
FormSectionDetail::Booking {
id,
diff --git a/crates/forms/src/inbound/toolset/create_form.rs b/crates/forms/src/inbound/toolset/create_form.rs
index fe8b1850f4..9e4ef1924c 100644
--- a/crates/forms/src/inbound/toolset/create_form.rs
+++ b/crates/forms/src/inbound/toolset/create_form.rs
@@ -11,7 +11,7 @@ use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[schemars(
title = "CreateForm",
- description = "Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating."
+ description = "Create a complete questionnaire with response columns, ordered sections, gates and an optional saved booking link. Creates closed and private; use SetFormAccess afterward to open or share it. Existing-table attachment requires database Owner and an unbound table. Use local question/option keys in gates and reference only earlier sections. Required questions require an answer; gates compare answers using AND/OR. A questions section may set showWhen (rules like a gate's, referencing only questions of earlier sections) to branch: when earlier answers fail them the section is skipped, its questions are not required and their answers are not saved. Empty answers pass only IsEmpty. A final booking step reveals an existing authorized link after acceptance; its independent URL remains usable, and strict qualification is unsupported. Each invocation creates a new form; after a timeout, use ListForms and ReadForm before trying again. Returns actual saved IDs, links and completion state; inspect partial work instead of recreating."
)]
pub struct CreateForm {
/// Flat workflow arguments shared with the domain service.
diff --git a/crates/forms/src/inbound/toolset/edit_form.rs b/crates/forms/src/inbound/toolset/edit_form.rs
index dc41751252..1847c2d876 100644
--- a/crates/forms/src/inbound/toolset/edit_form.rs
+++ b/crates/forms/src/inbound/toolset/edit_form.rs
@@ -11,7 +11,7 @@ use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[schemars(
title = "EditForm",
- description = "Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess."
+ description = "Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/gates, set or clear a questions section's showWhen (setShowWhen; skipped sections' questions are not required or saved) and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep gates and showWhen rules after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess."
)]
pub struct EditForm {
/// Flat workflow arguments shared with the domain service.
diff --git a/crates/forms/src/outbound/pg_forms_repo.rs b/crates/forms/src/outbound/pg_forms_repo.rs
index 3e70f6143c..1f5a2de4ff 100644
--- a/crates/forms/src/outbound/pg_forms_repo.rs
+++ b/crates/forms/src/outbound/pg_forms_repo.rs
@@ -30,9 +30,9 @@ pub enum PgFormsRepoError {
/// Underlying database failure.
#[error("database error")]
Sqlx(#[from] sqlx::Error),
- /// A gate's rules could not be encoded as JSON for storage, or stored
- /// ones decoded.
- #[error("failed to encode or decode stored gate rules")]
+ /// A section's rules or booking target could not be encoded as JSON for
+ /// storage, or stored ones decoded.
+ #[error("failed to encode or decode a stored section's JSON")]
Json(#[from] serde_json::Error),
/// A folder id is not a uuid.
#[error("folder id is not a uuid")]
diff --git a/crates/forms/src/outbound/pg_forms_repo/layout.rs b/crates/forms/src/outbound/pg_forms_repo/layout.rs
index 4f02fdd51c..596f16b61e 100644
--- a/crates/forms/src/outbound/pg_forms_repo/layout.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/layout.rs
@@ -87,6 +87,7 @@ pub(super) async fn insert(
let mut rules: Vec<Option<String>> = Vec::new();
let mut messages = Vec::new();
let mut booking_targets: Vec<Option<String>> = Vec::new();
+ let mut show_whens: Vec<Option<String>> = Vec::new();
let mut question_ids = Vec::new();
let mut question_sections = Vec::new();
let mut question_columns = Vec::new();
@@ -103,6 +104,7 @@ pub(super) async fn insert(
title,
description,
questions,
+ show_when,
} => {
titles.push(title.clone());
descriptions.push(description.clone());
@@ -110,6 +112,7 @@ pub(super) async fn insert(
rules.push(None);
messages.push(String::new());
booking_targets.push(None);
+ show_whens.push(show_when.as_ref().map(serde_json::to_string).transpose()?);
for (question, position) in
questions
.iter()
@@ -137,6 +140,7 @@ pub(super) async fn insert(
rules.push(Some(serde_json::to_string(gate_rules)?));
messages.push(message.clone());
booking_targets.push(None);
+ show_whens.push(None);
}
FormSection::Booking {
title,
@@ -150,16 +154,18 @@ pub(super) async fn insert(
rules.push(None);
messages.push(String::new());
booking_targets.push(Some(serde_json::to_string(target)?));
+ show_whens.push(None);
}
}
}
sqlx::query!(
r#"
- INSERT INTO form_sections (id, form_id, position, title, description, kind, gate_rules, gate_message, booking_target)
+ INSERT INTO form_sections (id, form_id, position, title, description, kind, gate_rules, gate_message, booking_target, show_when)
SELECT section.id, $1, section.position, section.title, section.description,
- section.kind, section.rules::jsonb, section.message, section.booking_target::jsonb
- FROM UNNEST($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[], $8::text[], $9::text[])
- AS section(id, position, title, description, kind, rules, message, booking_target)
+ section.kind, section.rules::jsonb, section.message, section.booking_target::jsonb,
+ section.show_when::jsonb
+ FROM UNNEST($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[], $8::text[], $9::text[], $10::text[])
+ AS section(id, position, title, description, kind, rules, message, booking_target, show_when)
"#,
form.into_uuid(),
&section_ids,
@@ -170,6 +176,7 @@ pub(super) async fn insert(
&rules as &[Option<String>],
&messages,
&booking_targets as &[Option<String>],
+ &show_whens as &[Option<String>],
)
.execute(&mut **transaction)
.await?;
@@ -217,7 +224,7 @@ pub(super) async fn read(pool: &PgPool, form: FormId) -> Result<FormLayout, PgFo
let mut snapshot = pool.begin_with(SNAPSHOT).await?;
let sections = sqlx::query!(
r#"
- SELECT id, title, description, kind, gate_rules, gate_message, booking_target
+ SELECT id, title, description, kind, gate_rules, gate_message, booking_target, show_when
FROM form_sections WHERE form_id = $1
ORDER BY position, id
"#,
@@ -263,6 +270,10 @@ pub(super) async fn read(pool: &PgPool, form: FormId) -> Result<FormLayout, PgFo
title: section.title,
description: section.description,
questions: by_section.remove(&section.id).unwrap_or_default(),
+ show_when: section
+ .show_when
+ .map(serde_json::from_value::<FilterGroup>)
+ .transpose()?,
}),
FormSectionKind::Gate => {
let rules = section.gate_rules.ok_or(PgFormsRepoError::Corrupt {
diff --git a/crates/forms/src/outbound/pg_forms_repo/test.rs b/crates/forms/src/outbound/pg_forms_repo/test.rs
index 468bc8fa4a..c484017676 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test.rs
@@ -196,6 +196,7 @@ fn layout_over(table: &Table) -> FormLayout {
required: true,
widget: Some(Widget::Paragraph),
}],
+ show_when: None,
},
FormSection::Gate {
id: FormSectionId::new(),
@@ -217,6 +218,7 @@ fn layout_over(table: &Table) -> FormLayout {
title: "Empty".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
},
],
}
@@ -313,6 +315,7 @@ async fn a_layout_is_replaced_whole_and_a_trashed_forms_is_not(pool: PgPool) {
widget: Some(Widget::Short),
},
],
+ show_when: None,
}],
};
assert_eq!(
@@ -346,6 +349,79 @@ async fn a_layout_is_replaced_whole_and_a_trashed_forms_is_not(pool: PgPool) {
assert_eq!(repo.form(form.id).await.unwrap().unwrap().trashed_at, None);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sections_show_when_rules_read_back_as_written_and_clear_with_a_replace(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = form_over(&table);
+ let first = FormSectionId::new();
+ let branch = FormSectionId::new();
+ let branching = FormLayout {
+ sections: vec![
+ FormSection::Questions {
+ id: first,
+ title: "About you".into(),
+ description: "".into(),
+ questions: vec![QuestionLayout {
+ id: FormQuestionId::new(),
+ column: table.first,
+ help_text: "".into(),
+ required: true,
+ widget: None,
+ }],
+ show_when: None,
+ },
+ FormSection::Questions {
+ id: branch,
+ title: "Follow-up".into(),
+ description: "".into(),
+ questions: vec![QuestionLayout {
+ id: FormQuestionId::new(),
+ column: table.second,
+ help_text: "".into(),
+ required: true,
+ widget: None,
+ }],
+ show_when: Some(FilterGroup {
+ conjunction: Conjunction::Or,
+ conditions: vec![FilterNode::Condition(FilterCondition {
+ column: table.first,
+ test: FilterTest::Presence {
+ operator: PresenceOperator::IsNotEmpty,
+ },
+ })],
+ }),
+ },
+ ],
+ };
+ repo.create_form(&form, &branching, false).await.unwrap();
+
+ assert_eq!(repo.layout(form.id).await.unwrap(), branching);
+
+ let mut always_shown = branching.clone();
+ let FormSection::Questions { show_when, .. } = &mut always_shown.sections[1] else {
+ panic!("the second section asks questions");
+ };
+ *show_when = None;
+ repo.replace_layout(form.id, &always_shown, at(10), None)
+ .await
+ .unwrap();
+
+ assert_eq!(repo.layout(form.id).await.unwrap(), always_shown);
+ // Only a questions section is ever shown conditionally.
+ let gate_with_show_when = sqlx::query!(
+ r#"
+ INSERT INTO form_sections (id, form_id, position, kind, gate_rules, show_when)
+ VALUES ($1, $2, 'z', 'gate', '{}'::jsonb, '{}'::jsonb)
+ "#,
+ Uuid::now_v7(),
+ form.id.into_uuid(),
+ )
+ .execute(&pool)
+ .await;
+ assert!(gate_with_show_when.is_err());
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn facts_change_only_where_given_and_a_closing_time_can_be_cleared(pool: PgPool) {
let table = insert_table(&pool).await;
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/booking.rs b/crates/forms/src/outbound/pg_forms_repo/test/booking.rs
index a8dd53375b..97ae597f16 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test/booking.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test/booking.rs
@@ -27,6 +27,7 @@ async fn a_booking_step_reads_back_with_its_target_in_its_own_column(pool: PgPoo
required: true,
widget: None,
}],
+ show_when: None,
},
FormSection::Gate {
id: FormSectionId::new(),
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
index a90f5982e6..bebd72ab45 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
@@ -39,6 +39,7 @@ async fn a_projection_commits_its_layout_and_revision_together(pool: PgPool) {
required: true,
widget: None,
}],
+ show_when: None,
}],
};
repository
@@ -147,6 +148,7 @@ async fn concurrent_projections_commit_exactly_one_revision_and_its_layout(pool:
title: title.into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
};
barrier.wait().await;
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/races.rs b/crates/forms/src/outbound/pg_forms_repo/test/races.rs
index 8fdae38ff5..f5aec515d9 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test/races.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test/races.rs
@@ -19,6 +19,7 @@ fn file_question(table: &Table) -> FormLayout {
required: false,
widget: Some(Widget::File),
}],
+ show_when: None,
}],
}
}
@@ -246,6 +247,7 @@ async fn a_layout_reusing_another_forms_ids_is_refused_by_id_and_both_layouts_st
title: "Mine".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
};
assert_eq!(
@@ -266,6 +268,7 @@ async fn a_layout_reusing_another_forms_ids_is_refused_by_id_and_both_layouts_st
required: false,
widget: None,
}],
+ show_when: None,
}],
};
assert_eq!(
@@ -309,6 +312,7 @@ async fn two_forms_putting_one_new_id_at_once_leave_it_with_exactly_one(pool: Pg
title: "".into(),
description: "".into(),
questions: vec![],
+ show_when: None,
}],
};
diff --git a/crates/macro_db_client/migrations/20261102025729_forms_section_show_when.sql b/crates/macro_db_client/migrations/20261102025729_forms_section_show_when.sql
new file mode 100644
index 0000000000..47eadaa38b
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261102025729_forms_section_show_when.sql
@@ -0,0 +1,9 @@
+-- A questions section may be shown only when earlier answers pass rules:
+-- models_databases::views::FilterGroup as JSON, naming only columns asked in
+-- earlier sections. NULL means the section is always shown.
+ALTER TABLE form_sections ADD COLUMN show_when JSONB;
+ALTER TABLE form_sections ADD CONSTRAINT form_sections_show_when_check CHECK (
+ show_when IS NULL
+ OR (kind = 'questions' AND jsonb_typeof(show_when) = 'object')
+) NOT VALID;
+ALTER TABLE form_sections VALIDATE CONSTRAINT form_sections_show_when_check;
diff --git a/crates/models_forms/src/detail.rs b/crates/models_forms/src/detail.rs
index c210ebd2ce..41f2ef844e 100644
--- a/crates/models_forms/src/detail.rs
+++ b/crates/models_forms/src/detail.rs
@@ -46,6 +46,14 @@ pub enum FormSectionDetail {
description: String,
/// Its questions, in order.
questions: Vec<FormQuestionDetail>,
+ /// When to show it, from earlier shown sections' answers; absent,
+ /// it is always shown. Sent to every caller so a respondent's page
+ /// can skip it.
+ // utoipa does not apply `rename_all_fields`, so the wire name is explicit.
+ #[serde(rename = "showWhen", default, skip_serializing_if = "Option::is_none")]
+ #[schema(nullable = false)]
+ #[specta(optional)]
+ show_when: Option<FilterGroup>,
},
/// A check of earlier answers. The rules are sent to every caller so a
/// respondent's page can stop them before submitting; respondents are
diff --git a/crates/models_forms/src/error.rs b/crates/models_forms/src/error.rs
index aaf482e4b7..c46fcfa2d6 100644
--- a/crates/models_forms/src/error.rs
+++ b/crates/models_forms/src/error.rs
@@ -140,6 +140,21 @@ pub enum LayoutProblem {
/// Why.
reason: String,
},
+ /// A section's show-when rules test a column no earlier section asks.
+ #[error(
+ "a section can only be shown on answers to questions of earlier sections; column {column} is not one"
+ )]
+ ConditionNamesLaterColumn {
+ /// The column.
+ #[schema(value_type = Uuid)]
+ column: ColumnId,
+ },
+ /// A section's show-when rule does not fit its column.
+ #[error("a show-when rule does not fit its column: {reason}")]
+ ConditionRule {
+ /// Why.
+ reason: String,
+ },
/// A text is longer than allowed.
#[error("a text is longer than {max} characters")]
TextTooLong {
diff --git a/crates/models_forms/src/layout.rs b/crates/models_forms/src/layout.rs
index a11dd52674..424079e0f3 100644
--- a/crates/models_forms/src/layout.rs
+++ b/crates/models_forms/src/layout.rs
@@ -64,6 +64,15 @@ pub enum FormSection {
description: String,
/// Its questions, in order.
questions: Vec<QuestionLayout>,
+ /// When to show it: the rules answers of earlier shown sections must
+ /// pass, naming only their columns. A section whose rules fail is
+ /// skipped: its questions are not required and their answers are
+ /// not written. Absent, it is always shown.
+ // utoipa does not apply `rename_all_fields`, so the wire name is explicit.
+ #[serde(rename = "showWhen", default, skip_serializing_if = "Option::is_none")]
+ #[schema(nullable = false)]
+ #[specta(optional)]
+ show_when: Option<FilterGroup>,
},
/// A check of earlier answers: a respondent whose answers fail the rules
/// is stopped here with the message, and nothing is written.
diff --git a/crates/models_forms/src/test.rs b/crates/models_forms/src/test.rs
index a425bdd11c..33c82a9842 100644
--- a/crates/models_forms/src/test.rs
+++ b/crates/models_forms/src/test.rs
@@ -86,6 +86,7 @@ fn a_form_detail_reads_as_the_web_client_expects() {
required: true,
widget: Some(Widget::Choice),
}],
+ show_when: None,
},
FormSectionDetail::Gate {
id: ELIGIBILITY,
@@ -225,6 +226,7 @@ fn a_layout_put_reads_sections_by_kind_and_a_missing_widget_as_default() {
required: false,
widget: None,
}],
+ show_when: None,
},
FormSection::Gate {
id: ELIGIBILITY,
diff --git a/docs/agent-guide/forms.md b/docs/agent-guide/forms.md
index 2aa4f48310..ed5fdabdf2 100644
--- a/docs/agent-guide/forms.md
+++ b/docs/agent-guide/forms.md
@@ -95,8 +95,8 @@ keeps the meeting link last. Start an empty form by adding a section, then its q
Selecting the question puts its Required switch at the bottom right, with
duplicate, remove, and more actions on the left.
- Drag by the six-dot handle (mouse: move 4 px; touch: hold 200 ms). A line
- shows where it lands; a red line with a note means a gate checks that
- question and it must stay above the gate. Escape cancels; nothing saves
+ shows where it lands; a red line with a note means a gate or a section's
+ condition checks that question and it must stay above it. Escape cancels; nothing saves
until the drop. Keyboard: focus a handle, **Space**, **↑/↓**, **Space** to
drop, **Escape** to cancel, **Tab** leaves (cancelling).
- Sections drag by their own handle. A gate section's **Add rule / Edit rules**
@@ -105,6 +105,14 @@ keeps the meeting link last. Start an empty form by adding a section, then its q
Rules are sent to respondents' browsers, so keep confidential criteria out.
A gate whose rule tests a question that is gone shows **Remove broken
rules**.
+- A questions section after another one has **Show only when…** in its
+ **⋯** menu. It opens the same condition editor, over questions of earlier
+ sections, in a **Show this section only** row under the section header; the
+ row then reads the rule (`IF Team is Contractor`) with **Edit** and
+ **Remove**, and the routing footer above it says where a skipped section
+ leads ("Continue to section 2, or skip to section 3"). Removing the last
+ question a condition tests removes the condition, and a condition naming a
+ question that went in the grid shows **Remove broken rules**.
- "N columns not on this form" at the bottom lists table columns that are not
questions; **Add** puts one on the form.
- Layout edits collaborate live through Loro. Other editors' selections appear
@@ -185,7 +193,13 @@ it uses the builder’s centered 768px content column, the form's cover image an
logo when set, plain title and description,
and questions grouped within a single section card. Public sign-in guidance
sits below the form. One section per screen with
-**Back / Next**, **Submit** on the last. Required fields keep their asterisks;
+**Back / Next**, **Submit** on the last. A section with a condition is shown
+only when the answers of the sections shown before it pass it, and skipped
+otherwise: Back and Next skip it, "Section N of M" counts only the sections
+shown, its required questions are not required, and its answers are not
+sent (an edited response clears them). Answers typed into a section that a
+changed earlier answer later skips stay on screen if the respondent goes back
+and chooses it again. Required fields keep their asterisks;
the legend and response-editing guidance sit below the questions. Next checks required answers and any
gate locally; a failing gate shows "This form can't take your response" with
the gate's message (never its rules), **Check my answers** and, signed in,
@@ -280,7 +294,11 @@ Required means an answer must be present; it does not mean the answer qualifies.
Use nonempty AND/OR gates for qualification. Rules must refer to questions in
earlier sections and options belonging to those questions. Empty answers pass
only an `isEmpty` presence check, including for negative comparisons. Zero and
-false are answers. Put at most one booking section last. Select a saved accessible
+false are answers. To branch, give a questions section `showWhen` rules
+(`CreateForm`) or change them with `setShowWhen` (`EditForm`, `null` clears);
+they follow the same rules as a gate but name only questions of earlier
+sections, never the section's own. A skipped section's questions are not
+required and their answers are not saved. Put at most one booking section last. Select a saved accessible
profile/event identity from the scheduling UI or available booking tools. Booking
gates reveal a link after an accepted response; the independent booking URL
remains usable. Requests for strict booking enforcement are refused.
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 0d253fef07..f252deaafb 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -8186,6 +8186,13 @@ export type FormSection = {
* Its questions, in order.
*/
questions: Array<QuestionLayout>;
+ /**
+ * When to show it: the rules answers of earlier shown sections must
+ * pass, naming only their columns. A section whose rules fail is
+ * skipped: its questions are not required and their answers are
+ * not written. Absent, it is always shown.
+ */
+ showWhen?: FilterGroup;
/**
* Its title; may be empty.
*/
@@ -8249,6 +8256,12 @@ export type FormSectionDetail = {
* Its questions, in order.
*/
questions: Array<FormQuestionDetail>;
+ /**
+ * When to show it, from earlier shown sections' answers; absent,
+ * it is always shown. Sent to every caller so a respondent's page
+ * can skip it.
+ */
+ showWhen?: FilterGroup;
/**
* Its title.
*/
@@ -9968,6 +9981,18 @@ export type LayoutProblem = {
* Why.
*/
reason: string;
+} | {
+ /**
+ * The column.
+ */
+ column: string;
+ kind: 'conditionNamesLaterColumn';
+} | {
+ kind: 'conditionRule';
+ /**
+ * Why.
+ */
+ reason: string;
} | {
kind: 'textTooLong';
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 3b885c2a8e..80485a4a3b 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -32821,6 +32821,10 @@
},
"description": "Its questions, in order."
},
+ "showWhen": {
+ "$ref": "#/components/schemas/FilterGroup",
+ "description": "When to show it: the rules answers of earlier shown sections must\npass, naming only their columns. A section whose rules fail is\nskipped: its questions are not required and their answers are\nnot written. Absent, it is always shown."
+ },
"title": {
"type": "string",
"description": "Its title; may be empty."
@@ -32924,6 +32928,10 @@
},
"description": "Its questions, in order."
},
+ "showWhen": {
+ "$ref": "#/components/schemas/FilterGroup",
+ "description": "When to show it, from earlier shown sections' answers; absent,\nit is always shown. Sent to every caller so a respondent's page\ncan skip it."
+ },
"title": {
"type": "string",
"description": "Its title."
@@ -35496,6 +35504,37 @@
}
}
},
+ {
+ "type": "object",
+ "description": "A section's show-when rules test a column no earlier section asks.",
+ "required": ["column", "kind"],
+ "properties": {
+ "column": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The column."
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["conditionNamesLaterColumn"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "A section's show-when rule does not fit its column.",
+ "required": ["reason", "kind"],
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["conditionRule"]
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why."
+ }
+ }
+ },
{
"type": "object",
"description": "A text is longer than allowed.",