diff --git a/README.md b/README.md
index 4b0a7a6..319a28f 100644
--- a/README.md
+++ b/README.md
@@ -3,8 +3,8 @@
A framework-agnostic library to create user flows, surveys, and questionnaires.
You describe the flow as data (a decision tree). quaire takes care of the behavior:
-which question comes next, which answers are valid, and what the navigation looks like.
-You only build the view.
+which question comes next, which answers are valid, what the navigation looks like,
+and when the flow is complete. You only build the view.
# What can I build with quaire?
@@ -15,6 +15,7 @@ The library is already used for:
- Briefings
- Games
- Questionnaires
+- Wizards and onboarding flows
# Why the name?
@@ -47,17 +48,18 @@ This gives you a clean separation of:
# Features
-- Framework-agnostic and view-independent
-- Written in TypeScript, types included
-- No runtime dependencies
+- Framework-agnostic and view-independent, works with React, Vue, Svelte, Angular, or plain JavaScript
+- Written in TypeScript, types included, no runtime dependencies, ESM and CommonJS
- Linear flows, branches, merges, and loops
-- Optional questions that can be skipped
-- Options that depend on former answers
-- Validation that resets answers when they are no longer valid
+- Branching by answers, with conditions like "age is at least 18"
+- Options, titles, and other properties that change based on former answers
+- Built-in components: single select, multi-select, boolean, input, and range
+- Validation with built-in rules and custom validators
+- Back button, progress, and completion
- Navigation with categories and subcategories
- Restore the state from an existing result
-- Typed result
-- Extensible with custom component types and custom data
+- Extensible with custom component types and custom properties
+- Check your data for mistakes, e.g. data from a CMS
# Installation
@@ -69,259 +71,481 @@ npm i quaire
## 1. Define the questions
-The questions are a list of [QuaireItem](https://github.com/devCrossNet/quaire/blob/main/src/types.ts) objects.
-This can be static data in a JS/TS file, a JSON file that you load on demand,
-or JSON from a CMS or backend API.
+Every question has an ID, a component type, and a key. The key is the property in the result that stores the answer.
+The data can be static, a JSON file, or JSON from a CMS or backend API.
```ts
-import { QuaireComponentType, QuaireItem } from 'quaire';
+import { QuaireQuestionDefinition } from 'quaire';
-export const items: QuaireItem[] = [
+export const questions: QuaireQuestionDefinition[] = [
{
id: 1,
- resultProperty: 'foo', // property in the result that stores the answer
- navigationItemId: 1, // navigation entry of this question (optional)
- dependsOnResultProperties: [], // result properties of former questions that change the options (see below)
- componentType: QuaireComponentType.SINGLE_SELECT, // tells your view which component to render
- question: 'Question 1',
- description: 'Description 1',
+ type: 'SINGLE_SELECT',
+ key: 'plan',
+ title: 'Which plan do you want?',
required: true,
- selectOptions: [
- { label: 'Option 1', value: 'option 1', nextItemId: 2 },
- { label: 'Option 2', value: 'option 2', nextItemId: 3 },
+ options: [
+ { label: 'Free', value: 'free', next: 3 },
+ { label: 'Pro', value: 'pro', next: 2 },
],
- defaultValue: 'option 1', // (optional)
},
- // ...
+ {
+ id: 2,
+ type: 'INPUT',
+ key: 'company',
+ title: 'What is your company?',
+ required: true,
+ next: 3,
+ },
+ {
+ id: 3,
+ type: 'BOOLEAN',
+ key: 'newsletter',
+ title: 'Do you want our newsletter?',
+ defaultValue: false,
+ },
];
```
-### Component types
+The flow starts with the first question. `next` defines the following question.
+If there is no next question, the flow ends.
+
+## 2. Create a quaire instance
+
+```ts
+import { Quaire } from 'quaire';
+
+const quaire = new Quaire({ questions });
+```
+
+## 3. Show the active question and save the answer
-The component type defines where quaire finds the next question:
+```ts
+const question = quaire.getActiveQuestion();
-| Component type | Options | Next question |
-| ---------------- | ------------------------------------------------ | ----------------------------------- |
-| `SINGLE_SELECT` | `selectOptions: [{ label, value, nextItemId }]` | `nextItemId` of the selected option |
-| `RANGE_SLIDER` | `rangeOption: { range, nextItemId }` | `rangeOption.nextItemId` |
-| `INPUT` | `inputOption: { type, placeholder, nextItemId }` | `inputOption.nextItemId` |
-| any other string | - | `nextItemId` of the item |
+// show question.title, question.options, question.error, etc.
-If there is no next question, the active question stays the same.
-You can add your own component types, see [Custom component types](https://github.com/devCrossNet/quaire/tree/main/examples/custom-component-types).
+quaire.saveAnswer('pro'); // moves to the next question if the answer is valid
+```
-### Options that depend on former answers
+`saveAnswer()` stores the answer in the result. If the answer is valid, quaire moves to the next question.
+If not, the question stays active and `question.error` contains an error code.
+`defaultValue` is not saved automatically. Use it as the initial value of your component.
-Use `dependsOnResultProperties` when the options of a question depend on the answer of a former question.
-The options are then nested by the result property and the answer:
+## 4. Finish the flow
```ts
-{
- id: 2,
- resultProperty: 'bar',
- dependsOnResultProperties: ['foo'],
- // ...
- selectOptions: {
- foo: {
- 'option 1': [{ label: 'Option 1.1', value: 'option 1.1', nextItemId: 3 }],
- 'option 2': [{ label: 'Option 2.1', value: 'option 2.1', nextItemId: 3 }],
- },
- },
+if (quaire.isComplete()) {
+ save(quaire.getResult()); // { plan: 'pro', company: 'ACME', newsletter: false }
}
```
-This works the same way for `rangeOption`, `inputOption`, and `defaultValue`.
-With more than one dependency, the objects are nested in the same order, for example
-`{ foo: { 'option 1': { bar: { 'option 1.1': [...] } } } }`.
-See [Dependencies between questions](https://github.com/devCrossNet/quaire/tree/main/examples/dependencies-between-questions).
+The flow is complete when the last question is answered and all answers are valid.
-## 2. Define the navigation (optional)
+# Component types
-```ts
-import { QuaireNavigationItem } from 'quaire';
+| Type | Properties | Answer |
+| --------------- | ------------------------------------------------------------------------------------ | -------------------------------- |
+| `SINGLE_SELECT` | `options: [{ label, value, next? }]` | the value of one option |
+| `MULTI_SELECT` | `options`, `minSelected?`, `maxSelected?` | an array of option values |
+| `BOOLEAN` | `trueLabel?`, `falseLabel?` | `true` or `false` |
+| `INPUT` | `inputType?`, `placeholder?`, `min?`, `max?`, `minLength?`, `maxLength?`, `pattern?` | a string or a number |
+| `RANGE` | `min`, `max`, `step?` | a number or a `[from, to]` tuple |
-export const navigationItems: QuaireNavigationItem[] = [
- { id: 1, parentId: null, name: 'Category 1' }, // has no parent
- { id: 2, parentId: 1, name: 'Subcategory 1' }, // has a parent (only one level is supported)
- { id: 3, parentId: null, name: 'Category 2', icon: 'phone' },
-];
-```
+All questions have these properties:
-`getNavigation()` returns the navigation items with these additional properties:
+| Property | Description |
+| -------------- | ----------------------------------------------------------------------------- |
+| `id` | ID of the question, a string or a number |
+| `type` | Component type |
+| `key` | Property in the result that stores the answer |
+| `title` | The question |
+| `description` | Additional text (optional) |
+| `required` | The question must be answered (default: `false`) |
+| `defaultValue` | Initial value for your component (optional) |
+| `next` | The next question (optional, see [Branching](#branching)) |
+| `navigationId` | Navigation item of the question (optional) |
+| `validate` | Custom validator (optional, see [Validation](#validation)) |
+| `variants` | Properties that change based on answers (optional, see [Variants](#variants)) |
-| Property | Description |
-| --------------- | -------------------------------------------------------------------------------- |
-| `value` | Answer of the question. For select components, the option label |
-| `active` | The active question belongs to this item (or one of its children) |
-| `hasValue` | The question of this item (or one of its children) has an answer |
-| `isValid` | The question of this item is valid. Without own question: all children are valid |
-| `componentType` | Component type of the question |
-| `subNavigation` | Children of a parent item |
+You can add your own component types, see [Custom component types](#custom-component-types).
-A parent item without its own question is shown only if it has children with questions.
-Navigation items without any question are not shown.
-See [Navigation](https://github.com/devCrossNet/quaire/tree/main/examples/navigation).
+# Branching
-## 3. Use quaire
+The next question is defined in this order:
-Create a `Quaire` instance with your data:
+1. `next` of the selected option (select components)
+2. `next` of the question
+3. no next question: the flow ends
-```ts
-import { Quaire } from 'quaire';
+`next` can be a question ID or a list of conditions. The first matching condition wins.
+An entry without condition is the fallback:
-const q = new Quaire({ items, navigationItems });
+```ts
+{
+ id: 'age',
+ type: 'INPUT',
+ key: 'age',
+ title: 'How old are you?',
+ next: [
+ { when: { age: { lt: 18 } }, to: 'consent' },
+ { to: 'employment' },
+ ],
+}
```
-Get the active question and show it in any way you want:
+## Conditions
+
+A condition is an object. Every key is a result key, and all of them must match:
+
+| Condition | Matches when the answer |
+| --------------------------------- | ------------------------------------------------- |
+| `{ plan: 'pro' }` | is `'pro'` (or contains `'pro'` for multi-select) |
+| `{ plan: ['pro', 'business'] }` | is one of the values |
+| `{ age: { gte: 18 } }` | is a number `>= 18` (also `gt`, `lt`, `lte`) |
+| `{ age: { gte: 18, lt: 65 } }` | matches all comparisons |
+| `{ company: { answered: true } }` | has a value |
+| `{ plan: { not: 'free' } }` | does not match |
+
+For everything else, use a function. Note that functions cannot be stored as JSON:
```ts
-let activeQuestion = q.getActiveQuestion(); // first question
-let navigation = q.getNavigation();
-let result = q.getResult(); // {}
+{ when: (result) => result.items.length > 3, to: 'bulk-discount' }
```
-```vue
-
-
-
-
{{ activeQuestion.question }}
-
-
-
+See [Conditional branching](https://github.com/devCrossNet/quaire/tree/main/examples/conditional-branching).
+
+# Variants
+
+Use variants when the options or other properties of a question depend on former answers.
+The first variant whose condition matches is applied to the question:
+
+```ts
+{
+ id: 2,
+ type: 'SINGLE_SELECT',
+ key: 'breed',
+ title: 'Which breed?',
+ options: [],
+ variants: [
+ { when: { animal: 'dog' }, options: [{ label: 'Poodle', value: 'poodle' }] },
+ { when: { animal: 'cat' }, title: 'Which cat breed?', options: [{ label: 'Siamese', value: 'siamese' }] },
+ ],
+}
```
-When the user answers, save the answer. Then get the next question and update the navigation and the result:
+Variants can change `title`, `description`, `required`, `defaultValue`, `next`, and the properties of the component type.
+When an answer changes and another variant applies, the answer to this question is reset to `null`.
+See [Dependencies between questions](https://github.com/devCrossNet/quaire/tree/main/examples/dependencies-between-questions).
+
+# The path
+
+quaire follows the answers from the first question. The questions on this way are the **path**:
+
+- Only questions on the path are validated.
+- When the user changes an answer and takes another branch, the answers of the old branch are removed from the result.
+- An unanswered question is followed when its next question is clear, e.g. when all options lead to the same question.
+ So the path also shows the questions that are still open.
```ts
-function onSubmit(value: unknown) {
- q.saveAnswer(value);
+quaire.getState().path; // [1, 2, 3]
+```
+
+# Validation
+
+Validation runs in this order:
- activeQuestion = q.getActiveQuestion(); // next question
- navigation = q.getNavigation();
- result = q.getResult();
+1. `required`: a question without an answer gets the error `REQUIRED`.
+ `null`, `undefined`, `''`, and `[]` are no answer. `false` and `0` are answers.
+2. The rules of the component type, e.g. `INVALID_OPTION`, `MIN`, `MAX_LENGTH`, or `PATTERN`.
+3. The custom validator of the question:
+
+```ts
+{
+ id: 2,
+ type: 'INPUT',
+ key: 'username',
+ title: 'Choose a username',
+ validate: (value, result) => (value === 'admin' ? 'RESERVED' : null),
}
```
-`defaultValue` is not saved automatically. To use it, pass it to `saveAnswer()`, for example as the initial value of your input.
+`getErrors()` returns the error codes by question ID. Map the codes to messages in your view.
+All built-in codes are in `QuaireErrorCode`.
+See [Validation](https://github.com/devCrossNet/quaire/tree/main/examples/validation).
+
+## Skip a question
+
+- An optional question can be skipped: `saveAnswer(null)` moves to the next question.
+- Save the `NO_VALUE` constant to mark a question as answered without a value, e.g. for a "Skip" or "I don't know" button.
+ The navigation shows `NO_VALUE` as its value.
-## 4. Detect the end of the flow
+See [Linear flow with an optional question](https://github.com/devCrossNet/quaire/tree/main/examples/linear-flow-skip-question).
-You need to detect the end of the user flow yourself, for example via the question ID or via the result:
+# Back, progress, and jumping to questions
```ts
-function onSubmit(value: unknown) {
- // ...
-
- if (!q.isValid()) {
- return;
- }
-
- // via question ID
- if (activeQuestion.id === 3) {
- // save the result, redirect to another page, etc.
- }
-
- // via result
- if (result.foo && result.bar && result.baz) {
- // save the result, redirect to another page, etc.
- }
-}
+quaire.back(); // the previous question
+quaire.canGoBack(); // false on the first question
+quaire.goTo(3); // any question
+quaire.getProgress(); // { answered: 2, total: 4 }
+quaire.reset(); // start again
```
-# Guides
+`total` is the number of questions on the path. It can change when the user takes another branch.
+See [Wizard](https://github.com/devCrossNet/quaire/tree/main/examples/wizard).
+
+# Navigation
-## Validation
+```ts
+import { QuaireNavigationDefinition } from 'quaire';
+
+const navigation: QuaireNavigationDefinition[] = [
+ { id: 'about', title: 'About you', icon: 'user' },
+ { id: 'plan', parentId: 'about', title: 'Plan' }, // only one level is supported
+ { id: 'contact', title: 'Contact' },
+];
-- A required question without an answer gets a `REQUIRED` error.
-- `isValid()` is `true` when there are no errors. `getValidationErrors()` returns the errors by question ID.
-- If an answer changes, dependent answers that are no longer valid are reset to `null` or removed.
- Questions that are no longer part of the flow are removed from the result.
+const quaire = new Quaire({ questions, navigation });
+quaire.getNavigation();
+quaire.goToNavigationItem('about'); // a parent without question jumps to its first child
+```
-## Skip an optional question
+Questions are assigned with `navigationId`. `getNavigation()` returns the navigation items with these properties:
+
+| Property | Description |
+| ----------- | --------------------------------------------------------------- |
+| `question` | The question of this item, or `null` |
+| `value` | The answer. For select components, the label of the option |
+| `active` | The active question belongs to this item or one of its children |
+| `hasValue` | This item or one of its children has an answer |
+| `isValid` | This item and all its children are valid |
+| `reachable` | The question of this item or one of its children is on the path |
+| `children` | The children of a top-level item |
+
+All other properties of the definition, e.g. `title` and `icon`, are kept.
+Items without any question are not shown.
+See [Navigation](https://github.com/devCrossNet/quaire/tree/main/examples/navigation).
-There are two ways to skip a question:
+# Restore the state
-- Branch around it: an option of a former question points to the question after it.
-- Save the `NO_VALUE` constant as the answer. The navigation then shows the question as answered.
+Save the result, e.g. in your backend, and pass it back later.
+quaire follows the path and continues with the first open question:
```ts
-import { NO_VALUE } from 'quaire';
+const quaire = new Quaire({ questions, result: { plan: 'pro' } });
-q.saveAnswer(NO_VALUE);
+quaire.getActiveQuestion().id; // 2
+quaire.canGoBack(); // true
```
-See [Linear flow with an optional question](https://github.com/devCrossNet/quaire/tree/main/examples/linear-flow-skip-question).
+See [Restore state](https://github.com/devCrossNet/quaire/tree/main/examples/restore-state).
-## Jump to a question
+# Framework integration
+
+`getState()` returns one object with everything your view needs.
+The object only changes when the flow changes, and `subscribe()` calls a listener after every change.
```ts
-q.setActiveQuestionByQuestionId(2);
-q.setActiveQuestionByNavigationItemId(1); // a parent item without question jumps to its first child
+const { activeQuestion, result, errors, navigation, path, progress, isValid, isComplete, canGoBack } =
+ quaire.getState();
+
+const unsubscribe = quaire.subscribe((state) => render(state));
```
-After the user changes the answer, the flow continues with the next question. The other answers stay.
+## React
-## Restore the state
+```tsx
+import { useMemo, useSyncExternalStore } from 'react';
+import { Quaire, QuaireOptions } from 'quaire';
-Save the result (for example in your backend) and pass it back later.
-quaire replays the answers and continues with the first question that has no answer:
+export const useQuaire = (options: QuaireOptions) => {
+ const quaire = useMemo(() => new Quaire(options), []);
+ const state = useSyncExternalStore(
+ (listener) => quaire.subscribe(listener),
+ () => quaire.getState(),
+ );
+
+ return { quaire, state };
+};
+```
+
+## Vue
```ts
-const q = new Quaire({ items, navigationItems, result: { foo: 'option 1', bar: 'option 1.2' } });
+import { onUnmounted, shallowRef } from 'vue';
+import { Quaire, QuaireOptions } from 'quaire';
+
+export const useQuaire = (options: QuaireOptions) => {
+ const quaire = new Quaire(options);
+ const state = shallowRef(quaire.getState());
+
+ onUnmounted(quaire.subscribe((newState) => (state.value = newState)));
+
+ return { quaire, state };
+};
```
-See [Restore state](https://github.com/devCrossNet/quaire/tree/main/examples/restore-state).
+# TypeScript
## Typed result
-By default, all answers are `unknown`. Pass your own result type as the first type parameter to get a typed result.
+By default, all answers are `unknown`. Pass your result type as the first type parameter.
Each answer is optional and can be `null`: it is missing until the user answers, and it is reset to `null` when it becomes invalid.
```ts
-import { Quaire } from 'quaire';
-
type MyResult = {
- foo: string;
- bar: Array;
+ plan: 'free' | 'pro';
+ newsletter: boolean;
};
-const q = new Quaire({ items, navigationItems });
-const result = q.getResult(); // { foo?: string | null; bar?: Array | null }
+const quaire = new Quaire({ questions });
+quaire.getResult(); // { plan?: 'free' | 'pro' | null; newsletter?: boolean | null }
```
-# API
+## Questions by type
+
+`type` tells TypeScript which properties a question has:
-| Method | Description |
-| ------------------------------------------------------- | ---------------------------------------------------- |
-| `getActiveQuestion()` | Returns the active question or `null` |
-| `saveAnswer(answer)` | Saves the answer of the active question and moves on |
-| `getResult()` | Returns all answers by result property |
-| `getNavigation()` | Returns the navigation with values and states |
-| `isValid()` | Returns `true` when there are no validation errors |
-| `getValidationErrors()` | Returns the validation errors by question ID |
-| `setActiveQuestionByQuestionId(questionId)` | Sets the active question |
-| `setActiveQuestionByNavigationItemId(navigationItemId)` | Sets the active question by navigation item |
+```ts
+const question = quaire.getActiveQuestion();
-# Extend quaire
+if (question?.type === 'SINGLE_SELECT') {
+ question.options; // QuaireSelectOption[]
+}
+```
-`Quaire` is a class. Extend it and override its protected methods to change the behavior:
+## Custom properties
+
+Add your own properties to questions, options, and navigation items, e.g. for your view:
+
+```ts
+type MyQuestionDefinition = QuaireQuestionDefinition & { progress: number };
+type MyNavigationDefinition = QuaireNavigationDefinition & { color: string };
+
+const quaire = new Quaire({ questions, navigation });
+
+quaire.getActiveQuestion().progress;
+quaire.getNavigation()[0].color;
+```
+
+See [Extending the data definition](https://github.com/devCrossNet/quaire/tree/main/examples/extending-data-definition).
+
+## Custom component types
+
+A component defines how quaire handles a type. All functions are optional:
+
+```ts
+import { QuaireComponent, QuaireQuestionDefinition, QuaireQuestionDefinitionBase } from 'quaire';
+
+type RatingDefinition = QuaireQuestionDefinitionBase<'RATING', { stars: number }>;
+type MyQuestionDefinition = QuaireQuestionDefinition | RatingDefinition;
+
+const rating: QuaireComponent = {
+ hasValue: (value) => typeof value === 'number', // default: not null, undefined, '' or []
+ validate: (definition, value) => (Number(value) <= definition.stars ? null : 'INVALID_RATING'),
+ getNext: (definition, value) => undefined, // default: the `next` of the question
+ getDisplayValue: (definition, value) => `${value} / ${definition.stars}`, // shown in the navigation
+};
+
+const quaire = new Quaire({ questions, components: { RATING: rating } });
+```
+
+You can also replace a built-in component, e.g. `components: { INPUT: myInput }`.
+See [Custom component types](https://github.com/devCrossNet/quaire/tree/main/examples/custom-component-types).
+
+# Check your data
+
+`validateDefinition()` finds mistakes in your data, e.g. in a test for data from a CMS:
+
+```ts
+import { validateDefinition } from 'quaire';
+
+expect(validateDefinition({ questions, navigation })).toEqual([]);
+```
+
+It finds duplicate IDs and keys, unknown types, `next` targets that do not exist, questions that cannot be reached,
+and unknown navigation items. Each problem has a `code` and a `message`.
+
+# API
-- [Custom component types](https://github.com/devCrossNet/quaire/tree/main/examples/custom-component-types): add multi-select and boolean components
-- [Extending the data definition](https://github.com/devCrossNet/quaire/tree/main/examples/extending-data-definition): add your own properties to questions and navigation items
+## Options
+
+| Option | Description |
+| ------------ | ------------------------------------------------------------ |
+| `questions` | The question definitions, the flow starts with the first one |
+| `navigation` | The navigation definitions (optional) |
+| `result` | An existing result to restore (optional) |
+| `components` | Custom or replaced component types (optional) |
+
+## Methods
+
+| Method | Description |
+| ------------------------ | ---------------------------------------------------------------------- |
+| `getState()` | Everything below in one object, the same object until the next change |
+| `subscribe(listener)` | Calls the listener after every change, returns an unsubscribe function |
+| `getActiveQuestion()` | The active question or `null` |
+| `saveAnswer(value)` | Saves the answer and moves to the next question if it is valid |
+| `getResult()` | All answers by key |
+| `getErrors()` | The error codes by question ID |
+| `getNavigation()` | The navigation with values and states |
+| `getProgress()` | `{ answered, total }` of the path |
+| `isValid()` | `true` when there are no errors on the path |
+| `isComplete()` | `true` when the last question is answered and all answers are valid |
+| `canGoBack()` | `true` when there is a previous question |
+| `back()` | Goes to the previous question |
+| `goTo(questionId)` | Goes to a question |
+| `goToNavigationItem(id)` | Goes to the question of a navigation item |
+| `reset()` | Removes all answers and starts again |
+
+## Exports
+
+`Quaire`, `validateDefinition`, `matchesCondition`, `hasValue`, `defaultComponents`, `NO_VALUE`,
+`QuaireComponentType`, `QuaireErrorCode`, `QuaireDefinitionProblemCode`, and all types.
+
+# Migration from 0.x
+
+| 0.x | 1.0 |
+| ---------------------------------------------- | --------------------------------------------------------- |
+| `new Quaire({ items, navigationItems })` | `new Quaire({ questions, navigation })` |
+| `QuaireItem` | `QuaireQuestionDefinition` |
+| `QuaireNavigationItem` (input) | `QuaireNavigationDefinition` |
+| `componentType` | `type` |
+| `resultProperty` | `key` |
+| `question` (text) | `title` |
+| `navigationItemId` | `navigationId` |
+| `name` (navigation) | `title` |
+| `selectOptions` | `options` |
+| `rangeOption: { range: [min, max] }` | `min`, `max` |
+| `inputOption: { type, placeholder }` | `inputType`, `placeholder` |
+| `nextItemId` | `next` |
+| `RANGE_SLIDER` | `RANGE` |
+| `dependsOnResultProperties` and nested options | `variants` with `when` conditions |
+| `subNavigation` | `children` |
+| `setActiveQuestionByQuestionId(id)` | `goTo(id)` |
+| `setActiveQuestionByNavigationItemId(id)` | `goToNavigationItem(id)` |
+| `getValidationErrors()` | `getErrors()` |
+| `QuaireValidationError.REQUIRED` | `QuaireErrorCode.REQUIRED` |
+| Subclass and override protected methods | `components` option and custom properties |
+| No next question: the question stays active | No next question: the flow ends, `isComplete()` is `true` |
+| Answers of other branches stay in the result | Only answers on the path stay in the result |
# Examples
-Each example has a README with a diagram, the data, and tests that show the behavior step by step.
+Each example has a README, the data, and tests that show the behavior step by step.
- [Linear flow](https://github.com/devCrossNet/quaire/tree/main/examples/linear-flow)
- [Linear flow with a loop](https://github.com/devCrossNet/quaire/tree/main/examples/linear-flow-with-loop)
- [Linear flow with an optional question](https://github.com/devCrossNet/quaire/tree/main/examples/linear-flow-skip-question)
- [Branched flow that merges back into one](https://github.com/devCrossNet/quaire/tree/main/examples/branched-and-merged-flow)
-- [Dependencies between questions and validation](https://github.com/devCrossNet/quaire/tree/main/examples/dependencies-between-questions)
+- [Conditional branching](https://github.com/devCrossNet/quaire/tree/main/examples/conditional-branching)
+- [Dependencies between questions](https://github.com/devCrossNet/quaire/tree/main/examples/dependencies-between-questions)
+- [Validation](https://github.com/devCrossNet/quaire/tree/main/examples/validation)
+- [Wizard: back, progress, and completion](https://github.com/devCrossNet/quaire/tree/main/examples/wizard)
- [Navigation](https://github.com/devCrossNet/quaire/tree/main/examples/navigation)
- [Restore state](https://github.com/devCrossNet/quaire/tree/main/examples/restore-state)
+- [Custom component types](https://github.com/devCrossNet/quaire/tree/main/examples/custom-component-types)
+- [Extending the data definition](https://github.com/devCrossNet/quaire/tree/main/examples/extending-data-definition)
# Contribute
diff --git a/examples/branched-and-merged-flow/README.md b/examples/branched-and-merged-flow/README.md
index fa7302b..492e841 100644
--- a/examples/branched-and-merged-flow/README.md
+++ b/examples/branched-and-merged-flow/README.md
@@ -3,10 +3,11 @@
Question 1 splits the flow into two branches that merge back into question 4.
You can have as many branches as you want.
-- **Branch A:** question 2 is a `RANGE_SLIDER`. Its next question is defined in `rangeOption.nextItemId`.
-- **Branch B:** question 3 is an `INPUT`. Its next question is defined in `inputOption.nextItemId`.
+- **Branch A:** question 2 is a `RANGE` with a default value.
+- **Branch B:** question 3 is an `INPUT` with a default value.
Only the answers of the chosen branch are in the result.
+When the user goes back and chooses the other branch, the answers of the old branch are removed.
```
┌────────────┐
diff --git a/examples/conditional-branching/README.md b/examples/conditional-branching/README.md
new file mode 100644
index 0000000..fce9977
--- /dev/null
+++ b/examples/conditional-branching/README.md
@@ -0,0 +1,27 @@
+# Conditional branching
+
+The next question depends on the answers, not only on the selected option:
+
+```
+How old are you?
+├── under 18 ──► Do your parents agree?
+│ ├── yes ──► What are you interested in?
+│ └── no ──► end
+└── 18 or older ──► What do you do?
+ ├── employed, self-employed ──► What is your yearly income? ──► What are you interested in?
+ └── student ──────────────────────────────────────────────► What are you interested in?
+
+What are you interested in?
+├── contains "travel" ──► Where do you want to travel next?
+└── other ──► end
+```
+
+This example shows:
+
+- `next` with a list of conditions. The first match wins, an entry without `when` is the fallback.
+- Comparisons like `{ age: { lt: 18 } }`.
+- Multi-select conditions: `{ interests: 'travel' }` matches when the answer contains `'travel'`.
+- A flow that ends early when no condition matches.
+- A variant with a function condition, for rules that are not possible with data.
+
+See [data.ts](./data.ts) for the data and [conditional-branching.spec.ts](./conditional-branching.spec.ts) for the behavior step by step.
diff --git a/examples/custom-component-types/README.md b/examples/custom-component-types/README.md
index dc45001..d6947f0 100644
--- a/examples/custom-component-types/README.md
+++ b/examples/custom-component-types/README.md
@@ -1,19 +1,19 @@
# Custom component types
-This example extends `Quaire` with two new component types:
+This example adds a `RATING` component type with a `stars` property.
-- `MULTI_SELECT`: the answer is an array of option values
-- `BOOLEAN`: the answer is `true` or `false`
+[rating.ts](./rating.ts) defines the type and its behavior:
-[MyQuaire.ts](./MyQuaire.ts) overrides these protected properties and methods:
+- `RatingDefinition` describes the properties of a rating question.
+- `MyQuestionDefinition` combines the built-in types with the rating type.
+- The `rating` component validates the answer and shows "4 / 5" in the navigation.
-| Override | Why |
-| ------------------------------------------- | ------------------------------------------------------------------------------------------ |
-| `_selectComponentTypes` | `MULTI_SELECT` uses `selectOptions` like `SINGLE_SELECT` |
-| `_alwaysPossibleFollowUpQuestionComponents` | a `BOOLEAN` question that depends on former answers always stays in the flow |
-| `_validateSelectComponent` | a `MULTI_SELECT` answer is valid if at least one value is a valid option |
-| `_getNextItemIdFromSelectComponents` | find the next question for an array of values |
-| `_getDependencyPath` | a `MULTI_SELECT` answer is sorted and joined with `_` to one key, e.g. `option 1_option 2` |
-| `_getNavigationValue` | show the labels of all selected options in the navigation |
+The component is passed to quaire with the `components` option:
+
+```ts
+new Quaire