From 678c95d8ddf89ce7806be287c7b9a05da2cec5e5 Mon Sep 17 00:00:00 2001 From: Johannes Werner Date: Thu, 8 Oct 2026 20:32:36 +0200 Subject: [PATCH 1/3] feat!: redesign quaire for 1.0 - follow the path of the answers: only questions on the path are validated, answers of other branches are removed - add back(), canGoBack(), goTo(), getProgress(), isComplete() and reset() - add getState() and subscribe() for framework integration - add conditions for next questions and variants for dependent properties - add MULTI_SELECT and BOOLEAN, validation rules and custom validators - add a component registry and validateDefinition() - fix falsy answers, mutated result objects and slow flows - split the code into modules - ignore .claude in eslint BREAKING CHANGE: new data format and API. Items are questions with type, key, title and next, dependsOnResultProperties is replaced by variants, and the methods are renamed. See the migration table in the readme. Co-Authored-By: Claude Opus 5.5 --- eslint.config.mjs | 3 +- .../branched-and-merged-flow.spec.ts | 128 +-- examples/branched-and-merged-flow/data.ts | 110 +-- .../conditional-branching.spec.ts | 49 + examples/conditional-branching/data.ts | 72 ++ examples/custom-component-types/MyQuaire.ts | 88 -- .../custom-component-types.spec.ts | 210 +---- examples/custom-component-types/data.ts | 115 +-- examples/custom-component-types/rating.ts | 17 + .../dependencies-between-questions/data.ts | 165 +--- .../dependencies-between-questions.spec.ts | 180 +--- .../extending-data-definition/MyQuaire.ts | 60 -- examples/extending-data-definition/data.ts | 70 +- .../extending-data-definition.spec.ts | 69 +- examples/linear-flow-skip-question/data.ts | 96 +- .../linear-flow-skip-question.spec.ts | 112 +-- examples/linear-flow-with-loop/data.ts | 95 +- .../linear-flow-with-loop.spec.ts | 69 +- examples/linear-flow/data.ts | 94 +- examples/linear-flow/linear-flow.spec.ts | 72 +- examples/navigation/data.ts | 107 +-- examples/navigation/navigation.spec.ts | 128 +-- examples/restore-state/restore-state.spec.ts | 172 +--- examples/validation/data.ts | 63 ++ examples/validation/validation.spec.ts | 67 ++ examples/wizard/data.ts | 40 + examples/wizard/wizard.spec.ts | 69 ++ src/components.spec.ts | 138 +++ src/components.ts | 128 +++ src/conditions.spec.ts | 62 ++ src/conditions.ts | 40 + src/constants.ts | 40 + src/definition.spec.ts | 138 +++ src/definition.ts | 159 ++++ src/enums.ts | 9 - src/index.ts | 11 +- src/navigation.ts | 73 ++ src/quaire.spec.ts | 872 ++++++++++++------ src/quaire.ts | 707 ++++++-------- src/types.ts | 245 +++-- src/utils.spec.ts | 33 +- src/utils.ts | 22 +- vitest.config.mts | 2 +- 43 files changed, 2715 insertions(+), 2484 deletions(-) create mode 100644 examples/conditional-branching/conditional-branching.spec.ts create mode 100644 examples/conditional-branching/data.ts delete mode 100644 examples/custom-component-types/MyQuaire.ts create mode 100644 examples/custom-component-types/rating.ts delete mode 100644 examples/extending-data-definition/MyQuaire.ts create mode 100644 examples/validation/data.ts create mode 100644 examples/validation/validation.spec.ts create mode 100644 examples/wizard/data.ts create mode 100644 examples/wizard/wizard.spec.ts create mode 100644 src/components.spec.ts create mode 100644 src/components.ts create mode 100644 src/conditions.spec.ts create mode 100644 src/conditions.ts create mode 100644 src/definition.spec.ts create mode 100644 src/definition.ts delete mode 100644 src/enums.ts create mode 100644 src/navigation.ts diff --git a/eslint.config.mjs b/eslint.config.mjs index 1ed8a6b..a5b92c3 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,7 +6,7 @@ import tseslint from 'typescript-eslint'; export default defineConfig( { - ignores: ['**/.github/**', '**/coverage/**', '**/dist/**', '**/node_modules/**', 'commitlint.config.mjs'], + ignores: ['**/.claude/**', '**/.github/**', '**/coverage/**', '**/dist/**', '**/node_modules/**', 'commitlint.config.mjs'], }, eslint.configs.recommended, tseslint.configs.recommended, @@ -26,6 +26,7 @@ export default defineConfig( { selector: 'typeLike', format: ['PascalCase'], custom: { regex: '^I[A-Z]', match: false } }, ], '@typescript-eslint/no-require-imports': 0, + '@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true, argsIgnorePattern: '^_' }], 'no-async-promise-executor': 0, 'no-prototype-builtins': 0, }, diff --git a/examples/branched-and-merged-flow/branched-and-merged-flow.spec.ts b/examples/branched-and-merged-flow/branched-and-merged-flow.spec.ts index a2acbec..8c9cced 100644 --- a/examples/branched-and-merged-flow/branched-and-merged-flow.spec.ts +++ b/examples/branched-and-merged-flow/branched-and-merged-flow.spec.ts @@ -1,128 +1,48 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('branched-and-merged-flow', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); - test('should go through branch A (range slider) and merge into question 4', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - + test('should go through branch A (range) and merge into question 4', () => { Q.saveAnswer('option 1'); + expect(Q.getActiveQuestion().title).toBe('Question 2'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - - Q.saveAnswer(activeQuestion.defaultValue); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 4'); + Q.saveAnswer(Q.getActiveQuestion().defaultValue); + expect(Q.getActiveQuestion().title).toBe('Question 4'); Q.saveAnswer('option 1'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 4'); - - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: [50, 75], - foobarbaz: 'option 1', - }); - - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'RANGE_SLIDER', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: [50, 75], - }, - ], - value: 'Option 1', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: 'Option 1', - }, + expect(Q.getResult()).toEqual({ foo: 'option 1', bar: [50, 75], foobarbaz: 'option 1' }); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 1', children: [{ id: 2, value: [50, 75] }] }, + { id: 3, value: 'Option 1', active: true }, ]); }); test('should go through branch B (input) and merge into question 4', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - Q.saveAnswer('option 2'); + expect(Q.getActiveQuestion().title).toBe('Question 3'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); - - Q.saveAnswer(activeQuestion.defaultValue); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 4'); + Q.saveAnswer(Q.getActiveQuestion().defaultValue); + expect(Q.getActiveQuestion().title).toBe('Question 4'); Q.saveAnswer('option 1'); + expect(Q.getResult()).toEqual({ foo: 'option 2', baz: 'user input', foobarbaz: 'option 1' }); + expect(Q.getNavigation()).toMatchObject([{ id: 1, children: [{ id: 2, value: 'user input' }] }, { id: 3 }]); + }); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 4'); - - expect(Q.getResult()).toEqual({ - foo: 'option 2', - baz: 'user input', - foobarbaz: 'option 1', - }); + test('should remove the answers of branch A when the user switches to branch B', () => { + Q.saveAnswer('option 1'); + Q.saveAnswer([20, 30]); + Q.saveAnswer('option 2'); + Q.goTo(1); + Q.saveAnswer('option 2'); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'INPUT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'user input', - }, - ], - value: 'Option 2', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: 'Option 1', - }, - ]); + expect(Q.getActiveQuestion().title).toBe('Question 3'); + expect(Q.getResult()).toEqual({ foo: 'option 2', foobarbaz: 'option 2' }); }); }); diff --git a/examples/branched-and-merged-flow/data.ts b/examples/branched-and-merged-flow/data.ts index 34b5d21..50eca75 100644 --- a/examples/branched-and-merged-flow/data.ts +++ b/examples/branched-and-merged-flow/data.ts @@ -1,95 +1,53 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +export const questions: Array = [ { - id: 1, // Branch A/B - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + id: 1, + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, // branch A - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 3, // branch B - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 2 }, // branch A + { label: 'Option 2', value: 'option 2', next: 3 }, // branch B ], }, { id: 2, // branch A - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.RANGE_SLIDER, - question: 'Question 2', - description: 'Description 2', - required: false, - rangeOption: { - range: [0, 100], - nextItemId: 4, // Branch A/B - }, + type: 'RANGE', + key: 'bar', + title: 'Question 2', + navigationId: 2, + min: 0, + max: 100, defaultValue: [50, 75], + next: 4, }, { id: 3, // branch B - resultProperty: 'baz', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.INPUT, - question: 'Question 3', - description: 'Description 3', - required: false, - inputOption: { - type: 'text', - placeholder: 'baz', - nextItemId: 4, // Branch A/B - }, + type: 'INPUT', + key: 'baz', + title: 'Question 3', + navigationId: 2, defaultValue: 'user input', + next: 4, }, { - id: 4, // Branch A/B - resultProperty: 'foobarbaz', - navigationItemId: 3, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 4', - description: 'Description 4', - required: false, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - }, - { - label: 'Option 2', - value: 'option 2', - }, + id: 4, // both branches merge here + type: 'SINGLE_SELECT', + key: 'foobarbaz', + title: 'Question 4', + navigationId: 3, + options: [ + { label: 'Option 1', value: 'option 1' }, + { label: 'Option 2', value: 'option 2' }, ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1' }, + { id: 2, parentId: 1, title: 'Subcategory 1' }, + { id: 3, title: 'Category 2' }, ]; diff --git a/examples/conditional-branching/conditional-branching.spec.ts b/examples/conditional-branching/conditional-branching.spec.ts new file mode 100644 index 0000000..0cd48fa --- /dev/null +++ b/examples/conditional-branching/conditional-branching.spec.ts @@ -0,0 +1,49 @@ +import { Quaire, validateDefinition } from '../../src'; +import { questions } from './data'; + +describe('conditional-branching', () => { + let Q: Quaire; + + beforeEach(() => { + Q = new Quaire({ questions }); + }); + + test('should have a valid definition', () => { + expect(validateDefinition({ questions })).toEqual([]); + }); + + test('should end the flow for minors without consent', () => { + Q.saveAnswer(15); + expect(Q.getActiveQuestion().id).toBe('consent'); + + Q.saveAnswer(false); + expect(Q.isComplete()).toBe(true); + expect(Q.getState().path).toEqual(['age', 'consent']); + }); + + test('should ask minors with consent about their interests', () => { + Q.saveAnswer(15); + Q.saveAnswer(true); + + expect(Q.getActiveQuestion().id).toBe('interests'); + }); + + test('should ask adults about their employment and income', () => { + Q.saveAnswer(30); + Q.saveAnswer('employed'); + Q.saveAnswer(120000); + Q.saveAnswer(['music', 'travel']); + + expect(Q.getActiveQuestion()).toMatchObject({ id: 'destination', placeholder: 'Maldives' }); + expect(Q.getState().path).toEqual(['age', 'employment', 'income', 'interests', 'destination']); + }); + + test('should skip the income for students', () => { + Q.saveAnswer(21); + Q.saveAnswer('student'); + Q.saveAnswer(['sports']); + + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ age: 21, employment: 'student', interests: ['sports'] }); + }); +}); diff --git a/examples/conditional-branching/data.ts b/examples/conditional-branching/data.ts new file mode 100644 index 0000000..5ec3ca8 --- /dev/null +++ b/examples/conditional-branching/data.ts @@ -0,0 +1,72 @@ +import type { QuaireQuestionDefinition } from '../../src'; + +export const questions: Array = [ + { + id: 'age', + type: 'INPUT', + key: 'age', + title: 'How old are you?', + inputType: 'number', + required: true, + min: 0, + max: 120, + // the first matching condition wins, an entry without condition is the fallback + next: [{ when: { age: { lt: 18 } }, to: 'consent' }, { to: 'employment' }], + }, + { + id: 'consent', + type: 'BOOLEAN', + key: 'consent', + title: 'Do your parents agree?', + required: true, + // without consent, the flow ends here + next: [{ when: { consent: true }, to: 'interests' }], + }, + { + id: 'employment', + type: 'SINGLE_SELECT', + key: 'employment', + title: 'What do you do?', + required: true, + options: [ + { label: 'Employed', value: 'employed', next: 'income' }, + { label: 'Self-employed', value: 'self-employed', next: 'income' }, + { label: 'Student', value: 'student', next: 'interests' }, + ], + }, + { + id: 'income', + type: 'INPUT', + key: 'income', + title: 'What is your yearly income?', + inputType: 'number', + next: 'interests', + }, + { + id: 'interests', + type: 'MULTI_SELECT', + key: 'interests', + title: 'What are you interested in?', + required: true, + options: [ + { label: 'Sports', value: 'sports' }, + { label: 'Music', value: 'music' }, + { label: 'Travel', value: 'travel' }, + ], + // a multi-select answer matches if it contains the value + next: [{ when: { interests: 'travel' }, to: 'destination' }], + }, + { + id: 'destination', + type: 'INPUT', + key: 'destination', + title: 'Where do you want to travel next?', + // a function can be used for conditions that are not possible with data + variants: [ + { + when: (result) => Number(result.income) > 100000, + placeholder: 'Maldives', + }, + ], + }, +]; diff --git a/examples/custom-component-types/MyQuaire.ts b/examples/custom-component-types/MyQuaire.ts deleted file mode 100644 index 25796bc..0000000 --- a/examples/custom-component-types/MyQuaire.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { - Quaire, - QuaireComponentType, - QuaireItem, - QuaireOptions, - QuaireQuestion, - QuaireValidationError, -} from '../../src'; - -export enum MyComponentType { - MULTI_SELECT = 'MULTI_SELECT', - BOOLEAN = 'BOOLEAN', -} - -export class MyQuaire extends Quaire { - // add MULTI_SELECT to select component to use dedicated logic - protected readonly _selectComponentTypes: Array = [ - QuaireComponentType.SINGLE_SELECT, - MyComponentType.MULTI_SELECT, - ]; - // questions with these components always stay in the flow, even if they depend on former answers - // e.g. a BOOLEAN question that depends on a MULTI_SELECT answer is never removed from the flow - protected readonly _alwaysPossibleFollowUpQuestionComponents: Array = [ - QuaireComponentType.RANGE_SLIDER, - QuaireComponentType.INPUT, - MyComponentType.BOOLEAN, - ]; - - constructor({ items, navigationItems, result }: QuaireOptions) { - // call Quaire constructor - super({ items, navigationItems, result }); - } - - // override default behaviour and apply new logic for MULTI_SELECT components - protected _validateSelectComponent(question: QuaireQuestion, currentAnswer: unknown[]) { - if (question.componentType === MyComponentType.MULTI_SELECT) { - const options = question.selectOptions.filter((o) => currentAnswer.includes(o.value)); - - if (question.required && options.length === 0) { - this._result[question.resultProperty] = null; - this._validationErrors[question.id] = QuaireValidationError.REQUIRED; - } - } else { - super._validateSelectComponent(question, currentAnswer); - } - } - - // override default behaviour and apply new logic for MULTI_SELECT components - protected _getNextItemIdFromSelectComponents = (activeQuestion: QuaireQuestion, answer: unknown) => { - const option = activeQuestion.selectOptions.find((o) => - Array.isArray(answer) ? answer.includes(o.value) : o.value === answer, - ); - - return option?.nextItemId; - }; - - // override default behaviour and apply new logic for MULTI_SELECT components - // in case a question has a dependency to a MULTI_SELECT component value, - // we need to concatenate the array to get one key for the item definition - protected _getDependencyPath(item: QuaireItem) { - const path: Array = []; - - item.dependsOnResultProperties.forEach((resultProperty) => { - const resultPropertyValue = this._getResultByValueProperty(resultProperty); - - if (resultPropertyValue) { - path.push(resultProperty); - path.push( - Array.isArray(resultPropertyValue) ? resultPropertyValue.sort().join('_') : String(resultPropertyValue), - ); - } - }); - return path; - } - - // override default behaviour and apply new logic for MULTI_SELECT components - protected _getNavigationValue(question: QuaireQuestion, answer: unknown) { - if (question.componentType === MyComponentType.MULTI_SELECT) { - const answers = answer as unknown[]; - - return question.selectOptions - .filter((selectOption) => answers.includes(selectOption.value)) - .map((selectOption) => selectOption.label); - } else { - return super._getNavigationValue(question, answer); - } - } -} diff --git a/examples/custom-component-types/custom-component-types.spec.ts b/examples/custom-component-types/custom-component-types.spec.ts index 39ea077..747e969 100644 --- a/examples/custom-component-types/custom-component-types.spec.ts +++ b/examples/custom-component-types/custom-component-types.spec.ts @@ -1,201 +1,43 @@ -import { items, navigationItems } from './data'; -import { MyComponentType, MyQuaire } from './MyQuaire'; +import { Quaire, validateDefinition } from '../../src'; +import { navigation, questions } from './data'; +import { MyQuestionDefinition, rating } from './rating'; describe('custom-component-types', () => { - let Q: MyQuaire; + let Q: Quaire; beforeEach(() => { - Q = new MyQuaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation, components: { RATING: rating } }); }); - const answerAllQuestionsWithOption1 = () => { - Q.saveAnswer('option 1'); - Q.saveAnswer(['option 2', 'option 1']); - Q.saveAnswer(true); - }; - - test('should go through MULTI_SELECT and BOOLEAN questions', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - - Q.saveAnswer('option 1'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - expect(activeQuestion.componentType).toBe(MyComponentType.MULTI_SELECT); - expect(activeQuestion.selectOptions).toEqual([ - { - label: 'Option 1', - nextItemId: 3, - value: 'option 1', - }, - { - label: 'Option 2', - nextItemId: 3, - value: 'option 2', - }, - ]); - - Q.saveAnswer(['option 2', 'option 1']); - activeQuestion = Q.getActiveQuestion(); - - expect(activeQuestion.question).toBe('Question 3'); - expect(activeQuestion.componentType).toBe(MyComponentType.BOOLEAN); - expect(activeQuestion.defaultValue).toBe(true); - - Q.saveAnswer(activeQuestion.defaultValue); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: ['option 1', 'option 2'], - baz: true, - }); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'MULTI_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: ['Option 1', 'Option 2'], - }, - ], - value: 'Option 1', - }, - { - active: false, - componentType: 'BOOLEAN', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: true, - }, - ]); + test('should have a valid definition', () => { + expect(validateDefinition({ questions, navigation, components: { RATING: rating } })).toEqual([]); }); - test('should reset the MULTI_SELECT answer when the first answer changes', () => { - answerAllQuestionsWithOption1(); + test('should validate the custom component', () => { + Q.saveAnswer(6); - Q.saveAnswer('option 2'); - const activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - expect(activeQuestion.componentType).toBe(MyComponentType.MULTI_SELECT); - expect(activeQuestion.selectOptions).toEqual([ - { - label: 'Option 3', - nextItemId: 3, - value: 'option 3', - }, - { - label: 'Option 4', - nextItemId: 3, - value: 'option 4', - }, - ]); - expect(Q.getResult()).toEqual({ - foo: 'option 2', - bar: null, - baz: true, - }); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: true, - componentType: 'MULTI_SELECT', - hasValue: false, - id: 2, - isValid: false, - name: 'Subcategory 1', - value: null, - }, - ], - value: 'Option 2', - }, - { - active: false, - componentType: 'BOOLEAN', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: true, - }, - ]); + expect(Q.getActiveQuestion().error).toBe('INVALID_RATING'); }); - test('should only accept MULTI_SELECT options that match the first answer', () => { - answerAllQuestionsWithOption1(); - Q.saveAnswer('option 2'); + test('should ask for improvements after a bad rating', () => { + Q.saveAnswer(2); + expect(Q.getActiveQuestion().type).toBe('MULTI_SELECT'); - Q.saveAnswer('option 1'); - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); + Q.saveAnswer(['docs', 'api']); + Q.saveAnswer(true); - Q.saveAnswer(['option 3', 'option 4']); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); - expect(activeQuestion.defaultValue).toBe(false); + expect(Q.isComplete()).toBe(true); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: '2 / 5', children: [{ id: 2, value: ['Documentation', 'API'] }] }, + { id: 3, value: 'Yes' }, + ]); + }); - Q.saveAnswer(activeQuestion.defaultValue); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); + test('should skip the improvements after a good rating', () => { + Q.saveAnswer(5); + expect(Q.getActiveQuestion().type).toBe('BOOLEAN'); - expect(Q.getResult()).toEqual({ - foo: 'option 2', - bar: ['option 3', 'option 4'], - baz: false, - }); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'MULTI_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: ['Option 3', 'Option 4'], - }, - ], - value: 'Option 2', - }, - { - active: false, - componentType: 'BOOLEAN', - hasValue: false, - id: 3, - isValid: false, - name: 'Category 2', - subNavigation: [], - value: null, - }, - ]); + Q.saveAnswer(false); + expect(Q.getResult()).toEqual({ rating: 5, recommend: false }); }); }); diff --git a/examples/custom-component-types/data.ts b/examples/custom-component-types/data.ts index 185d21a..4800e2c 100644 --- a/examples/custom-component-types/data.ts +++ b/examples/custom-component-types/data.ts @@ -1,102 +1,45 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; -import { MyComponentType } from './MyQuaire'; +import type { QuaireNavigationDefinition } from '../../src'; +import type { MyQuestionDefinition } from './rating'; -export const items: Array = [ +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + type: 'RATING', + key: 'rating', + title: 'How do you like quaire?', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 2, - }, - ], + stars: 5, + next: [{ when: { rating: { lte: 2 } }, to: 2 }, { to: 3 }], }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: ['foo'], - componentType: MyComponentType.MULTI_SELECT, - question: 'Question 2', - description: 'Description 2', + type: 'MULTI_SELECT', + key: 'improvements', + title: 'What can we improve?', + navigationId: 2, required: true, - selectOptions: { - foo: { - 'option 1': [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 3, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 3, - }, - ], - 'option 2': [ - { - label: 'Option 3', - value: 'option 3', - nextItemId: 3, - }, - { - label: 'Option 4', - value: 'option 4', - nextItemId: 3, - }, - ], - }, - }, + options: [ + { label: 'Documentation', value: 'docs' }, + { label: 'Performance', value: 'performance' }, + { label: 'API', value: 'api' }, + ], + next: 3, }, { id: 3, - resultProperty: 'baz', - navigationItemId: 3, - dependsOnResultProperties: ['bar'], - componentType: MyComponentType.BOOLEAN, - question: 'Question 3', - description: 'Description 3', + type: 'BOOLEAN', + key: 'recommend', + title: 'Would you recommend quaire?', + navigationId: 3, required: true, - nextItemId: 1, - defaultValue: { - bar: { - 'option 1_option 2': true, - 'option 3_option 4': false, - 'option 1': false, - 'option 2': false, - }, - }, + trueLabel: 'Yes', + falseLabel: 'No', }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Rating' }, + { id: 2, parentId: 1, title: 'Improvements' }, + { id: 3, title: 'Recommendation' }, ]; diff --git a/examples/custom-component-types/rating.ts b/examples/custom-component-types/rating.ts new file mode 100644 index 0000000..e6c0508 --- /dev/null +++ b/examples/custom-component-types/rating.ts @@ -0,0 +1,17 @@ +import type { QuaireComponent, QuaireQuestionDefinition, QuaireQuestionDefinitionBase } from '../../src'; + +// a custom component type with its own properties +export type RatingDefinition = QuaireQuestionDefinitionBase<'RATING', { stars: number }>; + +// all built-in types plus the custom type +export type MyQuestionDefinition = QuaireQuestionDefinition | RatingDefinition; + +export const rating: QuaireComponent = { + // the answer must be a whole number between 1 and the number of stars + validate: (definition, value) => + typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= definition.stars + ? null + : 'INVALID_RATING', + // the navigation shows "4 / 5" instead of 4 + getDisplayValue: (definition, value) => `${value} / ${definition.stars}`, +}; diff --git a/examples/dependencies-between-questions/data.ts b/examples/dependencies-between-questions/data.ts index a625d3a..68e41f2 100644 --- a/examples/dependencies-between-questions/data.ts +++ b/examples/dependencies-between-questions/data.ts @@ -1,144 +1,53 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition, QuaireSelectOption } from '../../src'; -export const items: Array = [ +const options = (...values: Array): Array => + values.map((value) => ({ label: value.replace('option', 'Option'), value })); + +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 2, - }, - ], + options: options('option 1', 'option 2').map((option) => ({ ...option, next: 2 })), }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: ['foo'], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 2', - description: 'Description 2', + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Question 2', + navigationId: 2, required: true, - selectOptions: { - foo: { - 'option 1': [ - { - label: 'Option 1.1', - value: 'option 1.1', - nextItemId: 3, - }, - { - label: 'Option 1.2', - value: 'option 1.2', - nextItemId: 3, - }, - ], - 'option 2': [ - { - label: 'Option 2.1', - value: 'option 2.1', - nextItemId: 3, - }, - { - label: 'Option 2.2', - value: 'option 2.2', - nextItemId: 3, - }, - ], - }, - }, + options: [], + next: 3, + // the options depend on the answer to question 1 + variants: [ + { when: { foo: 'option 1' }, options: options('option 1.1', 'option 1.2') }, + { when: { foo: 'option 2' }, options: options('option 2.1', 'option 2.2') }, + ], }, { id: 3, - resultProperty: 'baz', - navigationItemId: 3, - dependsOnResultProperties: ['foo', 'bar'], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 3', - description: 'Description 3', + type: 'SINGLE_SELECT', + key: 'baz', + title: 'Question 3', + navigationId: 3, required: true, - selectOptions: { - foo: { - 'option 1': { - bar: { - 'option 1.1': [ - { - label: 'Option 1.1.1', - value: 'option 1.1.1', - }, - { - label: 'Option 1.1.2', - value: 'option 1.1.2', - }, - ], - 'option 1.2': [ - { - label: 'Option 1.2.1', - value: 'option 1.2.1', - }, - { - label: 'Option 1.2.2', - value: 'option 1.2.2', - }, - ], - }, - }, - 'option 2': { - bar: { - 'option 2.1': [ - { - label: 'Option 2.1.1', - value: 'option 2.1.1', - }, - { - label: 'Option 2.1.2', - value: 'option 2.1.2', - }, - ], - 'option 2.2': [ - { - label: 'Option 2.2.1', - value: 'option 2.2.1', - }, - { - label: 'Option 2.2.2', - value: 'option 2.2.2', - }, - ], - }, - }, - }, - }, + options: [], + // the options depend on the answers to question 1 and question 2 + variants: [ + { when: { foo: 'option 1', bar: 'option 1.1' }, options: options('option 1.1.1', 'option 1.1.2') }, + { when: { foo: 'option 1', bar: 'option 1.2' }, options: options('option 1.2.1', 'option 1.2.2') }, + { when: { foo: 'option 2', bar: 'option 2.1' }, options: options('option 2.1.1', 'option 2.1.2') }, + { when: { foo: 'option 2', bar: 'option 2.2' }, options: options('option 2.2.1', 'option 2.2.2') }, + ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1' }, + { id: 2, parentId: 1, title: 'Subcategory 1' }, + { id: 3, title: 'Category 2' }, ]; diff --git a/examples/dependencies-between-questions/dependencies-between-questions.spec.ts b/examples/dependencies-between-questions/dependencies-between-questions.spec.ts index 62547d1..8334f49 100644 --- a/examples/dependencies-between-questions/dependencies-between-questions.spec.ts +++ b/examples/dependencies-between-questions/dependencies-between-questions.spec.ts @@ -1,97 +1,31 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('dependencies-between-questions', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); - test('should show select options based on the previous answers', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.selectOptions).toEqual([ - { - label: 'Option 1', - nextItemId: 2, - value: 'option 1', - }, - { - label: 'Option 2', - nextItemId: 2, - value: 'option 2', - }, - ]); + const optionValues = () => { + const question = Q.getActiveQuestion(); - Q.saveAnswer('option 1'); + return question.type === 'SINGLE_SELECT' ? question.options.map((option) => option.value) : []; + }; - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.selectOptions).toEqual([ - { - label: 'Option 1.1', - value: 'option 1.1', - nextItemId: 3, - }, - { - label: 'Option 1.2', - value: 'option 1.2', - nextItemId: 3, - }, - ]); + test('should show the options based on the previous answers', () => { + expect(optionValues()).toEqual(['option 1', 'option 2']); - Q.saveAnswer('option 1.1'); + Q.saveAnswer('option 1'); + expect(optionValues()).toEqual(['option 1.1', 'option 1.2']); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.selectOptions).toEqual([ - { - label: 'Option 1.1.1', - value: 'option 1.1.1', - }, - { - label: 'Option 1.1.2', - value: 'option 1.1.2', - }, - ]); + Q.saveAnswer('option 1.1'); + expect(optionValues()).toEqual(['option 1.1.1', 'option 1.1.2']); Q.saveAnswer('option 1.1.1'); - - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'option 1.1', - baz: 'option 1.1.1', - }); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 1.1', - }, - ], - value: 'Option 1', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: 'Option 1.1.1', - }, - ]); + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ foo: 'option 1', bar: 'option 1.1', baz: 'option 1.1.1' }); }); test('should reset and invalidate dependent questions when the first answer changes', () => { @@ -99,89 +33,21 @@ describe('dependencies-between-questions', () => { Q.saveAnswer('option 1.1'); Q.saveAnswer('option 1.1.1'); - Q.setActiveQuestionByQuestionId(1); + Q.goTo(1); Q.saveAnswer('option 2'); - expect(Q.getResult()).toEqual({ - foo: 'option 2', - bar: null, - }); - expect(Q.isValid()).toBeFalsy(); - expect(Q.getValidationErrors()).toEqual({ - '2': 'REQUIRED', - }); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 2, - isValid: false, - name: 'Subcategory 1', - value: null, - }, - ], - value: 'Option 2', - }, - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 3, - isValid: false, - name: 'Category 2', - subNavigation: [], - value: null, - }, + expect(Q.getResult()).toEqual({ foo: 'option 2', bar: null, baz: null }); + expect(Q.isValid()).toBe(false); + expect(Q.getErrors()).toEqual({ '2': 'REQUIRED', '3': 'REQUIRED' }); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 2', isValid: false, children: [{ id: 2, value: null, active: true, isValid: false }] }, + { id: 3, value: null, isValid: false }, ]); Q.saveAnswer('option 2.2'); Q.saveAnswer('option 2.2.2'); - expect(Q.getResult()).toEqual({ - foo: 'option 2', - bar: 'option 2.2', - baz: 'option 2.2.2', - }); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 2.2', - }, - ], - value: 'Option 2', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: 'Option 2.2.2', - }, - ]); + expect(Q.getResult()).toEqual({ foo: 'option 2', bar: 'option 2.2', baz: 'option 2.2.2' }); + expect(Q.isValid()).toBe(true); }); }); diff --git a/examples/extending-data-definition/MyQuaire.ts b/examples/extending-data-definition/MyQuaire.ts deleted file mode 100644 index 5b17758..0000000 --- a/examples/extending-data-definition/MyQuaire.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { - Quaire, - QuaireInputItemOption, - QuaireItem, - QuaireItemOption, - QuaireNavigationItem, - QuaireQuestion, - QuaireRangeItemOption, - QuaireResult, -} from '../../src'; - -export type MyRangeItemOption = QuaireRangeItemOption & { - divisor: number; - unit: string; -}; - -export type MyItem = QuaireItem & { - progress: number; - rangeOption: MyRangeItemOption; -}; - -export type MyQuestion = QuaireQuestion & { - progress: number; - rangeOption: MyRangeItemOption; -}; - -export type MyNavigationItem = QuaireNavigationItem & { - progress?: number; - unit?: string; -}; - -export class MyQuaire extends Quaire { - protected _getQuestionObject( - item: MyItem, - dependsOnKeys: string[], - selectOptions: QuaireItemOption[], - rangeOption: QuaireRangeItemOption, - inputOption: QuaireInputItemOption, - defaultValue: unknown, - ): MyQuestion { - return { - ...super._getQuestionObject(item, dependsOnKeys, selectOptions, rangeOption, inputOption, defaultValue), - progress: item.progress, - }; - } - - protected _getNavigationItemObject( - activeNavigationItem: MyNavigationItem, - navigationItem: MyNavigationItem, - question: MyQuestion, - answer: unknown, - isParent: boolean, - ): MyNavigationItem { - return { - ...super._getNavigationItemObject(activeNavigationItem, navigationItem, question, answer, isParent), - progress: question.progress, - unit: question.rangeOption.unit, - }; - } -} diff --git a/examples/extending-data-definition/data.ts b/examples/extending-data-definition/data.ts index a515e65..96fce48 100644 --- a/examples/extending-data-definition/data.ts +++ b/examples/extending-data-definition/data.ts @@ -1,52 +1,46 @@ -import { QuaireComponentType } from '../../src'; -import { MyItem, MyNavigationItem } from './MyQuaire'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +// custom properties for all questions +export type MyQuestionDefinition = QuaireQuestionDefinition & { + progress: number; + unit?: string; +}; + +// custom properties for all navigation items +export type MyNavigationDefinition = QuaireNavigationDefinition & { + color: string; +}; + +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.RANGE_SLIDER, - question: 'Question 1', - description: 'Description 1', + type: 'RANGE', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, progress: 50, - rangeOption: { - range: [1, 100], - divisor: 10, - unit: '%', - nextItemId: 2, - }, + unit: '%', + min: 1, + max: 100, + next: 2, }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.RANGE_SLIDER, - question: 'Question 2', - description: 'Description 2', + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Question 2', + navigationId: 2, required: true, progress: 100, - rangeOption: { - range: [1, 5], - divisor: 100, - unit: 'km/h', - nextItemId: 1, - }, + options: [ + { label: 'Car', value: 'car', icon: 'car' }, // options can have custom properties, too + { label: 'Bike', value: 'bike', icon: 'bike' }, + ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1', color: 'blue' }, + { id: 2, parentId: 1, title: 'Subcategory 1', color: 'green' }, ]; diff --git a/examples/extending-data-definition/extending-data-definition.spec.ts b/examples/extending-data-definition/extending-data-definition.spec.ts index 80d560c..728fabc 100644 --- a/examples/extending-data-definition/extending-data-definition.spec.ts +++ b/examples/extending-data-definition/extending-data-definition.spec.ts @@ -1,59 +1,30 @@ -import { items, navigationItems } from './data'; -import { MyQuaire } from './MyQuaire'; +import { Quaire } from '../../src'; +import { MyNavigationDefinition, MyQuestionDefinition, navigation, questions } from './data'; describe('extending-data-definition', () => { - let Q: MyQuaire; + let Q: Quaire; beforeEach(() => { - Q = new MyQuaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); - test('should add custom properties to questions and navigation items', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - expect(activeQuestion.progress).toBe(50); - expect(activeQuestion.rangeOption.unit).toBe('%'); - expect(activeQuestion.rangeOption.divisor).toBe(10); + test('should add custom properties to questions', () => { + expect(Q.getActiveQuestion()).toMatchObject({ title: 'Question 1', progress: 50, unit: '%' }); Q.saveAnswer([20, 25]); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - expect(activeQuestion.progress).toBe(100); - expect(activeQuestion.rangeOption.unit).toBe('km/h'); - expect(activeQuestion.rangeOption.divisor).toBe(100); - - Q.saveAnswer([2, 5]); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - expect(Q.getResult()).toEqual({ - foo: [20, 25], - bar: [2, 5], - }); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'RANGE_SLIDER', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'RANGE_SLIDER', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: [2, 5], - progress: 100, - unit: 'km/h', - }, - ], - value: [20, 25], - progress: 50, - unit: '%', - }, - ]); + + const question = Q.getActiveQuestion(); + + expect(question.progress).toBe(100); + expect(question.type === 'SINGLE_SELECT' && question.options[0].icon).toBe('car'); + }); + + test('should add custom properties to navigation items', () => { + Q.saveAnswer([20, 25]); + + const [category] = Q.getNavigation(); + + expect(category).toMatchObject({ color: 'blue', value: [20, 25], question: { progress: 50, unit: '%' } }); + expect(category.children[0]).toMatchObject({ color: 'green', question: { progress: 100 } }); }); }); diff --git a/examples/linear-flow-skip-question/data.ts b/examples/linear-flow-skip-question/data.ts index b62f1ff..3e1b79b 100644 --- a/examples/linear-flow-skip-question/data.ts +++ b/examples/linear-flow-skip-question/data.ts @@ -1,86 +1,46 @@ -import { NO_VALUE, QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import { NO_VALUE } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 3, - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 2 }, + { label: 'Option 2', value: 'option 2', next: 3 }, // skips question 2 ], }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 2', - description: 'Description 2', - required: false, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 3, - }, - { - label: 'Skip', - value: NO_VALUE, - nextItemId: 3, - }, + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Question 2', + navigationId: 2, + options: [ + { label: 'Option 1', value: 'option 1', next: 3 }, + { label: 'Skip', value: NO_VALUE, next: 3 }, ], }, { id: 3, - resultProperty: 'baz', - navigationItemId: 3, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 3', - description: 'Description 3', + type: 'SINGLE_SELECT', + key: 'baz', + title: 'Question 3', + navigationId: 3, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - }, - { - label: 'Option 2', - value: 'option 2', - }, + options: [ + { label: 'Option 1', value: 'option 1' }, + { label: 'Option 2', value: 'option 2' }, ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1' }, + { id: 2, parentId: 1, title: 'Subcategory 1' }, + { id: 3, title: 'Category 2' }, ]; diff --git a/examples/linear-flow-skip-question/linear-flow-skip-question.spec.ts b/examples/linear-flow-skip-question/linear-flow-skip-question.spec.ts index c223b3f..18cc8dc 100644 --- a/examples/linear-flow-skip-question/linear-flow-skip-question.spec.ts +++ b/examples/linear-flow-skip-question/linear-flow-skip-question.spec.ts @@ -1,122 +1,36 @@ import { NO_VALUE, Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('linear-flow-skip-question', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); test('should skip question 2 when option 2 is chosen', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - Q.saveAnswer('option 2'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); + expect(Q.getActiveQuestion().title).toBe('Question 3'); Q.saveAnswer('option 1'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); - - expect(Q.getResult()).toEqual({ - foo: 'option 2', - baz: 'option 1', - }); - - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - value: 'Option 2', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: null, - }, - ], - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - value: 'Option 1', - subNavigation: [], - }, + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ foo: 'option 2', baz: 'option 1' }); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 2', children: [{ id: 2, value: null, hasValue: false, reachable: false }] }, + { id: 3, value: 'Option 1' }, ]); }); test('should save NO_VALUE when question 2 is skipped', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - Q.saveAnswer('option 1'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - Q.saveAnswer(NO_VALUE); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); + expect(Q.getActiveQuestion().title).toBe('Question 3'); Q.saveAnswer('option 1'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); - - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'NO_VALUE', - baz: 'option 1', - }); - - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - value: 'Option 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'NO_VALUE', // indicator that this question was answered with an "empty" value - }, - ], - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - value: 'Option 1', - subNavigation: [], - }, + expect(Q.getResult()).toEqual({ foo: 'option 1', bar: NO_VALUE, baz: 'option 1' }); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 1', children: [{ id: 2, value: NO_VALUE, hasValue: true, reachable: true }] }, + { id: 3, value: 'Option 1' }, ]); }); }); diff --git a/examples/linear-flow-with-loop/data.ts b/examples/linear-flow-with-loop/data.ts index 92814d6..dd47ffd 100644 --- a/examples/linear-flow-with-loop/data.ts +++ b/examples/linear-flow-with-loop/data.ts @@ -1,87 +1,46 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 2, - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 2 }, + { label: 'Option 2', value: 'option 2', next: 2 }, ], }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 2', - description: 'Description 2', + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Question 2', + navigationId: 2, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 3, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 3, - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 3 }, + { label: 'Option 2', value: 'option 2', next: 3 }, ], }, { id: 3, - resultProperty: 'baz', - navigationItemId: 3, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 3', - description: 'Description 3', + type: 'SINGLE_SELECT', + key: 'baz', + title: 'Question 3', + navigationId: 3, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 1, - }, + options: [ + { label: 'Option 1', value: 'option 1' }, + { label: 'Option 2', value: 'option 2', next: 1 }, // back to the first question ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1' }, + { id: 2, parentId: 1, title: 'Subcategory 1' }, + { id: 3, title: 'Category 2' }, ]; diff --git a/examples/linear-flow-with-loop/linear-flow-with-loop.spec.ts b/examples/linear-flow-with-loop/linear-flow-with-loop.spec.ts index b920716..cda6836 100644 --- a/examples/linear-flow-with-loop/linear-flow-with-loop.spec.ts +++ b/examples/linear-flow-with-loop/linear-flow-with-loop.spec.ts @@ -1,69 +1,38 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('linear-flow-with-loop', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); test('should go back to question 1 after the last question', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - Q.saveAnswer('option 1'); - - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); - + Q.saveAnswer('option 2'); Q.saveAnswer('option 2'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); + expect(Q.getActiveQuestion().title).toBe('Question 1'); + expect(Q.getResult()).toEqual({ foo: 'option 1', bar: 'option 2', baz: 'option 2' }); + expect(Q.isComplete()).toBe(false); + }); + test('should keep the answers when the loop starts again', () => { + Q.saveAnswer('option 1'); + Q.saveAnswer('option 2'); + Q.saveAnswer('option 2'); Q.saveAnswer('option 2'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); + expect(Q.getActiveQuestion().title).toBe('Question 2'); + expect(Q.getResult()).toEqual({ foo: 'option 2', bar: 'option 2', baz: 'option 2' }); + }); - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'option 2', - baz: 'option 2', - }); + test('should complete the flow with option 1 of the last question', () => { + Q.saveAnswer('option 1'); + Q.saveAnswer('option 2'); + Q.saveAnswer('option 1'); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - value: 'Option 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 2', - }, - ], - }, - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - value: 'Option 2', - subNavigation: [], - }, - ]); + expect(Q.isComplete()).toBe(true); }); }); diff --git a/examples/linear-flow/data.ts b/examples/linear-flow/data.ts index 19fdcd9..17f4ab3 100644 --- a/examples/linear-flow/data.ts +++ b/examples/linear-flow/data.ts @@ -1,86 +1,46 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +export const questions: Array = [ { id: 1, - resultProperty: 'foo', - navigationItemId: 1, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Question 1', + navigationId: 1, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 2, - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 2 }, + { label: 'Option 2', value: 'option 2', next: 2 }, ], }, { id: 2, - resultProperty: 'bar', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 2', - description: 'Description 2', + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Question 2', + navigationId: 2, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 3, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 3, - }, + options: [ + { label: 'Option 1', value: 'option 1', next: 3 }, + { label: 'Option 2', value: 'option 2', next: 3 }, ], }, { id: 3, - resultProperty: 'baz', - navigationItemId: 3, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 3', - description: 'Description 3', + type: 'SINGLE_SELECT', + key: 'baz', + title: 'Question 3', + navigationId: 3, required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - }, - { - label: 'Option 2', - value: 'option 2', - }, + options: [ + { label: 'Option 1', value: 'option 1' }, + { label: 'Option 2', value: 'option 2' }, ], }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: null, - name: 'Category 2', - }, +export const navigation: Array = [ + { id: 1, title: 'Category 1' }, + { id: 2, parentId: 1, title: 'Subcategory 1' }, + { id: 3, title: 'Category 2' }, ]; diff --git a/examples/linear-flow/linear-flow.spec.ts b/examples/linear-flow/linear-flow.spec.ts index 494955f..883faa3 100644 --- a/examples/linear-flow/linear-flow.spec.ts +++ b/examples/linear-flow/linear-flow.spec.ts @@ -1,74 +1,36 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('linear-flow', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); - }); - - test('should stay on the question when the answer is not a valid option', () => { - Q.saveAnswer('option 4'); - - expect(Q.getActiveQuestion().question).toBe('Question 1'); - expect(Q.getResult()).toEqual({ foo: null }); - expect(Q.getValidationErrors()).toEqual({ '1': 'REQUIRED', '2': 'REQUIRED', '3': 'REQUIRED' }); + Q = new Quaire({ questions, navigation }); }); test('should go through all questions in order', () => { - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); + expect(Q.getActiveQuestion().title).toBe('Question 1'); Q.saveAnswer('option 1'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 2'); + expect(Q.getActiveQuestion().title).toBe('Question 2'); Q.saveAnswer('option 2'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); + expect(Q.getActiveQuestion().title).toBe('Question 3'); Q.saveAnswer('option 1'); - activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 3'); + expect(Q.getActiveQuestion().title).toBe('Question 3'); + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ foo: 'option 1', bar: 'option 2', baz: 'option 1' }); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 1', active: false, children: [{ id: 2, value: 'Option 2', active: false }] }, + { id: 3, value: 'Option 1', active: true, children: [] }, + ]); + }); - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'option 2', - baz: 'option 1', - }); + test('should stay on the question when the answer is not a valid option', () => { + Q.saveAnswer('option 4'); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - value: 'Option 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 2', - }, - ], - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - value: 'Option 1', - subNavigation: [], - }, - ]); + expect(Q.getActiveQuestion().title).toBe('Question 1'); + expect(Q.getErrors()).toEqual({ '1': 'INVALID_OPTION' }); }); }); diff --git a/examples/navigation/data.ts b/examples/navigation/data.ts index 7d737f4..5d81aaf 100644 --- a/examples/navigation/data.ts +++ b/examples/navigation/data.ts @@ -1,97 +1,50 @@ -import { QuaireComponentType, QuaireItem, QuaireNavigationItem } from '../../src'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from '../../src'; -export const items: Array = [ +export const questions: Array = [ { id: 1, - resultProperty: 'name', - navigationItemId: 2, - dependsOnResultProperties: [], - componentType: QuaireComponentType.INPUT, - question: 'What is your name?', - description: '', + type: 'INPUT', + key: 'name', + title: 'What is your name?', + navigationId: 2, required: true, - inputOption: { - type: 'text', - nextItemId: 2, - }, + next: 2, }, { id: 2, - resultProperty: 'age', - navigationItemId: 3, - dependsOnResultProperties: [], - componentType: QuaireComponentType.INPUT, - question: 'How old are you?', - description: '', - required: false, - inputOption: { - type: 'number', - nextItemId: 3, - }, + type: 'INPUT', + key: 'age', + title: 'How old are you?', + navigationId: 3, + inputType: 'number', + next: 3, }, { id: 3, - resultProperty: 'contact', - navigationItemId: 4, - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'How should we contact you?', - description: '', + type: 'SINGLE_SELECT', + key: 'contact', + title: 'How should we contact you?', + navigationId: 4, required: true, - selectOptions: [ - { - label: 'E-Mail', - value: 'email', - nextItemId: 4, - }, - { - label: 'Phone', - value: 'phone', - nextItemId: 4, - }, + options: [ + { label: 'E-Mail', value: 'email', next: 4 }, + { label: 'Phone', value: 'phone', next: 4 }, ], }, { id: 4, - resultProperty: 'contactDetails', - navigationItemId: 5, - dependsOnResultProperties: [], - componentType: QuaireComponentType.INPUT, - question: 'Where can we reach you?', - description: '', + type: 'INPUT', + key: 'contactDetails', + title: 'Where can we reach you?', + navigationId: 5, required: true, - inputOption: { - type: 'text', - }, }, ]; -export const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Personal', // has no own question, only children - icon: 'user', - }, - { - id: 2, - parentId: 1, - name: 'Name', - }, - { - id: 3, - parentId: 1, - name: 'Age', - }, - { - id: 4, - parentId: null, - name: 'Contact', // has an own question and children - icon: 'phone', - }, - { - id: 5, - parentId: 4, - name: 'Details', - }, +export const navigation: Array = [ + { id: 1, title: 'Personal', icon: 'user' }, // has no own question, only children + { id: 2, parentId: 1, title: 'Name' }, + { id: 3, parentId: 1, title: 'Age' }, + { id: 4, title: 'Contact', icon: 'phone' }, // has an own question and children + { id: 5, parentId: 4, title: 'Details' }, ]; diff --git a/examples/navigation/navigation.spec.ts b/examples/navigation/navigation.spec.ts index 75ae539..59cac49 100644 --- a/examples/navigation/navigation.spec.ts +++ b/examples/navigation/navigation.spec.ts @@ -1,11 +1,11 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from './data'; +import { navigation, questions } from './data'; describe('navigation', () => { let Q: Quaire; beforeEach(() => { - Q = new Quaire({ items, navigationItems }); + Q = new Quaire({ questions, navigation }); }); const answerAllQuestions = () => { @@ -16,60 +16,31 @@ describe('navigation', () => { }; test('should show the initial navigation with categories and subcategories', () => { - expect(Q.getNavigation()).toEqual([ + expect(Q.getNavigation()).toMatchObject([ { id: 1, - name: 'Personal', - value: null, + title: 'Personal', icon: 'user', + question: null, + value: null, active: true, isValid: false, hasValue: false, - componentType: null, - subNavigation: [ - { - id: 2, - name: 'Name', - value: null, - icon: undefined, - active: true, - isValid: false, - hasValue: false, - componentType: 'INPUT', - }, - { - id: 3, - name: 'Age', - value: null, - icon: undefined, - active: false, - isValid: true, - hasValue: false, - componentType: 'INPUT', - }, + reachable: true, + children: [ + { id: 2, title: 'Name', active: true, isValid: false, hasValue: false, reachable: true }, + { id: 3, title: 'Age', active: false, isValid: true, hasValue: false, reachable: true }, ], }, { id: 4, - name: 'Contact', - value: null, + title: 'Contact', icon: 'phone', active: false, isValid: false, hasValue: false, - componentType: 'SINGLE_SELECT', - subNavigation: [ - { - id: 5, - name: 'Details', - value: null, - icon: undefined, - active: false, - isValid: false, - hasValue: false, - componentType: 'INPUT', - }, - ], + reachable: true, + children: [{ id: 5, title: 'Details', isValid: false, reachable: true }], }, ]); }); @@ -77,61 +48,23 @@ describe('navigation', () => { test('should show the answers in the navigation', () => { answerAllQuestions(); - expect(Q.isValid()).toBe(true); - expect(Q.getNavigation()).toEqual([ + expect(Q.isComplete()).toBe(true); + expect(Q.getNavigation()).toMatchObject([ { id: 1, - name: 'Personal', value: null, - icon: 'user', - active: false, isValid: true, hasValue: true, - componentType: null, - subNavigation: [ - { - id: 2, - name: 'Name', - value: 'Jane', - icon: undefined, - active: false, - isValid: true, - hasValue: true, - componentType: 'INPUT', - }, - { - id: 3, - name: 'Age', - value: 42, - icon: undefined, - active: false, - isValid: true, - hasValue: true, - componentType: 'INPUT', - }, + children: [ + { id: 2, value: 'Jane' }, + { id: 3, value: 42 }, ], }, { id: 4, - name: 'Contact', value: 'E-Mail', // label of the selected option - icon: 'phone', active: true, - isValid: true, - hasValue: true, - componentType: 'SINGLE_SELECT', - subNavigation: [ - { - id: 5, - name: 'Details', - value: 'jane@example.com', - icon: undefined, - active: true, - isValid: true, - hasValue: true, - componentType: 'INPUT', - }, - ], + children: [{ id: 5, value: 'jane@example.com', active: true }], }, ]); }); @@ -140,30 +73,25 @@ describe('navigation', () => { answerAllQuestions(); // category without own question: jumps to the first subcategory - Q.setActiveQuestionByNavigationItemId(1); - expect(Q.getActiveQuestion().question).toBe('What is your name?'); + Q.goToNavigationItem(1); + expect(Q.getActiveQuestion().title).toBe('What is your name?'); // category with own question - Q.setActiveQuestionByNavigationItemId(4); - expect(Q.getActiveQuestion().question).toBe('How should we contact you?'); + Q.goToNavigationItem(4); + expect(Q.getActiveQuestion().title).toBe('How should we contact you?'); // subcategory - Q.setActiveQuestionByNavigationItemId(3); - expect(Q.getActiveQuestion().question).toBe('How old are you?'); + Q.goToNavigationItem(3); + expect(Q.getActiveQuestion().title).toBe('How old are you?'); }); test('should continue with the next question after changing an answer', () => { answerAllQuestions(); - Q.setActiveQuestionByQuestionId(1); + Q.goTo(1); Q.saveAnswer('John'); - expect(Q.getActiveQuestion().question).toBe('How old are you?'); - expect(Q.getResult()).toEqual({ - name: 'John', - age: 42, - contact: 'email', - contactDetails: 'jane@example.com', - }); + expect(Q.getActiveQuestion().title).toBe('How old are you?'); + expect(Q.getResult()).toEqual({ name: 'John', age: 42, contact: 'email', contactDetails: 'jane@example.com' }); }); }); diff --git a/examples/restore-state/restore-state.spec.ts b/examples/restore-state/restore-state.spec.ts index 908d1fc..404f25e 100644 --- a/examples/restore-state/restore-state.spec.ts +++ b/examples/restore-state/restore-state.spec.ts @@ -1,161 +1,49 @@ import { Quaire } from '../../src'; -import { items, navigationItems } from '../dependencies-between-questions/data'; +import { navigation, questions } from '../dependencies-between-questions/data'; describe('restore-state', () => { test('should restore the state from a complete result', () => { const Q = new Quaire({ - items, - navigationItems, + questions, + navigation, result: { foo: 'option 1', bar: 'option 1.2', baz: 'option 1.2.1' }, }); - expect(Q.getActiveQuestion().selectOptions).toEqual([ - { - label: 'Option 1.2.1', - value: 'option 1.2.1', - }, - { - label: 'Option 1.2.2', - value: 'option 1.2.2', - }, - ]); - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'option 1.2', - baz: 'option 1.2.1', - }); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 1.2', - }, - ], - value: 'Option 1', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 3, - isValid: true, - name: 'Category 2', - subNavigation: [], - value: 'Option 1.2.1', - }, + expect(Q.getActiveQuestion().title).toBe('Question 3'); + expect(Q.isComplete()).toBe(true); + expect(Q.getNavigation()).toMatchObject([ + { id: 1, value: 'Option 1', children: [{ id: 2, value: 'Option 1.2' }] }, + { id: 3, value: 'Option 1.2.1', active: true }, ]); }); - test('should restore the state from a partial result', () => { - const Q = new Quaire({ items, navigationItems, result: { foo: 'option 1', bar: 'option 1.2' } }); + test('should continue with the first open question of a partial result', () => { + const Q = new Quaire({ questions, navigation, result: { foo: 'option 1', bar: 'option 1.2' } }); - expect(Q.getActiveQuestion().selectOptions).toEqual([ - { - label: 'Option 1.2.1', - value: 'option 1.2.1', - }, - { - label: 'Option 1.2.2', - value: 'option 1.2.2', - }, - ]); - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: 'option 1.2', + expect(Q.getActiveQuestion()).toMatchObject({ + title: 'Question 3', + options: [ + { label: 'Option 1.2.1', value: 'option 1.2.1' }, + { label: 'Option 1.2.2', value: 'option 1.2.2' }, + ], }); - expect(Q.getNavigation()).toEqual([ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 1, - isValid: true, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: true, - id: 2, - isValid: true, - name: 'Subcategory 1', - value: 'Option 1.2', - }, - ], - value: 'Option 1', - }, - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 3, - isValid: false, - name: 'Category 2', - subNavigation: [], - value: null, - }, - ]); + expect(Q.canGoBack()).toBe(true); + + Q.back(); + expect(Q.getActiveQuestion().title).toBe('Question 2'); + }); + + test('should continue with an invalid answer', () => { + const Q = new Quaire({ questions, navigation, result: { foo: 'option 1', bar: 'option 2.1' } }); + + expect(Q.getActiveQuestion().title).toBe('Question 2'); + expect(Q.getActiveQuestion().error).toBe('INVALID_OPTION'); }); test('should start at question 1 with an empty result', () => { - const Q = new Quaire({ items, navigationItems, result: {} }); + const Q = new Quaire({ questions, navigation, result: {} }); - expect(Q.getActiveQuestion().selectOptions).toEqual([ - { - label: 'Option 1', - nextItemId: 2, - value: 'option 1', - }, - { - label: 'Option 2', - nextItemId: 2, - value: 'option 2', - }, - ]); - expect(Q.getResult()).toEqual({}); - expect(Q.getNavigation()).toEqual([ - { - active: true, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 1, - isValid: false, - name: 'Category 1', - subNavigation: [ - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 2, - isValid: false, - name: 'Subcategory 1', - value: null, - }, - ], - value: null, - }, - { - active: false, - componentType: 'SINGLE_SELECT', - hasValue: false, - id: 3, - isValid: false, - name: 'Category 2', - subNavigation: [], - value: null, - }, - ]); + expect(Q.getActiveQuestion().title).toBe('Question 1'); + expect(Q.canGoBack()).toBe(false); }); }); diff --git a/examples/validation/data.ts b/examples/validation/data.ts new file mode 100644 index 0000000..7b5e331 --- /dev/null +++ b/examples/validation/data.ts @@ -0,0 +1,63 @@ +import type { QuaireQuestionDefinition } from '../../src'; + +export const questions: Array = [ + { + id: 1, + type: 'INPUT', + key: 'email', + title: 'What is your e-mail address?', + inputType: 'email', + required: true, + pattern: '^[^@\\s]+@[^@\\s]+$', + next: 2, + }, + { + id: 2, + type: 'INPUT', + key: 'username', + title: 'Choose a username', + required: true, + minLength: 3, + maxLength: 12, + // custom validators run after the built-in checks and return their own error codes + validate: (value) => (value === 'admin' ? 'RESERVED' : null), + next: 3, + }, + { + id: 3, + type: 'INPUT', + key: 'age', + title: 'How old are you?', + inputType: 'number', + min: 18, + max: 120, + next: 4, + }, + { + id: 4, + type: 'MULTI_SELECT', + key: 'topics', + title: 'Choose one or two topics', + required: true, + minSelected: 1, + maxSelected: 2, + options: [ + { label: 'News', value: 'news' }, + { label: 'Sports', value: 'sports' }, + { label: 'Tech', value: 'tech' }, + ], + }, +]; + +// map error codes to messages in your view +export const messages: Record = { + REQUIRED: 'Please answer this question.', + PATTERN: 'Please enter a valid e-mail address.', + MIN_LENGTH: 'Please use at least 3 characters.', + MAX_LENGTH: 'Please use at most 12 characters.', + RESERVED: 'This username is reserved.', + MIN: 'You must be at least 18 years old.', + MAX: 'Please check your age.', + TOO_FEW: 'Please choose at least one topic.', + TOO_MANY: 'Please choose at most two topics.', +}; diff --git a/examples/validation/validation.spec.ts b/examples/validation/validation.spec.ts new file mode 100644 index 0000000..d39cb26 --- /dev/null +++ b/examples/validation/validation.spec.ts @@ -0,0 +1,67 @@ +import { Quaire } from '../../src'; +import { messages, questions } from './data'; + +describe('validation', () => { + let Q: Quaire; + + beforeEach(() => { + Q = new Quaire({ questions }); + }); + + const error = () => messages[Q.getActiveQuestion().error]; + + test('should require an answer', () => { + expect(error()).toBe('Please answer this question.'); + expect(Q.isValid()).toBe(false); + }); + + test('should stay on the question until the answer is valid', () => { + Q.saveAnswer('not an e-mail'); + expect(error()).toBe('Please enter a valid e-mail address.'); + expect(Q.getActiveQuestion().id).toBe(1); + + Q.saveAnswer('jane@example.com'); + expect(Q.getActiveQuestion().id).toBe(2); + }); + + test('should check the length and run custom validators', () => { + Q.saveAnswer('jane@example.com'); + + Q.saveAnswer('jo'); + expect(error()).toBe('Please use at least 3 characters.'); + + Q.saveAnswer('a-very-long-username'); + expect(error()).toBe('Please use at most 12 characters.'); + + Q.saveAnswer('admin'); + expect(error()).toBe('This username is reserved.'); + + Q.saveAnswer('jane'); + expect(Q.getActiveQuestion().id).toBe(3); + }); + + test('should check numbers and the number of selected options', () => { + Q.saveAnswer('jane@example.com'); + Q.saveAnswer('jane'); + + Q.saveAnswer(16); + expect(error()).toBe('You must be at least 18 years old.'); + + Q.saveAnswer(30); + Q.saveAnswer(['news', 'sports', 'tech']); + expect(error()).toBe('Please choose at most two topics.'); + + Q.saveAnswer(['tech']); + expect(Q.isValid()).toBe(true); + expect(Q.isComplete()).toBe(true); + }); + + test('should skip optional questions', () => { + Q.saveAnswer('jane@example.com'); + Q.saveAnswer('jane'); + Q.saveAnswer(null); + + expect(Q.getActiveQuestion().id).toBe(4); + expect(Q.getResult()).toEqual({ email: 'jane@example.com', username: 'jane', age: null }); + }); +}); diff --git a/examples/wizard/data.ts b/examples/wizard/data.ts new file mode 100644 index 0000000..ecc6bb1 --- /dev/null +++ b/examples/wizard/data.ts @@ -0,0 +1,40 @@ +import type { QuaireQuestionDefinition } from '../../src'; + +export const questions: Array = [ + { + id: 1, + type: 'SINGLE_SELECT', + key: 'size', + title: 'Which size do you need?', + required: true, + options: [ + { label: 'Small', value: 's' }, + { label: 'Medium', value: 'm' }, + { label: 'Large', value: 'l' }, + ], + next: 2, + }, + { + id: 2, + type: 'BOOLEAN', + key: 'gift', + title: 'Is it a gift?', + required: true, + next: [{ when: { gift: true }, to: 3 }, { to: 4 }], + }, + { + id: 3, + type: 'INPUT', + key: 'message', + title: 'Your gift message', + maxLength: 200, + next: 4, + }, + { + id: 4, + type: 'INPUT', + key: 'address', + title: 'Where should we send it?', + required: true, + }, +]; diff --git a/examples/wizard/wizard.spec.ts b/examples/wizard/wizard.spec.ts new file mode 100644 index 0000000..ba5f383 --- /dev/null +++ b/examples/wizard/wizard.spec.ts @@ -0,0 +1,69 @@ +import { Quaire } from '../../src'; +import { questions } from './data'; + +describe('wizard', () => { + let Q: Quaire; + + beforeEach(() => { + Q = new Quaire({ questions }); + }); + + test('should show the progress', () => { + expect(Q.getProgress()).toEqual({ answered: 0, total: 3 }); + + Q.saveAnswer('m'); + Q.saveAnswer(true); + + // the total grows when the gift message is added to the path + expect(Q.getProgress()).toEqual({ answered: 2, total: 4 }); + }); + + test('should go back and forward', () => { + Q.saveAnswer('m'); + Q.saveAnswer(false); + expect(Q.getActiveQuestion().id).toBe(4); + + Q.back(); + expect(Q.getActiveQuestion().id).toBe(2); + + Q.saveAnswer(true); + expect(Q.getActiveQuestion().id).toBe(3); + + Q.back(); + Q.back(); + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.canGoBack()).toBe(false); + }); + + test('should complete the wizard', () => { + Q.saveAnswer('l'); + Q.saveAnswer(true); + Q.saveAnswer('Happy birthday!'); + expect(Q.isComplete()).toBe(false); + + Q.saveAnswer('Main Street 1'); + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ size: 'l', gift: true, message: 'Happy birthday!', address: 'Main Street 1' }); + }); + + test('should start again', () => { + Q.saveAnswer('l'); + Q.reset(); + + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.getResult()).toEqual({}); + }); + + test('should notify the view about every change', () => { + const states: Array = []; + const unsubscribe = Q.subscribe((state) => states.push(state.progress.answered)); + + Q.saveAnswer('s'); + Q.saveAnswer(false); + Q.back(); + unsubscribe(); + Q.back(); + + expect(states).toEqual([1, 2, 2]); + }); +}); diff --git a/src/components.spec.ts b/src/components.spec.ts new file mode 100644 index 0000000..d5426b2 --- /dev/null +++ b/src/components.spec.ts @@ -0,0 +1,138 @@ +import { defaultComponents } from './components.js'; +import { QuaireErrorCode } from './constants.js'; +import type { QuaireResolvedDefinition, QuaireQuestionDefinition } from './types.js'; + +describe('defaultComponents', () => { + const options = [ + { label: 'A', value: 'a', next: 2 }, + { label: 'B', value: 'b', next: 3 }, + { label: 'C', value: 'c' }, + ]; + + const definition = (properties: Record) => + ({ + id: 1, + key: 'foo', + title: 'Foo', + ...properties, + }) as unknown as QuaireResolvedDefinition; + + describe('SINGLE_SELECT', () => { + const { validate, getNext, getDisplayValue } = defaultComponents.SINGLE_SELECT; + const select = definition({ type: 'SINGLE_SELECT', options }); + + test('should only accept option values', () => { + expect(validate(select, 'a')).toBeNull(); + expect(validate(select, 'x')).toBe(QuaireErrorCode.INVALID_OPTION); + }); + + test('should use the next question of the selected option', () => { + expect(getNext(select, 'b')).toBe(3); + expect(getNext(select, 'c')).toBeUndefined(); + }); + + test('should use the next question of all options for unanswered questions', () => { + const sameNext = definition({ + type: 'SINGLE_SELECT', + options: options.map((option) => ({ ...option, next: 2 })), + }); + + expect(getNext(sameNext, undefined)).toBe(2); + expect(getNext(select, undefined)).toBeUndefined(); + }); + + test('should show the label of the selected option', () => { + expect(getDisplayValue(select, 'a')).toBe('A'); + expect(getDisplayValue(select, 'x')).toBeUndefined(); + }); + }); + + describe('MULTI_SELECT', () => { + const { validate, getNext, getDisplayValue } = defaultComponents.MULTI_SELECT; + const select = definition({ type: 'MULTI_SELECT', options, minSelected: 1, maxSelected: 2 }); + + test('should validate the selected values', () => { + expect(validate(select, ['a', 'b'])).toBeNull(); + expect(validate(select, 'a')).toBe(QuaireErrorCode.INVALID_TYPE); + expect(validate(select, ['a', 'x'])).toBe(QuaireErrorCode.INVALID_OPTION); + expect(validate(select, ['a', 'b', 'c'])).toBe(QuaireErrorCode.TOO_MANY); + expect(validate(definition({ type: 'MULTI_SELECT', options, minSelected: 2 }), ['a'])).toBe( + QuaireErrorCode.TOO_FEW, + ); + expect(validate(definition({ type: 'MULTI_SELECT', options }), ['a', 'b', 'c'])).toBeNull(); + }); + + test('should use the first selected option with a next question', () => { + expect(getNext(select, ['c', 'b'])).toBe(3); + expect(getNext(select, ['c'])).toBeUndefined(); + expect(getNext(select, undefined)).toBeUndefined(); + }); + + test('should show the labels of the selected options', () => { + expect(getDisplayValue(select, ['b', 'a'])).toEqual(['A', 'B']); + expect(getDisplayValue(select, 'a')).toBeUndefined(); + }); + }); + + describe('BOOLEAN', () => { + const { validate, getDisplayValue } = defaultComponents.BOOLEAN; + const boolean = definition({ type: 'BOOLEAN', trueLabel: 'Yes', falseLabel: 'No' }); + + test('should only accept booleans', () => { + expect(validate(boolean, false)).toBeNull(); + expect(validate(boolean, 'yes')).toBe(QuaireErrorCode.INVALID_TYPE); + }); + + test('should show the labels', () => { + expect(getDisplayValue(boolean, true)).toBe('Yes'); + expect(getDisplayValue(boolean, false)).toBe('No'); + }); + }); + + describe('INPUT', () => { + const { validate } = defaultComponents.INPUT; + + test('should validate numbers', () => { + const input = definition({ type: 'INPUT', min: 1, max: 10 }); + + expect(validate(input, 5)).toBeNull(); + expect(validate(input, 0)).toBe(QuaireErrorCode.MIN); + expect(validate(input, 11)).toBe(QuaireErrorCode.MAX); + expect(validate(definition({ type: 'INPUT' }), 100)).toBeNull(); + }); + + test('should validate strings', () => { + const input = definition({ type: 'INPUT', minLength: 2, maxLength: 5, pattern: '^[a-z]+$' }); + + expect(validate(input, 'abc')).toBeNull(); + expect(validate(input, 'a')).toBe(QuaireErrorCode.MIN_LENGTH); + expect(validate(input, 'abcdef')).toBe(QuaireErrorCode.MAX_LENGTH); + expect(validate(input, 'ABC')).toBe(QuaireErrorCode.PATTERN); + expect(validate(definition({ type: 'INPUT' }), 'anything')).toBeNull(); + }); + + test('should only accept strings and numbers', () => { + expect(validate(definition({ type: 'INPUT' }), true)).toBe(QuaireErrorCode.INVALID_TYPE); + }); + }); + + describe('RANGE', () => { + const { validate } = defaultComponents.RANGE; + const range = definition({ type: 'RANGE', min: 0, max: 100 }); + + test('should accept a number or a [from, to] tuple', () => { + expect(validate(range, 50)).toBeNull(); + expect(validate(range, [20, 80])).toBeNull(); + }); + + test('should reject other values', () => { + expect(validate(range, [1, 2, 3])).toBe(QuaireErrorCode.INVALID_TYPE); + expect(validate(range, '50')).toBe(QuaireErrorCode.INVALID_TYPE); + }); + + test('should check the limits', () => { + expect(validate(range, [-1, 50])).toBe(QuaireErrorCode.MIN); + expect(validate(range, 101)).toBe(QuaireErrorCode.MAX); + }); + }); +}); diff --git a/src/components.ts b/src/components.ts new file mode 100644 index 0000000..efd19ca --- /dev/null +++ b/src/components.ts @@ -0,0 +1,128 @@ +import { QuaireComponentType, QuaireErrorCode } from './constants.js'; +import type { + QuaireBooleanDefinition, + QuaireComponent, + QuaireComponents, + QuaireInputDefinition, + QuaireMultiSelectDefinition, + QuaireRangeDefinition, + QuaireSelectOption, + QuaireSingleSelectDefinition, +} from './types.js'; +import { hasValue } from './utils.js'; + +const findOption = (options: Array, value: unknown) => + options.find((option) => option.value === value); + +// an unanswered select question has a next question only if all options lead to the same question +const getCommonNext = (options: Array) => { + const nextIds = new Set(options.map((option) => String(option.next))); + + return nextIds.size === 1 ? options[0].next : undefined; +}; + +const singleSelect: QuaireComponent = { + validate: (definition, value) => (findOption(definition.options, value) ? null : QuaireErrorCode.INVALID_OPTION), + getNext: (definition, value) => + hasValue(value) ? findOption(definition.options, value)?.next : getCommonNext(definition.options), + getDisplayValue: (definition, value) => findOption(definition.options, value)?.label, +}; + +const multiSelect: QuaireComponent = { + validate: (definition, value) => { + if (!Array.isArray(value)) { + return QuaireErrorCode.INVALID_TYPE; + } + + if (!value.every((item) => findOption(definition.options, item))) { + return QuaireErrorCode.INVALID_OPTION; + } + + if (definition.minSelected !== undefined && value.length < definition.minSelected) { + return QuaireErrorCode.TOO_FEW; + } + + if (definition.maxSelected !== undefined && value.length > definition.maxSelected) { + return QuaireErrorCode.TOO_MANY; + } + + return null; + }, + // the first selected option with a next question wins + getNext: (definition, value) => + Array.isArray(value) + ? definition.options.find((option) => value.includes(option.value) && option.next !== undefined)?.next + : getCommonNext(definition.options), + getDisplayValue: (definition, value) => + Array.isArray(value) + ? definition.options.filter((option) => value.includes(option.value)).map((option) => option.label) + : undefined, +}; + +const boolean: QuaireComponent = { + validate: (_definition, value) => (typeof value === 'boolean' ? null : QuaireErrorCode.INVALID_TYPE), + getDisplayValue: (definition, value) => (value ? definition.trueLabel : definition.falseLabel), +}; + +const input: QuaireComponent = { + validate: (definition, value) => { + if (typeof value === 'number') { + if (definition.min !== undefined && value < definition.min) { + return QuaireErrorCode.MIN; + } + + if (definition.max !== undefined && value > definition.max) { + return QuaireErrorCode.MAX; + } + + return null; + } + + if (typeof value !== 'string') { + return QuaireErrorCode.INVALID_TYPE; + } + + if (definition.minLength !== undefined && value.length < definition.minLength) { + return QuaireErrorCode.MIN_LENGTH; + } + + if (definition.maxLength !== undefined && value.length > definition.maxLength) { + return QuaireErrorCode.MAX_LENGTH; + } + + if (definition.pattern !== undefined && !new RegExp(definition.pattern).test(value)) { + return QuaireErrorCode.PATTERN; + } + + return null; + }, +}; + +// the value is a number or a [from, to] tuple +const range: QuaireComponent = { + validate: (definition, value) => { + const values = Array.isArray(value) ? value : [value]; + + if (values.length > 2 || !values.every((item) => typeof item === 'number')) { + return QuaireErrorCode.INVALID_TYPE; + } + + if (values.some((item) => item < definition.min)) { + return QuaireErrorCode.MIN; + } + + if (values.some((item) => item > definition.max)) { + return QuaireErrorCode.MAX; + } + + return null; + }, +}; + +export const defaultComponents: QuaireComponents = { + [QuaireComponentType.SINGLE_SELECT]: singleSelect, + [QuaireComponentType.MULTI_SELECT]: multiSelect, + [QuaireComponentType.BOOLEAN]: boolean, + [QuaireComponentType.INPUT]: input, + [QuaireComponentType.RANGE]: range, +}; diff --git a/src/conditions.spec.ts b/src/conditions.spec.ts new file mode 100644 index 0000000..f85f597 --- /dev/null +++ b/src/conditions.spec.ts @@ -0,0 +1,62 @@ +import { matchesCondition, matchesValue } from './conditions.js'; + +describe('conditions', () => { + describe('matchesValue', () => { + test('should match equal values', () => { + expect(matchesValue('a', 'a')).toBe(true); + expect(matchesValue(false, false)).toBe(true); + expect(matchesValue(null, null)).toBe(true); + expect(matchesValue('a', 'b')).toBe(false); + }); + + test('should match multi-select answers that contain the value', () => { + expect(matchesValue(['a', 'b'], 'b')).toBe(true); + expect(matchesValue(['a', 'b'], 'c')).toBe(false); + }); + + test('should match one of a list of values', () => { + expect(matchesValue('b', ['a', 'b'])).toBe(true); + expect(matchesValue(['c', 'b'], ['a', 'b'])).toBe(true); + expect(matchesValue('c', ['a', 'b'])).toBe(false); + }); + + test('should compare numbers', () => { + expect(matchesValue(18, { gte: 18 })).toBe(true); + expect(matchesValue(17, { gte: 18 })).toBe(false); + expect(matchesValue(19, { gt: 18, lt: 20 })).toBe(true); + expect(matchesValue(20, { lt: 20 })).toBe(false); + expect(matchesValue(20, { lte: 20 })).toBe(true); + expect(matchesValue(21, { lte: 20 })).toBe(false); + expect(matchesValue(18, { gt: 18 })).toBe(false); + expect(matchesValue('18', { gte: 18 })).toBe(false); + }); + + test('should check if a question is answered', () => { + expect(matchesValue('a', { answered: true })).toBe(true); + expect(matchesValue(undefined, { answered: true })).toBe(false); + expect(matchesValue(null, { answered: false })).toBe(true); + }); + + test('should negate a matcher', () => { + expect(matchesValue('a', { not: 'b' })).toBe(true); + expect(matchesValue('a', { not: ['a', 'b'] })).toBe(false); + }); + }); + + describe('matchesCondition', () => { + test('should match without a condition', () => { + expect(matchesCondition(undefined, {})).toBe(true); + }); + + test('should match when all answers match', () => { + const result = { country: 'DE', age: 30 }; + + expect(matchesCondition({ country: 'DE', age: { gte: 18 } }, result)).toBe(true); + expect(matchesCondition({ country: 'DE', age: { lt: 18 } }, result)).toBe(false); + }); + + test('should call a condition function with the result', () => { + expect(matchesCondition((result) => result.age === 30, { age: 30 })).toBe(true); + }); + }); +}); diff --git a/src/conditions.ts b/src/conditions.ts new file mode 100644 index 0000000..6b0b12c --- /dev/null +++ b/src/conditions.ts @@ -0,0 +1,40 @@ +import type { QuaireCondition, QuaireResult, QuaireValueMatcher } from './types.js'; +import { hasValue, isNil } from './utils.js'; + +// multi-select answers match if they contain the expected value +const matchesScalar = (value: unknown, expected: unknown) => + Array.isArray(value) ? value.includes(expected) : value === expected; + +export const matchesValue = (value: unknown, matcher: QuaireValueMatcher): boolean => { + if (Array.isArray(matcher)) { + return matcher.some((expected) => matchesScalar(value, expected)); + } + + if (isNil(matcher) || typeof matcher !== 'object') { + return matchesScalar(value, matcher); + } + + const { gt, gte, lt, lte, answered, not } = matcher; + const isNumber = typeof value === 'number'; + + return ( + (answered === undefined || answered === hasValue(value)) && + (gt === undefined || (isNumber && value > gt)) && + (gte === undefined || (isNumber && value >= gte)) && + (lt === undefined || (isNumber && value < lt)) && + (lte === undefined || (isNumber && value <= lte)) && + (not === undefined || !matchesValue(value, not)) + ); +}; + +export const matchesCondition = (condition: QuaireCondition | undefined, result: QuaireResult): boolean => { + if (condition === undefined) { + return true; + } + + if (typeof condition === 'function') { + return condition(result); + } + + return Object.entries(condition).every(([key, matcher]) => matchesValue(result[key], matcher)); +}; diff --git a/src/constants.ts b/src/constants.ts index f9651bd..ecd3014 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1 +1,41 @@ +// answer for questions the user skipped on purpose, e.g. with a "skip" or "I don't know" button export const NO_VALUE = 'NO_VALUE'; + +export const QuaireComponentType = { + SINGLE_SELECT: 'SINGLE_SELECT', + MULTI_SELECT: 'MULTI_SELECT', + BOOLEAN: 'BOOLEAN', + INPUT: 'INPUT', + RANGE: 'RANGE', +} as const; + +export type QuaireComponentType = (typeof QuaireComponentType)[keyof typeof QuaireComponentType]; + +export const QuaireErrorCode = { + REQUIRED: 'REQUIRED', + INVALID_TYPE: 'INVALID_TYPE', + INVALID_OPTION: 'INVALID_OPTION', + TOO_FEW: 'TOO_FEW', + TOO_MANY: 'TOO_MANY', + MIN: 'MIN', + MAX: 'MAX', + MIN_LENGTH: 'MIN_LENGTH', + MAX_LENGTH: 'MAX_LENGTH', + PATTERN: 'PATTERN', +} as const; + +export type QuaireErrorCode = (typeof QuaireErrorCode)[keyof typeof QuaireErrorCode]; + +export const QuaireDefinitionProblemCode = { + DUPLICATE_ID: 'DUPLICATE_ID', + DUPLICATE_KEY: 'DUPLICATE_KEY', + UNKNOWN_TYPE: 'UNKNOWN_TYPE', + UNKNOWN_NEXT: 'UNKNOWN_NEXT', + UNREACHABLE: 'UNREACHABLE', + DUPLICATE_NAVIGATION_ID: 'DUPLICATE_NAVIGATION_ID', + UNKNOWN_NAVIGATION: 'UNKNOWN_NAVIGATION', + UNKNOWN_PARENT: 'UNKNOWN_PARENT', +} as const; + +export type QuaireDefinitionProblemCode = + (typeof QuaireDefinitionProblemCode)[keyof typeof QuaireDefinitionProblemCode]; diff --git a/src/definition.spec.ts b/src/definition.spec.ts new file mode 100644 index 0000000..9ab6d51 --- /dev/null +++ b/src/definition.spec.ts @@ -0,0 +1,138 @@ +import { QuaireDefinitionProblemCode } from './constants.js'; +import { resolveDefinition, validateDefinition } from './definition.js'; +import type { QuaireNavigationDefinition, QuaireQuestionDefinition } from './types.js'; + +describe('definition', () => { + describe('resolveDefinition', () => { + const question: QuaireQuestionDefinition = { + id: 2, + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Bar', + options: [], + variants: [ + { when: { foo: 'a' }, options: [{ label: 'A1', value: 'a1' }] }, + { when: { foo: 'b' }, title: 'Bar for B', options: [{ label: 'B1', value: 'b1' }] }, + ], + }; + + test('should apply the first matching variant', () => { + const { definition, variantIndex } = resolveDefinition(question, { foo: 'b' }); + + expect(variantIndex).toBe(1); + expect(definition).toEqual({ + id: 2, + type: 'SINGLE_SELECT', + key: 'bar', + title: 'Bar for B', + options: [{ label: 'B1', value: 'b1' }], + }); + }); + + test('should use the base definition without a matching variant', () => { + const { definition, variantIndex } = resolveDefinition(question, {}); + + expect(variantIndex).toBe(-1); + expect(definition).toEqual({ id: 2, type: 'SINGLE_SELECT', key: 'bar', title: 'Bar', options: [] }); + }); + }); + + describe('validateDefinition', () => { + const navigation: Array = [ + { id: 'a', title: 'A' }, + { id: 'b', parentId: 'a', title: 'B' }, + ]; + const questions: Array = [ + { + id: 1, + type: 'SINGLE_SELECT', + key: 'foo', + title: 'Foo', + navigationId: 'a', + options: [ + { label: 'A', value: 'a', next: 2 }, + { label: 'B', value: 'b', next: '3' }, + ], + }, + { id: 2, type: 'BOOLEAN', key: 'bar', title: 'Bar', next: [{ when: { bar: true }, to: 3 }, { to: 3 }] }, + { id: 3, type: 'INPUT', key: 'baz', title: 'Baz', navigationId: 'b' }, + ]; + + test('should find no problems in a correct definition', () => { + expect(validateDefinition({ questions, navigation })).toEqual([]); + }); + + test('should find duplicate IDs and keys', () => { + const problems = validateDefinition({ + questions: [...questions, { ...questions[2], id: '3' }], + navigation: [...navigation, { id: 'a', title: 'A again' }], + }); + + expect(problems.map((problem) => problem.code)).toEqual([ + QuaireDefinitionProblemCode.DUPLICATE_ID, + QuaireDefinitionProblemCode.DUPLICATE_KEY, + QuaireDefinitionProblemCode.DUPLICATE_NAVIGATION_ID, + ]); + expect(problems[0]).toEqual({ + code: QuaireDefinitionProblemCode.DUPLICATE_ID, + message: 'The question ID "3" is used more than once.', + questionId: '3', + }); + }); + + test('should find unknown types, next questions and navigation items', () => { + const problems = validateDefinition({ + questions: [ + { ...questions[0], navigationId: 'x' }, + { ...questions[1], type: 'RATING' as 'BOOLEAN', next: 9 }, + { ...questions[2], variants: [{ when: { foo: 'a' }, next: [{ to: 8 }] }] }, + ], + navigation: [...navigation, { id: 'c', parentId: 'y', title: 'C' }], + }); + + expect(problems.map((problem) => problem.message)).toEqual([ + 'Question "1" has the unknown navigation ID "x".', + 'Question "2" has the unknown type "RATING".', + 'Question "2" leads to the unknown question "9".', + 'Question "3" leads to the unknown question "8".', + 'Navigation item "c" has the unknown parent "y".', + ]); + }); + + test('should find questions that cannot be reached', () => { + const problems = validateDefinition({ questions: [{ ...questions[1], next: undefined }, questions[2]] }); + + expect(problems).toEqual([ + { + code: QuaireDefinitionProblemCode.UNKNOWN_NAVIGATION, + message: 'Question "3" has the unknown navigation ID "b".', + questionId: 3, + }, + { + code: QuaireDefinitionProblemCode.UNREACHABLE, + message: 'Question "3" cannot be reached from the first question.', + questionId: 3, + }, + ]); + }); + + test('should accept custom component types', () => { + const rating = { ...questions[2], type: 'RATING' as 'INPUT', navigationId: undefined }; + + expect(validateDefinition({ questions: [rating], components: { RATING: {} } })).toEqual([]); + }); + + test('should check options of variants', () => { + const select = { + ...questions[0], + options: [], + variants: [{ when: { foo: 'a' }, options: [{ label: 'X', value: 'x', next: 7 }] }], + }; + + expect(validateDefinition({ questions: [select] }).map((problem) => problem.code)).toEqual([ + QuaireDefinitionProblemCode.UNKNOWN_NEXT, + QuaireDefinitionProblemCode.UNKNOWN_NAVIGATION, + ]); + }); + }); +}); diff --git a/src/definition.ts b/src/definition.ts new file mode 100644 index 0000000..c7fac5c --- /dev/null +++ b/src/definition.ts @@ -0,0 +1,159 @@ +import { defaultComponents } from './components.js'; +import { matchesCondition } from './conditions.js'; +import { QuaireDefinitionProblemCode } from './constants.js'; +import type { + QuaireDefinitionProblem, + QuaireId, + QuaireNext, + QuaireOptions, + QuaireQuestionDefinitionBase, + QuaireResolvedDefinition, + QuaireResult, +} from './types.js'; +import { isNil } from './utils.js'; + +// applies the first variant whose condition matches the result +export const resolveDefinition = ( + definition: Definition, + result: QuaireResult, +) => { + const { variants = [], ...base } = definition; + const variantIndex = variants.findIndex((variant) => matchesCondition(variant.when, result)); + + if (variantIndex === -1) { + return { definition: base as unknown as QuaireResolvedDefinition, variantIndex }; + } + + const { when, ...overrides } = variants[variantIndex]; + + return { + definition: { ...base, ...overrides } as unknown as QuaireResolvedDefinition, + variantIndex, + }; +}; + +const getNextIds = (next: QuaireNext | undefined): Array => { + if (isNil(next)) { + return []; + } + + return Array.isArray(next) ? next.map((entry) => entry.to) : [next]; +}; + +// all question IDs a question can lead to, including all variants and options +const getAllNextIds = (definition: QuaireQuestionDefinitionBase): Array => + [definition, ...(definition.variants || [])].flatMap((source) => { + const { options } = source as { options?: unknown }; + const optionNextIds = Array.isArray(options) + ? options.flatMap((option: { next?: QuaireId }) => getNextIds(option.next)) + : []; + + return [...getNextIds(source.next), ...optionNextIds]; + }); + +const findDuplicates = (values: Array) => values.filter((value, index) => values.indexOf(value) !== index); + +// finds mistakes in the data, e.g. to check data from a CMS in a test +export const validateDefinition = ({ + questions, + navigation = [], + components, +}: QuaireOptions): Array => { + const problems: Array = []; + const allComponents = { ...defaultComponents, ...components }; + const questionIds = new Set(questions.map((question) => String(question.id))); + const navigationIds = new Set(navigation.map((item) => String(item.id))); + + findDuplicates(questions.map((question) => String(question.id))).forEach((id) => + problems.push({ + code: QuaireDefinitionProblemCode.DUPLICATE_ID, + message: `The question ID "${id}" is used more than once.`, + questionId: id, + }), + ); + + findDuplicates(questions.map((question) => question.key)).forEach((key) => + problems.push({ + code: QuaireDefinitionProblemCode.DUPLICATE_KEY, + message: `The key "${key}" is used by more than one question.`, + }), + ); + + findDuplicates(navigation.map((item) => String(item.id))).forEach((id) => + problems.push({ + code: QuaireDefinitionProblemCode.DUPLICATE_NAVIGATION_ID, + message: `The navigation ID "${id}" is used more than once.`, + navigationId: id, + }), + ); + + questions.forEach((question) => { + if (!allComponents[question.type]) { + problems.push({ + code: QuaireDefinitionProblemCode.UNKNOWN_TYPE, + message: `Question "${question.id}" has the unknown type "${question.type}".`, + questionId: question.id, + }); + } + + getAllNextIds(question) + .filter((nextId) => !questionIds.has(String(nextId))) + .forEach((nextId) => + problems.push({ + code: QuaireDefinitionProblemCode.UNKNOWN_NEXT, + message: `Question "${question.id}" leads to the unknown question "${nextId}".`, + questionId: question.id, + }), + ); + + if (!isNil(question.navigationId) && !navigationIds.has(String(question.navigationId))) { + problems.push({ + code: QuaireDefinitionProblemCode.UNKNOWN_NAVIGATION, + message: `Question "${question.id}" has the unknown navigation ID "${question.navigationId}".`, + questionId: question.id, + }); + } + }); + + navigation + .filter((item) => !isNil(item.parentId) && !navigationIds.has(String(item.parentId))) + .forEach((item) => + problems.push({ + code: QuaireDefinitionProblemCode.UNKNOWN_PARENT, + message: `Navigation item "${item.id}" has the unknown parent "${item.parentId}".`, + navigationId: item.id, + }), + ); + + // every question must be reachable from the first question + const questionsById = new Map(questions.map((question) => [String(question.id), question])); + const reachable = new Set(); + const queue = questions.slice(0, 1); + + while (queue.length > 0) { + const question = queue.shift() as QuaireQuestionDefinitionBase; + + if (!reachable.has(String(question.id))) { + reachable.add(String(question.id)); + getAllNextIds(question).forEach((nextId) => { + const next = questionsById.get(String(nextId)); + + if (next) { + queue.push(next); + } + }); + } + } + + questions + .filter((question) => !reachable.has(String(question.id))) + .forEach((question) => + problems.push({ + code: QuaireDefinitionProblemCode.UNREACHABLE, + message: `Question "${question.id}" cannot be reached from the first question.`, + questionId: question.id, + }), + ); + + return problems; +}; diff --git a/src/enums.ts b/src/enums.ts deleted file mode 100644 index 1468598..0000000 --- a/src/enums.ts +++ /dev/null @@ -1,9 +0,0 @@ -export enum QuaireComponentType { - INPUT = 'INPUT', - SINGLE_SELECT = 'SINGLE_SELECT', - RANGE_SLIDER = 'RANGE_SLIDER', -} - -export enum QuaireValidationError { - REQUIRED = 'REQUIRED', -} diff --git a/src/index.ts b/src/index.ts index 4278889..76a533d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,7 @@ -export * from './constants'; -export * from './enums'; -export * from './types'; -export * from './quaire'; +export * from './constants.js'; +export * from './types.js'; +export { defaultComponents } from './components.js'; +export { matchesCondition } from './conditions.js'; +export { validateDefinition } from './definition.js'; +export { Quaire } from './quaire.js'; +export { hasValue } from './utils.js'; diff --git a/src/navigation.ts b/src/navigation.ts new file mode 100644 index 0000000..d1fd52e --- /dev/null +++ b/src/navigation.ts @@ -0,0 +1,73 @@ +import type { QuaireId, QuaireNavigationDefinition, QuaireNavigationItem } from './types.js'; +import { isNil, isSameId } from './utils.js'; + +type NavigationQuestion = { + hasValue: boolean; + isValid: boolean; +}; + +type NavigationOptions = { + // the question that is shown for a navigation item + getQuestion: (navigationId: QuaireId) => Question | null; + isReachable: (question: Question) => boolean; + getDisplayValue: (question: Question) => unknown; + activeNavigationId: QuaireId | undefined; +}; + +export const buildNavigation = < + NavigationDefinition extends QuaireNavigationDefinition, + Question extends NavigationQuestion, +>( + navigation: Array, + { getQuestion, isReachable, getDisplayValue, activeNavigationId }: NavigationOptions, +): Array> => { + const toItem = (definition: NavigationDefinition) => { + const { parentId, ...properties } = definition; + const question = getQuestion(definition.id); + + return { + ...properties, + question, + value: question?.hasValue ? getDisplayValue(question) : null, + active: isSameId(activeNavigationId, definition.id), + hasValue: question?.hasValue ?? false, + isValid: question?.isValid ?? true, + reachable: question ? isReachable(question) : false, + } as QuaireNavigationItem; + }; + + // parents first, so children can be added independent of their position in the list + const parents = navigation + .filter((definition) => isNil(definition.parentId)) + .map((definition) => ({ + ...toItem(definition), + children: [] as Array>, + })); + + navigation + .filter((definition) => !isNil(definition.parentId)) + .forEach((definition) => { + const parent = parents.find((item) => isSameId(item.id, definition.parentId)); + const child = toItem(definition); + + // ignore children without a question or with an unknown parent + if (parent && child.question) { + parent.children.push(child); + } + }); + + // a parent combines its own state with the state of its children + return parents + .filter((parent) => parent.question || parent.children.length > 0) + .map((parent) => { + const items = parent.question ? [parent, ...parent.children] : parent.children; + + return { + ...parent, + active: items.some((item) => item.active), + hasValue: items.some((item) => item.hasValue), + isValid: items.every((item) => item.isValid), + reachable: items.some((item) => item.reachable), + }; + }); +}; diff --git a/src/quaire.spec.ts b/src/quaire.spec.ts index c189298..19bc630 100644 --- a/src/quaire.spec.ts +++ b/src/quaire.spec.ts @@ -1,363 +1,687 @@ -import { Quaire, QuaireComponentType, QuaireItem, QuaireNavigationItem, QuairePartialResult } from './index'; +import { NO_VALUE, QuaireErrorCode } from './constants.js'; +import { Quaire } from './quaire.js'; +import type { + QuaireNavigationDefinition, + QuaireNavigationItem, + QuairePartialResult, + QuaireQuestionDefinition, + QuaireQuestionDefinitionBase, +} from './types.js'; + +const questions: Array = [ + { + id: 1, + type: 'SINGLE_SELECT', + key: 'plan', + title: 'Which plan do you want?', + navigationId: 'plan', + required: true, + options: [ + { label: 'Free', value: 'free', next: 3 }, + { label: 'Pro', value: 'pro', next: 2 }, + ], + }, + { + id: 2, + type: 'INPUT', + key: 'company', + title: 'What is your company?', + navigationId: 'company', + required: true, + next: 3, + }, + { + id: 3, + type: 'BOOLEAN', + key: 'newsletter', + title: 'Do you want our newsletter?', + navigationId: 'newsletter', + required: true, + defaultValue: false, + trueLabel: 'Yes', + falseLabel: 'No', + }, +]; + +const navigation: Array = [ + { id: 'company', parentId: 'plan', title: 'Company' }, // child before its parent + { id: 'plan', title: 'Plan' }, + { id: 'newsletter', title: 'Newsletter', icon: 'mail' }, + { id: 'settings', parentId: 'newsletter', title: 'Settings' }, // child without question + { id: 'orphan', parentId: 'unknown', title: 'Orphan' }, // child with unknown parent + { id: 'empty', title: 'Empty' }, // parent without question and children +]; + +// keeps the navigation tests short +const summarize = (items: Array) => + items.map(({ id, value, active, hasValue, isValid, reachable, children }) => ({ + id, + value, + active, + hasValue, + isValid, + reachable, + ...(children ? { children: summarize(children) } : {}), + })); describe('Quaire', () => { - const items: Array = [ - { - id: 1, - navigationItemId: 2, - resultProperty: 'foo', - dependsOnResultProperties: [], - componentType: QuaireComponentType.SINGLE_SELECT, - question: 'Question 1', - description: 'Description 1', - required: true, - selectOptions: [ - { - label: 'Option 1', - value: 'option 1', - nextItemId: 2, - }, - { - label: 'Option 2', - value: 'option 2', - nextItemId: 2, - }, - ], - }, - { - id: 2, - navigationItemId: 3, - resultProperty: 'bar', - dependsOnResultProperties: ['foo'], - componentType: QuaireComponentType.RANGE_SLIDER, - question: 'Question 2', - description: 'Description 2', - required: true, - rangeOption: { - foo: { - 'option 1': { - range: [1, 99], - nextItemId: 3, - }, - 'option 2': { - range: [100, 199], - nextItemId: 3, - }, - }, - }, - defaultValue: { - foo: { - 'option 1': [20, 50], - 'option 2': [120, 150], - }, - }, - }, - { - id: 3, - navigationItemId: 4, - resultProperty: 'baz', - dependsOnResultProperties: ['foo'], - componentType: QuaireComponentType.INPUT, - question: 'Question 3', - description: 'Description 3', - required: true, - inputOption: { - foo: { - 'option 1': { - type: 'text', - placeholder: 'Enter a text', - nextItemId: 1, - }, - 'option 2': { - type: 'number', - placeholder: 'Type a number', - nextItemId: 1, + describe('without questions', () => { + test('should have no active question', () => { + const Q = new Quaire({ questions: [], result: {} }); + + Q.saveAnswer('anything'); + Q.goTo(1); + Q.back(); + Q.reset(); + + expect(Q.getState()).toEqual({ + activeQuestion: null, + result: {}, + errors: {}, + navigation: [], + path: [], + progress: { answered: 0, total: 0 }, + isValid: true, + isComplete: false, + canGoBack: false, + }); + }); + }); + + describe('answers', () => { + test('should start with the first question', () => { + const Q = new Quaire({ questions }); + + expect(Q.getActiveQuestion()).toEqual({ + ...questions[0], + value: null, + error: QuaireErrorCode.REQUIRED, + isValid: false, + hasValue: false, + }); + }); + + test('should move to the next question of the selected option', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('pro'); + + expect(Q.getActiveQuestion().id).toBe(2); + }); + + test('should save false and 0 as answers', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('free'); + expect(Q.getActiveQuestion().defaultValue).toBe(false); + + Q.saveAnswer(false); + expect(Q.getResult()).toEqual({ plan: 'free', newsletter: false }); + expect(Q.isValid()).toBe(true); + }); + + test('should stay on the question when the answer is invalid', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('enterprise'); + + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.getActiveQuestion().error).toBe(QuaireErrorCode.INVALID_OPTION); + expect(Q.getResult()).toEqual({ plan: 'enterprise' }); + expect(Q.isValid()).toBe(false); + }); + + test('should stay on the last question and complete the flow', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('free'); + expect(Q.isComplete()).toBe(false); + + Q.saveAnswer(true); + expect(Q.getActiveQuestion().id).toBe(3); + expect(Q.isComplete()).toBe(true); + }); + + test('should stay on the question when the next question does not exist', () => { + const Q = new Quaire({ questions: [{ ...questions[1], next: 99 }] }); + + Q.saveAnswer('ACME'); + + expect(Q.getActiveQuestion().id).toBe(2); + }); + + test('should accept NO_VALUE for skipped questions', () => { + const Q = new Quaire({ questions, navigation }); + + Q.saveAnswer('pro'); + Q.saveAnswer(NO_VALUE); + + expect(Q.getActiveQuestion().id).toBe(3); + expect(Q.getErrors()).toEqual({ '3': QuaireErrorCode.REQUIRED }); + expect(Q.getNavigation()[0].children[0].value).toBe(NO_VALUE); + }); + + test('should use a custom validator', () => { + const Q = new Quaire({ + questions: [ + { + ...questions[1], + validate: (value, result) => + String(value).endsWith('GmbH') || result.country !== 'DE' ? null : 'LEGAL_FORM_MISSING', }, - }, - }, - defaultValue: { - foo: { - 'option 1': 'Value for option1', - 'option 2': 500, - }, - }, - }, - ]; - const navigationItems: Array = [ - { - id: 1, - parentId: null, - name: 'Category 1', - }, - { - id: 2, - parentId: 1, - name: 'Subcategory 1', - }, - { - id: 3, - parentId: 1, - name: 'Subcategory 2', - }, - { - id: 4, - parentId: 1, - name: 'Subcategory 3', - }, - ]; - - describe('dependent options', () => { - test('should use range, input and default values based on the dependent answer', () => { - const Q = new Quaire({ items }); - - let activeQuestion = Q.getActiveQuestion(); - expect(activeQuestion.question).toBe('Question 1'); - - Q.saveAnswer('option 1'); - activeQuestion = Q.getActiveQuestion(); - - expect(activeQuestion.question).toBe('Question 2'); - expect(activeQuestion.rangeOption).toEqual({ range: [1, 99], nextItemId: 3 }); - expect(activeQuestion.defaultValue).toEqual([20, 50]); - - Q.saveAnswer(activeQuestion.defaultValue); - activeQuestion = Q.getActiveQuestion(); - - expect(activeQuestion.question).toBe('Question 3'); - expect(activeQuestion.inputOption).toEqual({ - placeholder: 'Enter a text', - type: 'text', - nextItemId: 1, + ], + result: { country: 'DE' }, }); - expect(activeQuestion.defaultValue).toEqual('Value for option1'); - Q.saveAnswer(activeQuestion.defaultValue); - expect(Q.getResult()).toEqual({ - foo: 'option 1', - bar: [20, 50], - baz: 'Value for option1', + Q.saveAnswer('ACME'); + expect(Q.getErrors()).toEqual({ '2': 'LEGAL_FORM_MISSING' }); + + Q.saveAnswer('ACME GmbH'); + expect(Q.getErrors()).toEqual({}); + }); + }); + + describe('path', () => { + test('should follow the answers from the first question', () => { + const Q = new Quaire({ questions }); + + expect(Q.getState().path).toEqual([1]); + + Q.saveAnswer('pro'); + expect(Q.getState().path).toEqual([1, 2, 3]); + }); + + test('should remove answers of a branch that is no longer taken', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('pro'); + Q.saveAnswer('ACME'); + Q.saveAnswer(true); + Q.goTo(1); + Q.saveAnswer('free'); + + expect(Q.getResult()).toEqual({ plan: 'free', newsletter: true }); + expect(Q.getState().path).toEqual([1, 3]); + }); + + test('should only validate questions on the path', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('free'); + Q.saveAnswer(true); + + expect(Q.isValid()).toBe(true); + expect(Q.getErrors()).toEqual({}); + }); + + test('should validate unanswered questions with only one next question', () => { + const Q = new Quaire({ + questions: [{ ...questions[1], id: 1, next: 2 }, { ...questions[1], key: 'name' }, questions[2]], }); - // Jump to question 1 and choose different option - Q.setActiveQuestionByQuestionId(1); - Q.saveAnswer('option 2'); - activeQuestion = Q.getActiveQuestion(); + expect(Q.getState().path).toEqual([1, 2, 3]); + expect(Q.getErrors()).toEqual({ '1': 'REQUIRED', '2': 'REQUIRED', '3': 'REQUIRED' }); + }); + + test('should stop at a loop', () => { + const Q = new Quaire({ + questions: [ + { ...questions[1], id: 1, next: 2 }, + { ...questions[2], id: 2, next: [{ when: { newsletter: true }, to: 1 }] }, + ], + }); - expect(Q.getValidationErrors()).toEqual({ '2': 'REQUIRED' }); - expect(activeQuestion.question).toBe('Question 2'); - expect(activeQuestion.rangeOption).toEqual({ range: [100, 199], nextItemId: 3 }); - expect(activeQuestion.defaultValue).toEqual([120, 150]); + Q.saveAnswer('ACME'); + Q.saveAnswer(true); - Q.saveAnswer(activeQuestion.defaultValue); - activeQuestion = Q.getActiveQuestion(); + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.getState().path).toEqual([1, 2]); + expect(Q.isComplete()).toBe(false); + }); - expect(activeQuestion.question).toBe('Question 3'); - expect(activeQuestion.inputOption).toEqual({ - placeholder: 'Type a number', - type: 'number', - nextItemId: 1, + test('should branch with conditions', () => { + const age: QuaireQuestionDefinition = { + id: 'age', + type: 'INPUT', + key: 'age', + title: 'How old are you?', + next: [{ when: { age: { gte: 18 } }, to: 'adult' }, { to: 'minor' }], + }; + const adult = new Quaire({ + questions: [age, { ...questions[2], id: 'adult' }, { ...questions[2], id: 'minor' }], }); - expect(activeQuestion.defaultValue).toEqual(500); + const minor = new Quaire({ + questions: [age, { ...questions[2], id: 'adult' }, { ...questions[2], id: 'minor' }], + }); + + adult.saveAnswer(30); + minor.saveAnswer(12); - Q.saveAnswer(activeQuestion.defaultValue); - expect(Q.getResult()).toEqual({ - foo: 'option 2', - bar: [120, 150], - baz: 500, + expect(adult.getActiveQuestion().id).toBe('adult'); + expect(minor.getActiveQuestion().id).toBe('minor'); + }); + + test('should end the flow when no condition matches', () => { + const Q = new Quaire({ + questions: [{ ...questions[1], next: [{ when: { company: 'ACME' }, to: 3 }] }, questions[2]], }); + + Q.saveAnswer('Other'); + + expect(Q.getActiveQuestion().id).toBe(2); + expect(Q.isComplete()).toBe(true); }); }); - describe('navigation', () => { - test('should return an empty navigation without items', () => { - const Q = new Quaire({ items: [] }); + describe('variants', () => { + const variantQuestions: Array = [ + { + id: 1, + type: 'SINGLE_SELECT', + key: 'animal', + title: 'Which animal?', + options: [ + { label: 'Dog', value: 'dog', next: 2 }, + { label: 'Cat', value: 'cat', next: 2 }, + ], + }, + { + id: 2, + type: 'SINGLE_SELECT', + key: 'breed', + title: 'Which breed?', + required: true, + options: [], + variants: [ + { when: { animal: 'dog' }, options: [{ label: 'Poodle', value: 'poodle' }] }, + { when: { animal: 'cat' }, options: [{ label: 'Siamese', value: 'siamese' }] }, + ], + }, + ]; + + test('should show the options of the matching variant', () => { + const Q = new Quaire({ questions: variantQuestions }); + + Q.saveAnswer('cat'); + + expect(Q.getActiveQuestion()).toMatchObject({ options: [{ label: 'Siamese', value: 'siamese' }] }); + }); + + test('should reset the answer when the variant changes', () => { + const Q = new Quaire({ questions: variantQuestions }); + + Q.saveAnswer('dog'); + Q.saveAnswer('poodle'); + Q.goTo(1); + Q.saveAnswer('cat'); - expect(Q.getActiveQuestion()).toBeNull(); - expect(Q.getNavigation()).toEqual([]); + expect(Q.getResult()).toEqual({ animal: 'cat', breed: null }); + expect(Q.getErrors()).toEqual({ '2': QuaireErrorCode.REQUIRED }); + expect(Q.getActiveQuestion().id).toBe(2); + }); + + test('should keep the answer when the variant does not change', () => { + const Q = new Quaire({ questions: variantQuestions }); + + Q.saveAnswer('dog'); + Q.saveAnswer('poodle'); + Q.goTo(1); + Q.saveAnswer('dog'); + + expect(Q.getResult()).toEqual({ animal: 'dog', breed: 'poodle' }); }); + }); - test('should set the active question by navigation item ID', () => { - const Q = new Quaire({ items, navigationItems }); + describe('history', () => { + test('should go back to the previous question', () => { + const Q = new Quaire({ questions }); - Q.setActiveQuestionByNavigationItemId(3); + expect(Q.canGoBack()).toBe(false); + + Q.saveAnswer('pro'); + Q.saveAnswer('ACME'); + expect(Q.canGoBack()).toBe(true); + + Q.back(); expect(Q.getActiveQuestion().id).toBe(2); - Q.setActiveQuestionByNavigationItemId(2); + Q.back(); expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.canGoBack()).toBe(false); + expect(Q.getResult()).toEqual({ plan: 'pro', company: 'ACME' }); + }); + + test('should jump to a question', () => { + const Q = new Quaire({ questions }); + const state = Q.getState(); + + Q.goTo(1); + Q.goTo(99); + expect(Q.getState()).toBe(state); + + Q.goTo('3'); + expect(Q.getActiveQuestion().id).toBe(3); - Q.setActiveQuestionByNavigationItemId(1); + Q.back(); expect(Q.getActiveQuestion().id).toBe(1); }); - test('should derive a parent navigation item from its children when it has no question', () => { - const Q = new Quaire({ items, navigationItems }); - expect(Q.getNavigation()).toEqual([ + test('should keep the other answers when an answer changes', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('pro'); + Q.saveAnswer('ACME'); + Q.saveAnswer(true); + Q.goTo(2); + Q.saveAnswer('ACME GmbH'); + + expect(Q.getActiveQuestion().id).toBe(3); + expect(Q.getResult()).toEqual({ plan: 'pro', company: 'ACME GmbH', newsletter: true }); + }); + }); + + describe('navigation', () => { + test('should show the navigation of the flow', () => { + const Q = new Quaire({ questions, navigation }); + + expect(summarize(Q.getNavigation())).toEqual([ { - id: 1, - name: 'Category 1', + id: 'plan', value: null, - icon: undefined, active: true, + hasValue: false, isValid: false, + reachable: true, + children: [{ id: 'company', value: null, active: false, hasValue: false, isValid: true, reachable: false }], + }, + { + id: 'newsletter', + value: null, + active: false, hasValue: false, - componentType: null, - subNavigation: [ - { - id: 2, - name: 'Subcategory 1', - value: null, - icon: undefined, - active: true, - isValid: false, - hasValue: false, - componentType: 'SINGLE_SELECT', - }, - { - id: 3, - name: 'Subcategory 2', - value: null, - icon: undefined, - active: false, - isValid: false, - hasValue: false, - componentType: 'RANGE_SLIDER', - }, - { - id: 4, - name: 'Subcategory 3', - value: null, - icon: undefined, - active: false, - isValid: false, - hasValue: false, - componentType: 'INPUT', - }, + isValid: true, + reachable: false, + children: [], + }, + ]); + }); + + test('should show the answers and keep custom properties', () => { + const Q = new Quaire({ questions, navigation }); + + Q.saveAnswer('pro'); + Q.saveAnswer('ACME'); + Q.saveAnswer(false); + + const [plan, newsletter] = Q.getNavigation(); + + expect(summarize([plan, newsletter])).toEqual([ + { + id: 'plan', + value: 'Pro', + active: false, + hasValue: true, + isValid: true, + reachable: true, + children: [{ id: 'company', value: 'ACME', active: false, hasValue: true, isValid: true, reachable: true }], + }, + { id: 'newsletter', value: 'No', active: true, hasValue: true, isValid: true, reachable: true, children: [] }, + ]); + expect(newsletter).toMatchObject({ title: 'Newsletter', icon: 'mail', question: { id: 3, value: false } }); + }); + + test('should derive a parent without question from its children', () => { + const Q = new Quaire({ + questions, + navigation: [ + { id: 'about', title: 'About' }, + { id: 'plan', parentId: 'about', title: 'Plan' }, + { id: 'company', parentId: 'about', title: 'Company' }, + ], + }); + + Q.saveAnswer('free'); + + expect(summarize(Q.getNavigation())).toEqual([ + { + id: 'about', + value: null, + active: false, + hasValue: true, + isValid: true, + reachable: true, + children: [ + { id: 'plan', value: 'Free', active: false, hasValue: true, isValid: true, reachable: true }, + { id: 'company', value: null, active: false, hasValue: false, isValid: true, reachable: false }, ], }, ]); + }); + + test('should show the answered question when a navigation item has more than one question', () => { + const Q = new Quaire({ + questions: [ + { ...questions[1], id: 1, next: 2, navigationId: 'about' }, + { ...questions[1], key: 'name', navigationId: 'about' }, + ], + navigation: [{ id: 'about', title: 'About' }], + }); - Q.saveAnswer('option 1'); - Q.saveAnswer([20, 50]); - Q.saveAnswer('text'); + expect(Q.getNavigation()[0].question.id).toBe(1); - const [parent] = Q.getNavigation(); - expect(parent.hasValue).toBe(true); - expect(parent.isValid).toBe(true); + Q.goTo(2); + Q.saveAnswer('Jane'); + + expect(Q.getNavigation()[0].question.id).toBe(2); }); - test('should skip navigation items without questions', () => { - const navigationItemsWithoutQuestions: Array = [ - { id: 1, parentId: null, name: 'Category 1' }, - { id: 2, parentId: 1, name: 'Subcategory 1' }, - { id: 3, parentId: 1, name: 'Subcategory without question' }, - { id: 5, parentId: null, name: 'Category without question' }, - ]; - const Q = new Quaire({ items: [items[0]], navigationItems: navigationItemsWithoutQuestions }); + test('should jump to a question via the navigation', () => { + const Q = new Quaire({ + questions, + navigation: [ + { id: 'about', title: 'About' }, + ...navigation.map((item) => ({ ...item, parentId: item.parentId ?? 'about' })), + ], + }); + + Q.goToNavigationItem('newsletter'); + expect(Q.getActiveQuestion().id).toBe(3); - const navigation = Q.getNavigation(); + Q.goToNavigationItem('about'); + expect(Q.getActiveQuestion().id).toBe(1); - expect(navigation.map((item) => item.name)).toEqual(['Category 1']); - expect(navigation[0].subNavigation.map((item) => item.name)).toEqual(['Subcategory 1']); + Q.goToNavigationItem('empty'); + expect(Q.getActiveQuestion().id).toBe(1); }); }); - describe('navigation order', () => { - test('should add children that come before their parent', () => { - const [parent, ...children] = navigationItems; - const Q = new Quaire({ items, navigationItems: [...children, parent] }); + describe('state', () => { + test('should return the same state until the flow changes', () => { + const Q = new Quaire({ questions }); + const state = Q.getState(); - expect(Q.getNavigation()).toEqual(new Quaire({ items, navigationItems }).getNavigation()); + expect(Q.getState()).toBe(state); + + Q.saveAnswer('pro'); + expect(Q.getState()).not.toBe(state); }); - test('should ignore children with an unknown parent', () => { - const navigationItemsWithUnknownParent: Array = [ - { id: 2, parentId: 99, name: 'Subcategory with unknown parent' }, - ]; - const Q = new Quaire({ items, navigationItems: navigationItemsWithUnknownParent }); + test('should notify subscribers about changes', () => { + const Q = new Quaire({ questions }); + const listener = vi.fn(); + const unsubscribe = Q.subscribe(listener); + + Q.saveAnswer('pro'); + expect(listener).toHaveBeenCalledWith(Q.getState()); - expect(Q.getNavigation()).toEqual([]); + unsubscribe(); + Q.saveAnswer('ACME'); + expect(listener).toHaveBeenCalledTimes(1); }); - }); - describe('active question', () => { - test('should have no active question for an unknown question ID', () => { - const Q = new Quaire({ items }); + test('should not change the result that was passed in or returned', () => { + const result = { plan: 'pro' }; + const Q = new Quaire({ questions, result }); - Q.setActiveQuestionByQuestionId(99); + Q.saveAnswer('ACME'); + (Q.getResult() as Record).plan = 'changed'; - expect(Q.getActiveQuestion()).toBeNull(); + expect(result).toEqual({ plan: 'pro' }); + expect(Q.getState().path).toEqual([1, 2, 3]); + expect(Q.getActiveQuestion().id).toBe(3); }); - test('should ignore answers when no question is active', () => { - const Q = new Quaire({ items, navigationItems }); + test('should count the progress on the path', () => { + const Q = new Quaire({ questions }); - Q.setActiveQuestionByNavigationItemId(99); - Q.saveAnswer('option 1'); + expect(Q.getProgress()).toEqual({ answered: 0, total: 1 }); + + Q.saveAnswer('pro'); + expect(Q.getProgress()).toEqual({ answered: 1, total: 3 }); + + Q.saveAnswer('ACME'); + Q.saveAnswer(true); + expect(Q.getProgress()).toEqual({ answered: 3, total: 3 }); + }); + + test('should reset the flow', () => { + const Q = new Quaire({ questions }); + + Q.saveAnswer('pro'); + Q.reset(); - expect(Q.getActiveQuestion()).toBeNull(); expect(Q.getResult()).toEqual({}); + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.canGoBack()).toBe(false); }); }); - describe('validation', () => { - test('should be invalid until all required questions are answered', () => { - const Q = new Quaire({ items }); + describe('restore', () => { + test('should continue with the first open question', () => { + const Q = new Quaire({ questions, result: { plan: 'pro' } }); - expect(Q.isValid()).toBe(false); - expect(Q.getValidationErrors()).toEqual({ '1': 'REQUIRED', '2': 'REQUIRED', '3': 'REQUIRED' }); + expect(Q.getActiveQuestion().id).toBe(2); + expect(Q.canGoBack()).toBe(true); + + Q.back(); + expect(Q.getActiveQuestion().id).toBe(1); + }); - Q.saveAnswer('option 1'); - Q.saveAnswer([20, 50]); - Q.saveAnswer('text'); + test('should continue with an invalid answer', () => { + const Q = new Quaire({ questions, result: { plan: 'pro', company: true } }); - expect(Q.isValid()).toBe(true); - expect(Q.getValidationErrors()).toEqual({}); + expect(Q.getActiveQuestion().id).toBe(2); + expect(Q.getErrors()).toEqual({ '2': QuaireErrorCode.INVALID_TYPE, '3': QuaireErrorCode.REQUIRED }); + }); + + test('should show the last question of a complete result', () => { + const Q = new Quaire({ questions, result: { plan: 'free', newsletter: true, other: 'kept' } }); + + expect(Q.getActiveQuestion().id).toBe(3); + expect(Q.isComplete()).toBe(true); + expect(Q.getResult()).toEqual({ plan: 'free', newsletter: true, other: 'kept' }); + }); + + test('should start with the first question for an empty result', () => { + const Q = new Quaire({ questions, result: {} }); + + expect(Q.getActiveQuestion().id).toBe(1); + expect(Q.canGoBack()).toBe(false); + }); + }); + + describe('custom components', () => { + type RatingDefinition = QuaireQuestionDefinitionBase<'RATING', { stars: number }>; + + const rating: RatingDefinition = { id: 1, type: 'RATING', key: 'rating', title: 'How do you like it?', stars: 5 }; + + test('should use the component of a custom type', () => { + const Q = new Quaire<{ rating: number }, RatingDefinition>({ + questions: [{ ...rating, navigationId: 'rating' }], + navigation: [{ id: 'rating', title: 'Rating' }], + components: { + RATING: { + hasValue: (value) => typeof value === 'number' && value > 0, + validate: (definition: RatingDefinition, value) => + Number(value) <= definition.stars ? null : 'TOO_MANY_STARS', + getDisplayValue: (_definition, value) => '★'.repeat(Number(value)), + }, + }, + }); + + Q.saveAnswer(0); + expect(Q.getErrors()).toEqual({}); + expect(Q.getActiveQuestion().hasValue).toBe(false); + + Q.saveAnswer(6); + expect(Q.getErrors()).toEqual({ '1': 'TOO_MANY_STARS' }); + + Q.saveAnswer(3); + expect(Q.getNavigation()[0].value).toBe('★★★'); + expect(Q.getActiveQuestion().stars).toBe(5); + }); + + test('should accept any value for a type without component', () => { + const Q = new Quaire({ + questions: [ + { ...rating, next: 2 }, + { ...rating, id: 2, key: 'other' }, + ], + }); + + Q.saveAnswer('great'); + + expect(Q.getActiveQuestion().id).toBe(2); + expect(Q.getResult()).toEqual({ rating: 'great' }); }); }); describe('result type', () => { // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- interfaces must work as result type interface MyResult { - foo: string; - bar: Array; - baz: string | number; + plan: 'free' | 'pro'; + newsletter: boolean; } test('should type the result with a custom result type', () => { - const Q = new Quaire({ - items, - result: { foo: 'option 1' }, - }); - - Q.saveAnswer([20, 50]); + const Q = new Quaire({ questions, result: { plan: 'free' } }); - const result = Q.getResult(); - - expectTypeOf(result.foo).toEqualTypeOf(); - expectTypeOf(result.bar).toEqualTypeOf | null | undefined>(); - expect(result).toEqual({ foo: 'option 1', bar: [20, 50] }); + expectTypeOf(Q.getResult().plan).toEqualTypeOf<'free' | 'pro' | null | undefined>(); + expectTypeOf(Q.getResult().newsletter).toEqualTypeOf(); }); test('should infer the result type from the result option', () => { - const Q = new Quaire({ items, result: { foo: 'option 1' } }); + const Q = new Quaire({ questions, result: { plan: 'free' } }); - expectTypeOf(Q.getResult()).toEqualTypeOf<{ foo?: string | null }>(); + expectTypeOf(Q.getResult()).toEqualTypeOf<{ plan?: string | null }>(); }); test('should use unknown values without a custom result type', () => { - const Q = new Quaire({ items }); + const Q = new Quaire({ questions }); expectTypeOf(Q.getResult()).toEqualTypeOf(); expectTypeOf(Q.getActiveQuestion().value).toEqualTypeOf(); }); }); - describe('restore state', () => { - test('should keep the result when there are no items', () => { - const Q = new Quaire({ items: [], result: { foo: 'option 1' } }); - - expect(Q.getActiveQuestion()).toBeNull(); - expect(Q.getResult()).toEqual({ foo: 'option 1' }); + describe('performance', () => { + test('should handle long flows with dependencies', () => { + const longFlow: Array = Array.from({ length: 500 }, (_, index) => ({ + id: index, + type: 'INPUT', + key: `q${index}`, + title: `Question ${index}`, + required: true, + next: index + 1 < 500 ? index + 1 : undefined, + variants: index > 0 ? [{ when: { [`q${index - 1}`]: 'yes' }, placeholder: 'yes' }] : [], + })); + const Q = new Quaire({ questions: longFlow }); + const start = performance.now(); + + longFlow.forEach(() => Q.saveAnswer('yes')); + + expect(Q.isComplete()).toBe(true); + expect(performance.now() - start).toBeLessThan(2000); }); }); }); diff --git a/src/quaire.ts b/src/quaire.ts index fe49fe3..1f751e8 100644 --- a/src/quaire.ts +++ b/src/quaire.ts @@ -1,505 +1,412 @@ -import { NO_VALUE } from './constants'; -import { - QuaireBase, - QuaireInputItemOption, - QuaireItem, - QuaireItemOption, +import { defaultComponents } from './components.js'; +import { matchesCondition } from './conditions.js'; +import { NO_VALUE, QuaireErrorCode } from './constants.js'; +import { resolveDefinition } from './definition.js'; +import { buildNavigation } from './navigation.js'; +import type { + QuaireComponent, + QuaireComponents, + QuaireError, + QuaireId, + QuaireNavigationDefinition, QuaireNavigationItem, QuaireOptions, QuairePartialResult, QuaireQuestion, - QuaireRangeItemOption, + QuaireQuestionDefinition, + QuaireQuestionDefinitionBase, + QuaireResolvedDefinition, QuaireResult, -} from './types'; -import { QuaireComponentType, QuaireValidationError } from './enums'; -import { getByPath, hasAnswer } from './utils'; + QuaireState, +} from './types.js'; +import { hasValue, isSameId } from './utils.js'; + +type Step = { + definition: QuaireResolvedDefinition; + variantIndex: number; + value: unknown; + hasValue: boolean; + error: QuaireError | null; +}; export class Quaire< Result extends object = QuaireResult, - Item extends QuaireItem = QuaireItem, - Question extends QuaireQuestion = QuaireQuestion, - NavigationItem extends QuaireNavigationItem = QuaireNavigationItem, -> implements QuaireBase { - protected _activeItemId: number | null = null; - protected readonly _items: Array; - protected readonly _navigationItems: Array; - protected readonly _result: QuaireResult = {}; - protected readonly _validationErrors: Record = {}; - protected readonly _selectComponentTypes: Array = [QuaireComponentType.SINGLE_SELECT]; - protected readonly _rangeComponentTypes: Array = [QuaireComponentType.RANGE_SLIDER]; - protected readonly _inputComponentTypes: Array = [QuaireComponentType.INPUT]; - protected readonly _alwaysPossibleFollowUpQuestionComponents: Array = [ - QuaireComponentType.RANGE_SLIDER, - QuaireComponentType.INPUT, - ]; - - constructor({ items, navigationItems, result }: QuaireOptions) { - this._items = items; - this._navigationItems = navigationItems || []; - - if (items.length > 0) { - this._activeItemId = this._items[0].id; - } - + Definition extends QuaireQuestionDefinitionBase = QuaireQuestionDefinition, + NavigationDefinition extends QuaireNavigationDefinition = QuaireNavigationDefinition, +> { + protected readonly _questions: Array; + protected readonly _questionsById: Map; + protected readonly _navigation: Array; + protected readonly _components: QuaireComponents; + protected readonly _listeners = new Set< + ( + state: QuaireState< + Result, + QuaireQuestion, + QuaireNavigationItem> + >, + ) => void + >(); + protected _result: QuaireResult; + // variant of each answered question when it was answered, a changed variant makes the answer invalid + protected _answerVariants = new Map(); + protected _activeId: QuaireId | null; + protected _history: Array = []; + protected _path: Array> = []; + protected _pathById = new Map>(); + protected _state!: QuaireState< + Result, + QuaireQuestion, + QuaireNavigationItem> + >; + + constructor({ + questions, + navigation = [], + result, + components, + }: QuaireOptions) { + this._questions = questions; + this._questionsById = new Map(questions.map((question) => [String(question.id), question])); + this._navigation = navigation; + this._components = { ...defaultComponents, ...components }; + this._result = { ...result }; + this._activeId = questions.length > 0 ? questions[0].id : null; + this._update(); + + // continue a restored flow with the first open question if (result) { - this._result = result as QuaireResult; - this._setActiveItemId(); - } + const openIndex = this._path.findIndex((step) => !step.hasValue || step.error); + const activeIndex = openIndex === -1 ? this._path.length - 1 : openIndex; - this._validate(this.getActiveQuestion()); + this._history = this._path.slice(0, activeIndex).map((step) => step.definition.id); + this._activeId = this._path[activeIndex]?.definition.id ?? this._activeId; + this._buildState(); + } } - protected _setActiveItemId() { - let activeQuestion = this.getActiveQuestion(); - - if (activeQuestion) { - let answer = this._result[activeQuestion.resultProperty]; - - if (!hasAnswer(answer)) { - return; - } + protected _getDefinition(id: QuaireId | null) { + return this._questionsById.get(String(id)); + } - while (activeQuestion) { - this.saveAnswer(answer); + protected _getComponent(type: string): QuaireComponent { + return this._components[type] || {}; + } - const currentQuestion = this.getActiveQuestion(); + protected _hasValue(definition: QuaireResolvedDefinition, value: unknown) { + const component = this._getComponent(definition.type); - if (currentQuestion && activeQuestion.id !== currentQuestion.id) { - activeQuestion = currentQuestion; + return component.hasValue ? component.hasValue(value) : hasValue(value); + } - answer = this._result[activeQuestion.resultProperty]; - } else { - activeQuestion = null; - answer = null; - } + protected _validate(definition: QuaireResolvedDefinition, value: unknown): QuaireError | null { + if (!this._hasValue(definition, value)) { + return definition.required ? QuaireErrorCode.REQUIRED : null; + } - if (!hasAnswer(answer)) { - break; - } - } + if (value === NO_VALUE) { + return null; } - } - protected _getItem(itemId: number | undefined) { - return this._items.find((i) => i.id === itemId); + return ( + this._getComponent(definition.type).validate?.(definition, value) || + definition.validate?.(value, this._result) || + null + ); } - protected _getQuestionObject( - item: Item, - dependsOnKeys: string[], - selectOptions: QuaireItemOption[] | null, - rangeOption: QuaireRangeItemOption | null, - inputOption: QuaireInputItemOption | null, - defaultValue: unknown, - ): Question { - const value = this._getResultByValueProperty(item.resultProperty); + protected _getNext(definition: QuaireResolvedDefinition, value: unknown): QuaireId | undefined { + const next = this._getComponent(definition.type).getNext?.(definition, value); - let isValid = true; + if (next !== undefined) { + return next; + } - if ((!value && item.required) || this._validationErrors[item.id]) { - isValid = false; + if (Array.isArray(definition.next)) { + return definition.next.find((entry) => matchesCondition(entry.when, this._result))?.to; } - const question: QuaireQuestion = { - id: item.id, - navigationItemId: item.navigationItemId, - question: item.question, - description: item.description, - required: item.required, - resultProperty: item.resultProperty, + return definition.next; + } + + protected _getStep(question: Definition): Step { + const { definition, variantIndex } = resolveDefinition(question, this._result); + const value = this._result[definition.key]; + + return { + definition, + variantIndex, value, - componentType: item.componentType, - dependsOnQuestions: this._items - .map((i) => { - if (dependsOnKeys.includes(i.resultProperty)) { - return this._getQuestion(i.id); - } - - return null; - }) - .filter((question) => question !== null), - selectOptions, - rangeOption, - inputOption, - defaultValue, - isValid, - nextItemId: item.nextItemId, - valueHasChanged: false, + hasValue: this._hasValue(definition, value), + error: this._validate(definition, value), }; - - return question as Question; } - protected _getDependencyPath(item: Item) { - const path: Array = []; + // the questions from the first question to the end, following the answers + protected _computePath() { + const path = new Map>(); + let question = this._questions[0]; - item.dependsOnResultProperties.forEach((resultProperty) => { - const resultPropertyValue = this._getResultByValueProperty(resultProperty); + while (question && !path.has(String(question.id))) { + const step = this._getStep(question); - if (resultPropertyValue) { - path.push(resultProperty); - path.push(String(resultPropertyValue)); - } - }); + path.set(String(question.id), step); + question = this._getDefinition(this._getNext(step.definition, step.value) ?? null) as Definition; + } return path; } - protected _getQuestion(itemId: number | undefined) { - const item = this._getItem(itemId); + // resets answers whose variant changed and removes answers of questions that are not on the path + protected _invalidate(path: Map>) { + let changed = false; + + [...path.values()] + .filter((step) => step.hasValue) + .forEach(({ definition, variantIndex }) => { + const answerVariant = this._answerVariants.get(definition.key); + + if (answerVariant === undefined) { + this._answerVariants.set(definition.key, variantIndex); + } else if (answerVariant !== variantIndex) { + this._result[definition.key] = null; + this._answerVariants.delete(definition.key); + changed = true; + } + }); + + this._questions + .filter((question) => !path.has(String(question.id)) && question.key in this._result) + .forEach((question) => { + delete this._result[question.key]; + this._answerVariants.delete(question.key); + changed = true; + }); - return item ? this._getQuestionFromItem(item) : null; + return changed; } - protected _getQuestionFromItem(item: Item) { - let selectOptions: Array | null; - let rangeOption: QuaireRangeItemOption | null; - let inputOption: QuaireInputItemOption | null; - let defaultValue: unknown; + protected _update() { + do { + this._pathById = this._computePath(); + } while (this._invalidate(this._pathById)); - if (item.dependsOnResultProperties.length > 0) { - const path = this._getDependencyPath(item); - selectOptions = getByPath | null>(item.selectOptions, path, null); - rangeOption = getByPath(item.rangeOption, path, null); - inputOption = getByPath(item.inputOption, path, null); - defaultValue = getByPath(item.defaultValue, path, null); - } else { - selectOptions = item.selectOptions ? (item.selectOptions as Array) : null; - rangeOption = item.rangeOption ? item.rangeOption : null; - inputOption = item.inputOption ? item.inputOption : null; - defaultValue = item.defaultValue ? item.defaultValue : null; - } + this._path = [...this._pathById.values()]; - return this._getQuestionObject( - item, - item.dependsOnResultProperties, - selectOptions, - rangeOption, - inputOption, - defaultValue, - ); + this._buildState(); + } + + protected _toQuestion(step: Step): QuaireQuestion { + return { + ...step.definition, + value: step.value ?? null, + error: step.error, + isValid: step.error === null, + hasValue: step.hasValue, + }; } - protected _getQuestionByNavigationItemId(categoryId: number) { - let item = this._items - .filter((item) => hasAnswer(this._result[item.resultProperty])) - .find((i) => i.navigationItemId === categoryId); + // questions that are not on the path have no errors + protected _getQuestion(id: QuaireId): QuaireQuestion { + const step = this._pathById.get(String(id)); - if (!item) { - item = this._items.find((i) => i.navigationItemId === categoryId); + if (step) { + return this._toQuestion(step); } - return this._getQuestion(item?.id); - } - - protected _getResultByValueProperty(valueProperty: string) { - return this._result[valueProperty] === undefined ? null : this._result[valueProperty]; + return this._toQuestion({ ...this._getStep(this._getDefinition(id) as Definition), error: null }); } - protected _getActiveQuestionNavigationItem() { - const navigationItem = this._navigationItems.find((bc) => bc.id === this.getActiveQuestion()?.navigationItemId); - return navigationItem || null; - } + protected _getDisplayValue(question: QuaireQuestion) { + if (question.value === NO_VALUE) { + return NO_VALUE; + } - protected _validateSelectComponent(question: Question, currentAnswer: unknown) { - const option = question.selectOptions && question.selectOptions.find((o) => o.value === currentAnswer); + const definition = question as unknown as QuaireResolvedDefinition; - if (question.required && !option) { - this._result[question.resultProperty] = null; - this._validationErrors[question.id] = QuaireValidationError.REQUIRED; - } + return this._getComponent(question.type).getDisplayValue?.(definition, question.value) ?? question.value; } - protected _validateRangeComponent(question: Question, activeQuestion: Question | null) { - const isActiveQuestionADependency = !!question.dependsOnQuestions.find( - (dq) => dq.resultProperty === activeQuestion?.resultProperty, - ); + // prefers an answered question on the path, then any question on the path + protected _getNavigationQuestion(navigationId: QuaireId) { + const questions = this._questions.filter((question) => isSameId(question.navigationId, navigationId)); + const steps = this._path.filter((step) => isSameId(step.definition.navigationId, navigationId)); + const step = steps.find((item) => item.hasValue) || steps[0]; - if (isActiveQuestionADependency && activeQuestion?.required && activeQuestion.valueHasChanged) { - delete this._result[question.resultProperty]; - this._validationErrors[question.id] = QuaireValidationError.REQUIRED; + if (step) { + return this._toQuestion(step); } - } - protected _validateGenericComponent( - isQuestionInCurrentFlow: boolean, - question: Question, - activeQuestion: Question | null, - currentAnswer: unknown, - ) { - if ( - isQuestionInCurrentFlow && - !hasAnswer(currentAnswer) && - question.required && - !this._validationErrors[question.id] - ) { - this._validationErrors[question.id] = QuaireValidationError.REQUIRED; - } + return questions.length > 0 ? this._getQuestion(questions[0].id) : null; } - protected _validate(activeQuestion: Question | null) { - this._items.forEach((item) => { - const question = this._getQuestionFromItem(item); - const currentAnswer = this._getResultByValueProperty(question.resultProperty); - const possibleFollowUpQuestionIds: number[] = []; - - question.dependsOnQuestions.forEach((q) => { - const dependsOnQuestionResult = this._result[q.resultProperty]; + protected _isComplete() { + const lastStep = this._path[this._path.length - 1]; - // only take possible follow up id's based on the current result of the dependent question - q.selectOptions?.forEach((o) => { - if (o.value === dependsOnQuestionResult && o.nextItemId) { - possibleFollowUpQuestionIds.push(o.nextItemId); - } - }); - }); + return ( + lastStep !== undefined && + lastStep.hasValue && + this._path.every((step) => step.error === null) && + this._getNext(lastStep.definition, lastStep.value) === undefined + ); + } - // questions with some components always stay in the flow, even if they depend on former answers - if (this._alwaysPossibleFollowUpQuestionComponents.includes(question.componentType)) { - possibleFollowUpQuestionIds.push(question.id); - } + protected _buildState() { + const activeQuestion = this._activeId === null ? null : this._getQuestion(this._activeId); + const errors: Record = {}; - const isQuestionInCurrentFlow = - question.dependsOnQuestions.length > 0 ? possibleFollowUpQuestionIds.includes(question.id) : true; - - if (!isQuestionInCurrentFlow) { - delete this._result[question.resultProperty]; - delete this._validationErrors[question.id]; - } else if (currentAnswer && this._selectComponentTypes.includes(question.componentType)) { - this._validateSelectComponent(question, currentAnswer); - } else if (currentAnswer && this._rangeComponentTypes.includes(question.componentType)) { - this._validateRangeComponent(question, activeQuestion); - } else { - this._validateGenericComponent(isQuestionInCurrentFlow, question, activeQuestion, currentAnswer); + this._path.forEach((step) => { + if (step.error) { + errors[String(step.definition.id)] = step.error; } }); - } - public getResult() { - return this._result as QuairePartialResult; + this._state = { + activeQuestion, + result: { ...this._result } as QuairePartialResult, + errors, + navigation: buildNavigation(this._navigation, { + getQuestion: (navigationId) => this._getNavigationQuestion(navigationId), + isReachable: (question) => this._pathById.has(String(question.id)), + getDisplayValue: (question) => this._getDisplayValue(question), + activeNavigationId: activeQuestion?.navigationId, + }), + path: this._path.map((step) => step.definition.id), + progress: { + answered: this._path.filter((step) => step.hasValue && step.error === null).length, + total: this._path.length, + }, + isValid: Object.keys(errors).length === 0, + isComplete: this._isComplete(), + canGoBack: this._history.length > 0, + }; } - public getValidationErrors() { - return this._validationErrors; + protected _notify() { + this._listeners.forEach((listener) => listener(this._state)); } - public setActiveQuestionByNavigationItemId(navigationItemId: number) { - let quaireItem = this._items.find((item) => item.navigationItemId === navigationItemId); - - if (!quaireItem) { - const firstChildNavigationItem = this._navigationItems.find( - (navigationItem) => navigationItem.parentId === navigationItemId, - ); - quaireItem = this._items.find((item) => item.navigationItemId === firstChildNavigationItem?.id); - } - - this._activeItemId = quaireItem?.id || null; + // the state object only changes when the flow changes, e.g. for React's useSyncExternalStore + public getState() { + return this._state; } - public setActiveQuestionByQuestionId(questionId: number) { - this._activeItemId = questionId; + public subscribe( + listener: ( + state: QuaireState< + Result, + QuaireQuestion, + QuaireNavigationItem> + >, + ) => void, + ) { + this._listeners.add(listener); + + return () => { + this._listeners.delete(listener); + }; } public getActiveQuestion() { - if (this._activeItemId) { - return this._getQuestion(this._activeItemId); - } - - return null; + return this._state.activeQuestion; } - protected _getNextItemIdFromSelectComponents = (activeQuestion: Question | null, answer: unknown) => { - const option = activeQuestion?.selectOptions?.find((o) => o.value === answer); - return option?.nextItemId; - }; - - // eslint-disable-next-line - protected _getNextItemIdFromRangeComponents = (activeQuestion: Question | null, answer: unknown) => { - return activeQuestion?.rangeOption?.nextItemId; - }; + public getResult() { + return this._state.result; + } - // eslint-disable-next-line - protected _getNextItemIdFromInputComponents = (activeQuestion: Question | null, answer: unknown) => { - return activeQuestion?.inputOption?.nextItemId; - }; + public getErrors() { + return this._state.errors; + } - public saveAnswer(answer: unknown) { - const activeQuestion = this.getActiveQuestion(); + public getNavigation() { + return this._state.navigation; + } - if (activeQuestion) { - let nextItemId: number | null | undefined; + public getProgress() { + return this._state.progress; + } - activeQuestion.valueHasChanged = this._result[activeQuestion.resultProperty] !== answer; + public isValid() { + return this._state.isValid; + } - this._result[activeQuestion.resultProperty] = answer; + public isComplete() { + return this._state.isComplete; + } - delete this._validationErrors[activeQuestion.id]; + public canGoBack() { + return this._state.canGoBack; + } - if (this._selectComponentTypes.includes(activeQuestion.componentType)) { - nextItemId = this._getNextItemIdFromSelectComponents(activeQuestion, answer); - } else if (this._rangeComponentTypes.includes(activeQuestion.componentType)) { - nextItemId = this._getNextItemIdFromRangeComponents(activeQuestion, answer); - } else if (this._inputComponentTypes.includes(activeQuestion.componentType)) { - nextItemId = this._getNextItemIdFromInputComponents(activeQuestion, answer); - } else { - nextItemId = activeQuestion.nextItemId; - } + // saves the answer of the active question and moves to the next question if the answer is valid + public saveAnswer(value: unknown) { + const question = this._getDefinition(this._activeId); - if (!nextItemId) { - nextItemId = activeQuestion.id; - } + if (!question) { + return; + } - this._activeItemId = nextItemId; + const { definition } = resolveDefinition(question, this._result); - this._validate(activeQuestion); - } - } + this._result[definition.key] = value; + this._answerVariants.delete(definition.key); + this._update(); - protected _getNavigationValue(question: Question | null, answer: unknown): unknown { - let value: unknown; + const nextId = this._state.activeQuestion?.error ? undefined : this._getNext(definition, value); - if (question && this._selectComponentTypes.includes(question.componentType)) { - value = question?.selectOptions?.find((selectOption) => selectOption.value === answer)?.label; - } else { - value = answer; + if (nextId !== undefined && this._getDefinition(nextId)) { + this._history.push(question.id); + this._activeId = nextId; + this._buildState(); } - return value; - } - - protected _getNavigationItemObject( - activeNavigationItem: NavigationItem | null, - navigationItem: NavigationItem, - question: Question, - answer: unknown, - isParent: boolean, - ): NavigationItem { - const active = activeNavigationItem?.id === navigationItem.id; - const isValid = question.isValid; - const hasValue = Boolean(answer); - let value: unknown = null; - - if (answer === NO_VALUE) { - value = NO_VALUE; - } else if (answer) { - value = this._getNavigationValue(question, answer); - } + this._notify(); + } - const item: QuaireNavigationItem = { - id: navigationItem.id, - name: navigationItem.name, - value, - icon: navigationItem.icon, - active, - isValid, - hasValue, - componentType: question.componentType, - }; + public goTo(questionId: QuaireId) { + const question = this._getDefinition(questionId); - if (isParent) { - item.subNavigation = []; + if (!question || isSameId(question.id, this._activeId)) { + return; } - return item as NavigationItem; + // there is always an active question when questions exist + this._history.push(this._activeId as QuaireId); + this._activeId = question.id; + this._buildState(); + this._notify(); } - protected _getNavigationItem( - activeNavigationItem: NavigationItem | null, - navigationItem: NavigationItem, - isParent = true, - ) { - const question = this._getQuestionByNavigationItemId(navigationItem.id); + // a navigation item without a question leads to the question of its first child + public goToNavigationItem(navigationId: QuaireId) { + const firstChild = this._navigation.find((item) => isSameId(item.parentId, navigationId)); + const question = + this._getNavigationQuestion(navigationId) || (firstChild && this._getNavigationQuestion(firstChild.id)); if (question) { - const answer = this._getResultByValueProperty(question.resultProperty); - - return this._getNavigationItemObject(activeNavigationItem, navigationItem, question, answer, isParent); + this.goTo(question.id); } - - return null; - } - - // used for parent navigation items without an own question, the values are derived from the children - protected _getParentNavigationItemObject(navigationItem: NavigationItem): NavigationItem { - const item: QuaireNavigationItem = { - id: navigationItem.id, - name: navigationItem.name, - value: null, - icon: navigationItem.icon, - active: false, - isValid: true, - hasValue: false, - componentType: null, - subNavigation: [], - }; - - return item as NavigationItem; } - protected _addNavigationItem( - navigationItems: { [key: string]: NavigationItem }, - activeNavigationItem: NavigationItem | null, - navigationItem: NavigationItem, - parentNavigationItemIds: Set, - ) { - const newNavigationItem = this._getNavigationItem(activeNavigationItem, navigationItem); + public back() { + const previousId = this._history.pop(); - if (newNavigationItem) { - navigationItems[navigationItem.id] = newNavigationItem; - } else { - navigationItems[navigationItem.id] = this._getParentNavigationItemObject(navigationItem); - parentNavigationItemIds.add(navigationItem.id); + if (previousId === undefined) { + return; } - } - protected _addChildNavigationItem( - navigationItems: { [key: string]: NavigationItem }, - activeNavigationItem: NavigationItem | null, - navigationItem: NavigationItem, - ) { - const parent = navigationItems[navigationItem.parentId as number]; - const subNavigationItem = this._getNavigationItem(activeNavigationItem, navigationItem, false); - - // ignore children with unknown parents - if (parent && subNavigationItem) { - parent.subNavigation?.push(subNavigationItem); - parent.active = parent.active || activeNavigationItem?.parentId === navigationItem.parentId; - parent.hasValue = parent.hasValue || subNavigationItem.hasValue; - } + this._activeId = previousId; + this._buildState(); + this._notify(); } - public getNavigation = (): NavigationItem[] => { - const navigationItems: { [key: string]: NavigationItem } = {}; - const parentNavigationItemIds = new Set(); - const activeNavigationItem = this._getActiveQuestionNavigationItem(); - - // add all parents first, so children can be added independent of their position in the list - this._navigationItems - .filter((navigationItem) => !navigationItem.parentId) - .forEach((navigationItem) => { - this._addNavigationItem(navigationItems, activeNavigationItem, navigationItem, parentNavigationItemIds); - }); - - this._navigationItems - .filter((navigationItem) => navigationItem.parentId) - .forEach((navigationItem) => { - this._addChildNavigationItem(navigationItems, activeNavigationItem, navigationItem); - }); - - parentNavigationItemIds.forEach((id) => { - const subNavigation = navigationItems[id].subNavigation as NavigationItem[]; - - if (subNavigation.length === 0) { - delete navigationItems[id]; - } else { - navigationItems[id].isValid = subNavigation.every((child) => child.isValid); - } - }); - - return Object.values(navigationItems); - }; - - public isValid() { - return Object.keys(this._validationErrors).length === 0; + public reset() { + this._result = {}; + this._answerVariants.clear(); + this._history = []; + this._activeId = this._questions.length > 0 ? this._questions[0].id : null; + this._update(); + this._notify(); } } diff --git a/src/types.ts b/src/types.ts index 95b4d12..6a65e17 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,8 @@ -import { QuaireComponentType, QuaireValidationError } from './enums'; +import type { QuaireDefinitionProblemCode, QuaireErrorCode } from './constants.js'; + +type DistributiveOmit = T extends unknown ? Omit : never; + +export type QuaireId = string | number; export type QuaireResult = Record; @@ -7,95 +11,180 @@ export type QuairePartialResult = { [Key in keyof Result]?: Result[Key] | null; }; -export type QuaireBase< - Result extends object = QuaireResult, - Question extends QuaireQuestion = QuaireQuestion, - NavigationItem extends QuaireNavigationItem = QuaireNavigationItem, -> = { - saveAnswer(answer: unknown): void; - getActiveQuestion(): Question | null; - getResult(): QuairePartialResult; - getValidationErrors(): Record; - setActiveQuestionByNavigationItemId(navigationItemId: number): void; - setActiveQuestionByQuestionId(questionId: number): void; - isValid(): boolean; - getNavigation(): Array; -}; +export type QuaireScalar = string | number | boolean | null; -export type QuaireOptions< - Result extends object = QuaireResult, - Item extends QuaireItem = QuaireItem, - NavigationItem extends QuaireNavigationItem = QuaireNavigationItem, -> = { - items: Array; - navigationItems?: Array; - result?: QuairePartialResult; -}; +// a value, a list of possible values, or a comparison +export type QuaireValueMatcher = + | QuaireScalar + | Array + | { + gt?: number; + gte?: number; + lt?: number; + lte?: number; + answered?: boolean; + not?: QuaireValueMatcher; + }; -export type QuaireItemOption = { - [key: string]: unknown | QuaireItemOption; - label?: string; - value?: unknown; - nextItemId?: number; -}; +// all answers must match, a function can be used for everything else +export type QuaireCondition = Record | ((result: QuaireResult) => boolean); -export type QuaireRangeItemOption = { - [key: string]: unknown | QuaireRangeItemOption; - range?: Array; - nextItemId?: number; +// a question ID, or a list of conditional targets where the first match wins +export type QuaireNext = QuaireId | Array<{ when?: QuaireCondition; to: QuaireId }>; + +// built-in error codes, custom validators can return their own codes +export type QuaireError = QuaireErrorCode | (string & {}); + +export type QuaireValidator = (value: unknown, result: QuaireResult) => QuaireError | null | undefined; + +// properties that every question has and that variants can change +export type QuaireQuestionProperties = { + title: string; + description?: string; + required?: boolean; + defaultValue?: unknown; + next?: QuaireNext; }; -export type QuaireInputItemOption = { - [key: string]: unknown | QuaireInputItemOption; - type?: string; // HTML input type e.g. text, number, date, etc. - placeholder?: string; - nextItemId?: number; +export type QuaireVariant = { when: QuaireCondition } & Partial< + QuaireQuestionProperties & Props +>; + +export type QuaireQuestionDefinitionBase = { + id: QuaireId; + type: Type; + key: string; + navigationId?: QuaireId; + validate?: QuaireValidator; + variants?: Array>; +} & QuaireQuestionProperties & + Props; + +export type QuaireSelectOption = { + [key: string]: unknown; + label: string; + value: string | number | boolean; + next?: QuaireId; }; -export type QuaireItem = { - id: number; - question: string; - description: string; - required: boolean; - resultProperty: string; - dependsOnResultProperties: Array; - componentType: QuaireComponentType | string; - navigationItemId?: number; - selectOptions?: Array | QuaireItemOption; - rangeOption?: QuaireRangeItemOption; - inputOption?: QuaireInputItemOption; - defaultValue?: unknown; - nextItemId?: number; +export type QuaireSingleSelectDefinition = QuaireQuestionDefinitionBase< + 'SINGLE_SELECT', + { options: Array } +>; + +export type QuaireMultiSelectDefinition = QuaireQuestionDefinitionBase< + 'MULTI_SELECT', + { options: Array; minSelected?: number; maxSelected?: number } +>; + +export type QuaireBooleanDefinition = QuaireQuestionDefinitionBase< + 'BOOLEAN', + { trueLabel?: string; falseLabel?: string } +>; + +export type QuaireInputDefinition = QuaireQuestionDefinitionBase< + 'INPUT', + { + inputType?: string; // HTML input type, e.g. text, number, email + placeholder?: string; + min?: number; + max?: number; + minLength?: number; + maxLength?: number; + pattern?: string; + } +>; + +export type QuaireRangeDefinition = QuaireQuestionDefinitionBase<'RANGE', { min: number; max: number; step?: number }>; + +export type QuaireQuestionDefinition = + | QuaireSingleSelectDefinition + | QuaireMultiSelectDefinition + | QuaireBooleanDefinition + | QuaireInputDefinition + | QuaireRangeDefinition; + +// a definition with the matching variant applied +export type QuaireResolvedDefinition = + DistributiveOmit; + +export type QuaireQuestion = + QuaireResolvedDefinition & { + value: unknown; + error: QuaireError | null; + isValid: boolean; + hasValue: boolean; + }; + +// behavior of a component type, all functions are optional +export type QuaireComponent = { + // default: the value is not null, undefined, an empty string or an empty array + hasValue?(value: unknown): boolean; + // runs for answered questions after the required check + validate?(definition: QuaireResolvedDefinition, value: unknown): QuaireError | null; + // next question based on the answer, the value is missing for unanswered questions + getNext?(definition: QuaireResolvedDefinition, value: unknown): QuaireId | undefined; + // value that is shown in the navigation + getDisplayValue?(definition: QuaireResolvedDefinition, value: unknown): unknown; }; -export type QuaireNavigationItem = { - id: number; - name: string; - value?: unknown; +export type QuaireComponents = Record; + +export type QuaireNavigationDefinition = { + id: QuaireId; + parentId?: QuaireId | null; + title: string; icon?: string; - parentId?: number | null; - active?: boolean; - isValid?: boolean; - hasValue?: boolean; - subNavigation?: Array; - componentType?: QuaireComponentType | string | null; }; -export type QuaireQuestion = { - id: number; - navigationItemId?: number; - question: string; - description: string; - required: boolean; - resultProperty: string; +export type QuaireNavigationItem< + NavigationDefinition extends QuaireNavigationDefinition = QuaireNavigationDefinition, + Question = QuaireQuestion, +> = Omit & { + question: Question | null; value: unknown; - valueHasChanged?: boolean; - componentType: QuaireComponentType | string; + active: boolean; + hasValue: boolean; isValid: boolean; - dependsOnQuestions: Array; - selectOptions?: Array | null; - rangeOption?: QuaireRangeItemOption | null; - inputOption?: QuaireInputItemOption | null; - defaultValue?: unknown; - nextItemId?: number; + reachable: boolean; + children?: Array>; +}; + +export type QuaireProgress = { + answered: number; + total: number; +}; + +export type QuaireState< + Result extends object = QuaireResult, + Question = QuaireQuestion, + NavigationItem = QuaireNavigationItem, +> = { + activeQuestion: Question | null; + result: QuairePartialResult; + errors: Record; + navigation: Array; + path: Array; + progress: QuaireProgress; + isValid: boolean; + isComplete: boolean; + canGoBack: boolean; +}; + +export type QuaireOptions< + Result extends object = QuaireResult, + Definition extends QuaireQuestionDefinitionBase = QuaireQuestionDefinition, + NavigationDefinition extends QuaireNavigationDefinition = QuaireNavigationDefinition, +> = { + questions: Array; + navigation?: Array; + result?: QuairePartialResult; + components?: QuaireComponents; +}; + +export type QuaireDefinitionProblem = { + code: QuaireDefinitionProblemCode; + message: string; + questionId?: QuaireId; + navigationId?: QuaireId; }; diff --git a/src/utils.spec.ts b/src/utils.spec.ts index 3be29af..8440720 100644 --- a/src/utils.spec.ts +++ b/src/utils.spec.ts @@ -1,18 +1,31 @@ -import { getByPath } from './utils'; +import { hasValue, isNil, isSameId } from './utils.js'; -describe('getByPath', () => { - const object = { a: { b: [{ c: 'value' }] } }; +describe('utils', () => { + test('should detect null and undefined', () => { + expect(isNil(null)).toBe(true); + expect(isNil(undefined)).toBe(true); + expect(isNil(0)).toBe(false); + }); - test('should return the value at the path', () => { - expect(getByPath(object, ['a', 'b', '0', 'c'], null)).toBe('value'); + test('should treat false and 0 as values', () => { + expect(hasValue(false)).toBe(true); + expect(hasValue(0)).toBe(true); + expect(hasValue('text')).toBe(true); + expect(hasValue(['a'])).toBe(true); }); - test('should return the default value for a missing path', () => { - expect(getByPath(object, ['a', 'x', 'c'], null)).toBeNull(); - expect(getByPath(undefined, ['a'], null)).toBeNull(); + test('should treat null, undefined, empty strings and empty arrays as missing values', () => { + expect(hasValue(null)).toBe(false); + expect(hasValue(undefined)).toBe(false); + expect(hasValue('')).toBe(false); + expect(hasValue([])).toBe(false); }); - test('should return the default value for an empty path', () => { - expect(getByPath(object, [], null)).toBeNull(); + test('should compare string and number IDs', () => { + expect(isSameId(1, '1')).toBe(true); + expect(isSameId('a', 'a')).toBe(true); + expect(isSameId(1, 2)).toBe(false); + expect(isSameId(null, null)).toBe(false); + expect(isSameId(1, undefined)).toBe(false); }); }); diff --git a/src/utils.ts b/src/utils.ts index f1e64f6..9578fa0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,16 +1,16 @@ -export const isNil = (value: unknown): value is null | undefined => value === null || value === undefined; +import type { QuaireId } from './types.js'; -export const hasAnswer = (answer: unknown) => (Array.isArray(answer) ? answer.length > 0 : isNil(answer) === false); +export const isNil = (value: unknown): value is null | undefined => value === null || value === undefined; -export const getByPath = (object: unknown, path: Array, defaultValue: T): T => { - if (path.length === 0) { - return defaultValue; +// default check if a question has an answer, false and 0 are answers +export const hasValue = (value: unknown) => { + if (isNil(value) || value === '') { + return false; } - const value = path.reduce( - (current, key) => (isNil(current) ? undefined : (current as Record)[key]), - object, - ); - - return value === undefined ? defaultValue : (value as T); + return Array.isArray(value) ? value.length > 0 : true; }; + +// ids can be strings or numbers, e.g. from a CMS, so 1 and '1' are the same id +export const isSameId = (a: QuaireId | null | undefined, b: QuaireId | null | undefined) => + !isNil(a) && !isNil(b) && String(a) === String(b); diff --git a/vitest.config.mts b/vitest.config.mts index f6d6cc3..17a5831 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -7,7 +7,7 @@ export default defineConfig({ coverage: { provider: 'v8', include: ['src/**/*.ts', 'examples/**/*.ts'], - exclude: ['**/*.{test,spec}.ts', 'src/types.ts'], + exclude: ['**/*.{test,spec}.ts', 'src/types.ts', 'src/index.ts'], reportsDirectory: './coverage', reporter: ['html', 'text', 'lcov', 'json'], thresholds: { From 8cf28c2967c5acc217e04c3b5c7f324b90852e96 Mon Sep 17 00:00:00 2001 From: Johannes Werner Date: Thu, 8 Oct 2026 20:34:05 +0200 Subject: [PATCH 2/3] chore: ignore local claude plans Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 5276d2d..ceb86a1 100644 --- a/.gitignore +++ b/.gitignore @@ -105,3 +105,5 @@ dist # Webstorm .idea + +.claude/plans \ No newline at end of file From 734f8be73203d26e85b6afc77b9aedf180a01614 Mon Sep 17 00:00:00 2001 From: Johannes Werner Date: Thu, 8 Oct 2026 20:37:47 +0200 Subject: [PATCH 3/3] chore: ignore archived claude plans Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ceb86a1..97b42d6 100644 --- a/.gitignore +++ b/.gitignore @@ -106,4 +106,4 @@ dist # Webstorm .idea -.claude/plans \ No newline at end of file +.claude/plans*