Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ Optional extra settings for some [Question Types](#question-types)
| `questionType` | `linearscale` | String | `rating`, `promoter` | Sub type, fixed at creation; `rating` is a 1 to N scale drawn as icons, `promoter` is a 0 to 10 scale whose results show the promoter score; absent for a plain scale |
| `ratingIcon` | `linearscale` with `questionType` `rating` | string | `'star', 'heart', 'thumb'` | Set the icon of the rating, default: `'star'` |
| `goTo` | `dropdown, linearscale, multiple_unique` | Array | see [Jumps](#jumps) | Where to go next for an answer |
| `next` | `color, date, file, grid, long, multiple, ranking, short, time` | Integer / string | question id, `'submit'` | Where to go after the question, see [Jumps](#jumps) |
| `next` | `color, date, file, grid, long, multiple, ranking, section, short, time` | Integer / string | question id, `'submit'` | Where to go after the question or, on a section, after the section, see [Jumps](#jumps) |

### Jumps

Expand All @@ -291,6 +291,7 @@ An answer can lead to a later question or to the end of the form, as in Microsof
- Only the deprecated `datetime` accepts neither `goTo` nor `next` (400).
- A jump of the answer "Other" is for `multiple_unique` questions, as dropdowns have no answer "Other", and only matches while `allowOtherAnswer` is on.
- `next` also applies when the question is left unanswered.
- `next` on a section is where respondents go after the section, as "After this section go to" in Microsoft Forms: the id of a later section or `"submit"`; other targets are removed like other disallowed jumps. It applies when the path leaves the section towards the following section or the end of the form, so a jump of an answer out of the section wins over it, while a jump within the section still ends at it.

The respondent's path starts at the first question and follows these targets. It ends at a question that has no answer yet and a jump per answer past the following question, a jump of the answer "Other" only while `allowOtherAnswer` is on, and the questions after it appear once it is answered, as in Microsoft Forms. If such a question is optional and left empty, the form can be submitted without the questions after it. The first value of an answer decides, and answers to questions the submit view does not show, such as questions without a title, do not count. A target that is not a later question of the form, for example after the target was deleted, counts as the following question, and a jump of an option that no longer exists never matches. Questions off the path are skipped: answers to them are ignored, and their required flag does not apply. Editing a submission replaces all its stored answers, so answers to questions that are skipped now are removed.

Expand Down
4 changes: 4 additions & 0 deletions lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,10 @@ class Constants {
'next' => ['integer', 'string'],
];

public const EXTRA_SETTINGS_SECTION = [
'next' => ['integer', 'string'],
];

public const EXTRA_SETTINGS_GRID_QUESTION_TYPE = [
self::ANSWER_GRID_TYPE_CHECKBOX,
self::ANSWER_GRID_TYPE_NUMBER,
Expand Down
6 changes: 4 additions & 2 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,7 @@ public static function getAllowedExtraSettings(string $questionType): array {
Constants::ANSWER_TYPE_COLOR => Constants::EXTRA_SETTINGS_COLOR,
Constants::ANSWER_TYPE_TIME => Constants::EXTRA_SETTINGS_TIME,
Constants::ANSWER_TYPE_LINEARSCALE => Constants::EXTRA_SETTINGS_LINEARSCALE,
Constants::ANSWER_TYPE_SECTION => Constants::EXTRA_SETTINGS_SECTION,
default => [],
};
}
Expand Down Expand Up @@ -1296,7 +1297,7 @@ public static function mapJumpsOfCopies(array $questions, array $questionIdMap,
}

/**
* Remove the jumps that go to the question itself, to an earlier question or into the middle of another section, keeping the jumps to the end of the form, to later questions of the same section, to later sections and to questions that are not in the list
* Remove the jumps that go to the question itself, to an earlier question or into the middle of another section, and the jumps of a section to anything but a later section, keeping the jumps to the end of the form, to later questions of the same section, to later sections and to questions that are not in the list
*
* @param list<Question> $questions the questions of the form in their order
* @return list<Question> the questions whose jumps were removed, with their new extra settings set
Expand All @@ -1316,7 +1317,8 @@ public static function removeDisallowedJumps(array $questions): array {
foreach ($questions as $position => $question) {
$isDisallowed = static fn (mixed $target): bool => is_int($target) && isset($positions[$target])
&& ($positions[$target] <= $position
|| ($questions[$positions[$target]]->getType() !== Constants::ANSWER_TYPE_SECTION && $sections[$positions[$target]] !== $sections[$position]));
|| ($questions[$positions[$target]]->getType() !== Constants::ANSWER_TYPE_SECTION
&& ($question->getType() === Constants::ANSWER_TYPE_SECTION || $sections[$positions[$target]] !== $sections[$position])));
$extraSettings = $question->getExtraSettings();
$newSettings = $extraSettings;

Expand Down
23 changes: 19 additions & 4 deletions lib/Service/SubmissionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,7 @@ public function validateSubmission(array $questions, array $answers, string $for
* The questions on the path of the respondent: from the first question, each question leads to the target of its
* answer in `goTo`, else to its `next` target, else to the following question, until the end of the form.
* A target that is not a later question of the form counts as the following question.
* Leaving a section towards the following question or the end of the form goes to the `next` target of the section instead, if it has one.
* The path ends at a question that has no answer yet and a jump per answer past the following question.
*
* @param array $questions the questions of the form in their order
Expand All @@ -864,12 +865,18 @@ public static function getVisibleQuestions(array $questions, array $answers): ar
$questions = array_values($questions);
$positions = array_flip(array_column($questions, 'id'));
$visibleQuestions = [];
$sectionNext = null;

$position = 0;
while ($position < count($questions)) {
$question = $questions[$position];
$visibleQuestions[] = $question;
$toPosition = static fn (mixed $target): ?int => is_int($target) && isset($positions[$target]) && $positions[$target] > $position ? $positions[$target] : null;

if (($question['type'] ?? null) === Constants::ANSWER_TYPE_SECTION) {
$next = $question['extraSettings']['next'] ?? null;
$sectionNext = is_int($next) || is_string($next) ? $next : null;
}
$answer = $answers[$question['id']] ?? [];
if (self::awaitsAnswer($question, $answer, $position, $positions, count($questions))) {
break;
Expand All @@ -878,8 +885,15 @@ public static function getVisibleQuestions(array $questions, array $answers): ar
if ($target === Constants::JUMP_TARGET_SUBMIT) {
break;
}
$targetPosition = is_int($target) && isset($positions[$target]) ? $positions[$target] : null;
$position = $targetPosition !== null && $targetPosition > $position ? $targetPosition : $position + 1;
$targetPosition = $toPosition($target);
if ($targetPosition === null && $sectionNext !== null
&& ($position + 1 === count($questions) || ($questions[$position + 1]['type'] ?? null) === Constants::ANSWER_TYPE_SECTION)) {
if ($sectionNext === Constants::JUMP_TARGET_SUBMIT) {
break;
}
$targetPosition = $toPosition($sectionNext);
}
$position = $targetPosition ?? $position + 1;
}

return $visibleQuestions;
Expand Down Expand Up @@ -953,7 +967,7 @@ private static function awaitsAnswer(array $question, mixed $answer, int $positi
}

/**
* The jump target of a question for its answer: the target of the `goTo` entry matching the first value of the answer, else `next` on question types with `next`
* The jump target of a question for its answer: the target of the `goTo` entry matching the first value of the answer, else `next` on question types with `next` other than sections
*
* @param array $question the question
* @param mixed $answer the values of the answer to the question
Expand All @@ -974,7 +988,8 @@ private static function getJumpTarget(array $question, mixed $answer): string|in
}
}

$next = isset(FormsService::getAllowedExtraSettings((string)($question['type'] ?? ''))['next']) ? ($extraSettings['next'] ?? null) : null;
$type = (string)($question['type'] ?? '');
$next = $type !== Constants::ANSWER_TYPE_SECTION && isset(FormsService::getAllowedExtraSettings($type)['next']) ? ($extraSettings['next'] ?? null) : null;
return is_int($next) || is_string($next) ? $next : null;
}

Expand Down
67 changes: 67 additions & 0 deletions playwright/e2e/jump-issues.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,73 @@ test('jumps: in a form with sections, a jump into the middle of another section
])
})

test('jumps: a section jumps only to a later section or the end of the form', () => {
const section = (
id: number,
extraSettings: FormsQuestion['extraSettings'] = {},
): FormsQuestion => ({ ...short(id, extraSettings), type: 'section' })
const allowed = withoutDisallowedJumps([
section(1, { next: 2 }),
short(2),
section(3, { next: 5 }),
short(4),
section(5, { next: 'submit' }),
short(6),
])
expect(allowed.map((question) => question.extraSettings)).toEqual([
{},
{},
{ next: 5 },
{},
{ next: 'submit' },
{},
])
})

test('jumps: questions skipped by the next target of a section are unreachable', () => {
const section = (
id: number,
extraSettings: FormsQuestion['extraSettings'] = {},
): FormsQuestion => ({ ...short(id, extraSettings), type: 'section' })
expect([
...getJumpIssues([
section(1, { next: 5 }),
short(2),
section(3),
short(4),
section(5),
short(6),
]).unreachable,
]).toEqual([3, 4])
})

test('jump issues: two questions of a section that jump out of it are both named', () => {
const section = (id: number): FormsQuestion => ({
...short(id),
type: 'section',
})
expect([
...getJumpIssues([
section(1),
radio(2, { goTo: [{ optionId: 11, target: 6 }] }),
short(3, { next: 'submit' }),
short(4, { next: 5 }),
short(5),
section(6),
short(7),
]).leavingSection,
]).toEqual([2, 3])
expect([
...getJumpIssues([
section(1),
radio(2, { goTo: [{ optionId: 11, target: 4 }] }),
short(3),
section(4),
short(5),
]).leavingSection,
]).toEqual([])
})

test('jumps: only the jumps a reorder removed are removed from newer extra settings', () => {
const before = {
goTo: [
Expand Down
163 changes: 163 additions & 0 deletions playwright/e2e/sections.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,115 @@ test.describe('Sections', () => {
expect(stored.extraSettings.goTo).toEqual([])
})

test('After a section, respondents go to the section it names', async ({
page,
submitView,
}) => {
const form = await api(page.request, 'POST', '/forms')
for (const [type, text] of [
['section', 'Part one'],
['short', 'First'],
['section', 'Part two'],
['short', 'Second'],
['section', 'Part three'],
['short', 'Third'],
]) {
await api(page.request, 'POST', `/forms/${form.id}/questions`, {
type,
text,
})
}
await page.goto(`apps/forms/${form.hash}/edit`)

const select = page
.getByRole('listitem', { name: 'Section number 1' })
.getByRole('combobox', { name: 'After section 1 go to' })
await select.click()
await expect(page.getByRole('option')).toHaveText([
'Next section',
'Section 2: Part two',
'Section 3: Part three',
'End of the form',
])
const saved = page.waitForResponse(
(response) =>
response.request().method() === 'PATCH'
&& response.url().includes(`/forms/${form.id}/questions/`),
)
await page.getByRole('option', { name: 'Section 3: Part three' }).click()
expect((await saved).ok()).toBeTruthy()
await expect(
page
.getByRole('listitem', { name: 'Section number 3' })
.getByRole('combobox', { name: 'After section 3 go to' }),
).toBeVisible()

await page.goto(`apps/forms/${form.hash}/submit`)
await submitView.fillText('First', 'one')
await submitView.nextButton.click()
await expect(submitView.getQuestion('Part three')).toBeVisible()
await expect(submitView.nextButton).toHaveCount(0)
await submitView.fillText('Third', 'three')
const response = await submitView.submit()
expect(Object.keys(response.request().postDataJSON().answers)).toHaveLength(
2,
)
await expect(submitView.successMessage).toBeVisible()
})

test('A section that goes to a deleted section is named as a section and shows where respondents go', async ({
page,
}) => {
const form = await api(page.request, 'POST', '/forms')
const ids: number[] = []
for (const [type, text] of [
['section', 'Part one'],
['short', 'First'],
['section', 'Part two'],
['short', 'Second'],
['section', 'Part three'],
]) {
ids.push(
(
await api(page.request, 'POST', `/forms/${form.id}/questions`, {
type,
text,
})
).id,
)
}
await api(page.request, 'PATCH', `/forms/${form.id}/questions/${ids[0]}`, {
keyValuePairs: { extraSettings: { next: ids[4] } },
})
await api(page.request, 'PATCH', `/forms/${form.id}/questions/${ids[2]}`, {
keyValuePairs: { extraSettings: { next: 'submit' } },
})
await page.goto(`apps/forms/${form.hash}/edit`)

await page
.getByRole('listitem', { name: 'Section number 3' })
.getByRole('button', { name: 'Actions', exact: true })
.click()
await page
.getByRole('menuitem', { name: /^Delete (question|section)$/ })
.click()
await expect(
page
.getByRole('status')
.getByText(
'Section 1 went to a section that was deleted, so respondents now go to the next section instead.',
),
).toBeVisible()
const label = (number: number) =>
page
.getByRole('listitem', { name: `Section number ${number}` })
.locator('.jump-target-select__label')
await expect(label(1)).toHaveText(
'Next section (the chosen section was deleted or moved up)',
)
await expect(label(2)).toHaveText('End of the form')
})

test('Each page checks its required questions, an empty section is an info page', async ({
page,
submitView,
Expand Down Expand Up @@ -555,4 +664,58 @@ test.describe('Sections', () => {
await submitView.backButton.click()
await expect(submitView.getQuestion('Your name')).toBeVisible()
})

test('An empty section sends respondents on to its target without a page of its own', async ({
page,
submitView,
}) => {
const form = await api(page.request, 'POST', '/forms')
const ids: Record<string, number> = {}
for (const [type, text] of [
['section', 'Start'],
['short', 'First'],
['section', 'Jump'],
['section', 'Skipped'],
['short', 'Second'],
['section', 'End'],
['short', 'Third'],
['section', 'Finish'],
['section', 'Not reached'],
['short', 'Never'],
]) {
ids[text] = (
await api(page.request, 'POST', `/forms/${form.id}/questions`, {
type,
text: ['Jump', 'Finish'].includes(text) ? '' : text,
})
).id
}
for (const [section, next] of [
['Jump', ids.End],
['End', ids.Finish],
['Finish', 'submit'],
] as const) {
await api(
page.request,
'PATCH',
`/forms/${form.id}/questions/${ids[section]}`,
{ keyValuePairs: { extraSettings: { next } } },
)
}
await page.goto(`apps/forms/${form.hash}/submit`)

await submitView.fillText('First', 'one')
await submitView.nextButton.click()
await expect(submitView.getQuestion('End')).toBeVisible()
await expect(submitView.getQuestion('Skipped')).toBeHidden()
await expect(submitView.nextButton).toHaveCount(0)
await submitView.fillText('Third', 'three')
const response = await submitView.submit()
expect(
Object.keys(response.request().postDataJSON().answers)
.map(Number)
.sort((a, b) => a - b),
).toEqual([ids.First, ids.Third])
await expect(submitView.successMessage).toBeVisible()
})
})
17 changes: 13 additions & 4 deletions src/components/Questions/JumpTargetSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ export default defineComponent({
type: String,
default: null,
},

/**
* Label of a target that is not offered any more, by default going to the next question
*/
fallbackLabel: {
type: String,
default: () =>
t(
'forms',
'Next question (the chosen question was deleted or moved up)',
),
},
},

emits: ['update:modelValue'],
Expand All @@ -80,10 +92,7 @@ export default defineComponent({
return (
this.options.find((option) => option.id === this.modelValue) ?? {
id: this.modelValue,
label: t(
'forms',
'Next question (the chosen question was deleted or moved up)',
),
label: this.fallbackLabel,
}
)
},
Expand Down
Loading
Loading