Skip to content
Closed
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
1 change: 1 addition & 0 deletions docs/API_v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ Returns the questions and options of the given form (without submissions).
|-----------|---------|----------|-------------|
| _type_ | [QuestionType](DataStructure.md#question-types) | | The question-type of the new question |
| _text_ | String | yes | _Optional_ The text of the new question. |
| _subtype_ | String | yes | _Optional_ The sub type, stored as `extraSettings.questionType`: `checkbox`, `number` or `radio` for `grid`, `rating` for `linearscale` (a 1 to N scale drawn as icons). Any other value is rejected. |
| _position_ | Integer | yes | _(optional)_ 1-based position to insert the new question. When omitted the question is appended at the end. |
- Response: The new question object.

Expand Down
4 changes: 3 additions & 1 deletion docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,13 +263,15 @@ Optional extra settings for some [Question Types](#question-types)
| `timeMax` | `time` | string | - | Maximum allowed time to be chosen (as `HH:mm` string) |
| `timeMin` | `time` | string | - | Minimum allowed time to be chosen (as `HH:mm` string) |
| `timeRange` | `time` | Boolean | `true/false` | The time picker should query a time range |
| `optionsLowest` | `linearscale` | Integer | `0, 1` | Set the lowest value of the scale, default: `1` |
| `optionsLowest` | `linearscale` | Integer | `0, 1` | Set the lowest value of the scale, default: `1`; always `1` for the `rating` sub type |
| `optionsHighest` | `linearscale` | Integer | `2, 3, 4, 5, 6, 7, 8, 9, 10` | Set the highest value of the scale, default: `5` |
| `optionsLabelLowest` | `linearscale` | string | - | Set the label of the lowest value, default: `'Strongly disagree'` |
| `optionsLabelHighest` | `linearscale` | string | - | Set the label of the highest value, default: `'Strongly agree'` |
| `columns` | `grid` | Array | - | Array of column identifiers / labels for grid questions |
| `rows` | `grid` | Array | - | Array of row identifiers / labels for grid questions |
| `questionType` | `grid` | String | `checkbox`, `number`, `radio` | Type of cell for grid questions (checkbox, numeric input, or radio) |
| `questionType` | `linearscale` | String | `rating` | Sub type, fixed at creation; `rating` is a 1 to N scale drawn as icons; absent for a plain scale |
| `ratingIcon` | `linearscale` with `questionType` `rating` | string | `'star', 'heart', 'thumb'` | Set the icon of the rating, default: `'star'` |

### Option Types

Expand Down
8 changes: 8 additions & 0 deletions lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,14 @@ class Constants {
'optionsHighest' => ['integer', 'NULL'],
'optionsLabelLowest' => ['string', 'NULL'],
'optionsLabelHighest' => ['string', 'NULL'],
'questionType' => ['string'],
'ratingIcon' => ['string', 'NULL'],
];

public const RATING_ICONS = [
'star',
'heart',
'thumb',
];

public const EXTRA_SETTINGS_GRID = [
Expand Down
12 changes: 9 additions & 3 deletions lib/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
* @psalm-import-type FormsPartialForm from ResponseDefinitions
* @psalm-import-type FormsQuestion from ResponseDefinitions
* @psalm-import-type FormsQuestionType from ResponseDefinitions
* @psalm-import-type FormsQuestionGridCellType from ResponseDefinitions
* @psalm-import-type FormsQuestionSubtype from ResponseDefinitions
* @psalm-import-type FormsSubmission from ResponseDefinitions
* @psalm-import-type FormsSubmissions from ResponseDefinitions
* @psalm-import-type FormsUploadedFile from ResponseDefinitions
Expand Down Expand Up @@ -530,12 +530,13 @@ public function getQuestion(int $formId, int $questionId): DataResponse {
*
* @param int $formId the form id
* @param FormsQuestionType $type the new question type
* @param FormsQuestionGridCellType $subtype the new question subtype
* @param FormsQuestionSubtype $subtype the new question subtype
* @param string $text the new question title
* @param ?int $fromId (optional) id of the question that should be cloned
* @param ?int $position (optional) the position of the new question
* @return DataResponse<Http::STATUS_CREATED, FormsQuestion, array{}>
* @throws OCSBadRequestException Invalid type
* @throws OCSBadRequestException Invalid subtype
* @throws OCSBadRequestException Datetime question type no longer supported
* @throws OCSForbiddenException User has no permissions to get this form
* @throws OCSForbiddenException This form is archived and can not be modified
Expand Down Expand Up @@ -575,6 +576,11 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype
throw new OCSBadRequestException('Datetime question type no longer supported');
}

$extraSettings = $subtype ? ['questionType' => $subtype] : [];
if (!$this->formsService->areExtraSettingsValid($extraSettings, $type)) {
throw new OCSBadRequestException('Invalid subtype');
}

// Retrieve all active questions sorted by Order.
$questions = $this->questionMapper->findByForm($formId);

Expand All @@ -599,7 +605,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype
$question->setText($text);
$question->setDescription('');
$question->setIsRequired(false);
$question->setExtraSettings($subtype ? ['questionType' => $subtype] : []);
$question->setExtraSettings($extraSettings);

$question = $this->questionMapper->insert($question);

Expand Down
3 changes: 2 additions & 1 deletion lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* optionsLimitMax?: int,
* optionsLimitMin?: int,
* optionsLowest?: 0|1,
* ratingIcon?: "star"|"heart"|"thumb",
* shuffleOptions?: bool,
* timeMax?: string,
* timeMin?: string,
Expand All @@ -45,7 +46,7 @@
* }
*
* @psalm-type FormsQuestionType = "dropdown"|"multiple"|"multiple_unique"|"date"|"time"|"short"|"long"|"file"|"datetime"|"grid"|"linearscale"|"color"|"ranking"
* @psalm-type FormsQuestionGridCellType = "checkbox"|"number"|"radio"
* @psalm-type FormsQuestionSubtype = "checkbox"|"number"|"radio"|"rating"
*
* @psalm-type FormsQuestion = array{
* id: int,
Expand Down
14 changes: 14 additions & 0 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,20 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType
|| isset($extraSettings['optionsHighest']) && ($extraSettings['optionsHighest'] < 2 || $extraSettings['optionsHighest'] > 10)) {
return false;
}

$subtype = $extraSettings['questionType'] ?? null;
if ($subtype !== null && $subtype !== 'rating') {
return false;
}

if ($subtype === 'rating' && ($extraSettings['optionsLowest'] ?? 1) !== 1) {
return false;
}

if (isset($extraSettings['ratingIcon'])
&& ($subtype !== 'rating' || !in_array($extraSettings['ratingIcon'], Constants::RATING_ICONS, true))) {
return false;
}
}
return true;
}
Expand Down
15 changes: 12 additions & 3 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,14 @@
1
]
},
"ratingIcon": {
"type": "string",
"enum": [
"star",
"heart",
"thumb"
]
},
"shuffleOptions": {
"type": "boolean"
},
Expand All @@ -598,12 +606,13 @@
}
}
},
"QuestionGridCellType": {
"QuestionSubtype": {
"type": "string",
"enum": [
"checkbox",
"number",
"radio"
"radio",
"rating"
]
},
"QuestionType": {
Expand Down Expand Up @@ -1700,7 +1709,7 @@
"description": "the new question type"
},
"subtype": {
"$ref": "#/components/schemas/QuestionGridCellType",
"$ref": "#/components/schemas/QuestionSubtype",
"default": null,
"description": "the new question subtype"
},
Expand Down
8 changes: 6 additions & 2 deletions playwright/e2e/a11y-question-inputs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import { test as formTest } from '../support/fixtures/form.ts'
import { test as appNavigationTest } from '../support/fixtures/navigation.ts'
import { test as randomUserTest } from '../support/fixtures/random-user.ts'
import { test as topBarTest } from '../support/fixtures/topBar.ts'
import { GridSubtype, QuestionType } from '../support/sections/QuestionType.ts'
import {
GridSubtype,
LinearScaleSubtype,
QuestionType,
} from '../support/sections/QuestionType.ts'
import { FormsView } from '../support/sections/TopBarSection.ts'

const test = mergeTests(randomUserTest, appNavigationTest, formTest, topBarTest)
Expand Down Expand Up @@ -196,7 +200,7 @@ test.describe('Accessibility: aria attributes on question inputs', () => {
await appNavigation.clickNewForm()
await form.fillTitle('Test form')

await form.addQuestion(QuestionType.LinearScale)
await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Numbers)
const questions = await form.getQuestions()
await questions[0].fillTitle('Rate your experience')
await questions[0].fillDescription('From 1 to 5')
Expand Down
12 changes: 10 additions & 2 deletions playwright/e2e/question-editing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import { expect, mergeTests } from '@playwright/test'
import { test as formTest } from '../support/fixtures/form.ts'
import { test as appNavigationTest } from '../support/fixtures/navigation.ts'
import { test as randomUserTest } from '../support/fixtures/random-user.ts'
import { QuestionType } from '../support/sections/QuestionType.ts'
import {
LinearScaleSubtype,
QuestionType,
} from '../support/sections/QuestionType.ts'

const test = mergeTests(randomUserTest, appNavigationTest, formTest)

Expand All @@ -32,7 +35,12 @@ test.describe('Question editing lifecycle', () => {

for (const type of questionTypes) {
test(`Add a ${type} question`, async ({ form }) => {
await form.addQuestion(type)
await form.addQuestion(
type,
type === QuestionType.LinearScale
? LinearScaleSubtype.Numbers
: undefined,
)

const questions = await form.getQuestions()
expect(questions).toHaveLength(1)
Expand Down
174 changes: 174 additions & 0 deletions playwright/e2e/rating-question.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import { expect, mergeTests } from '@playwright/test'
import { test as formTest } from '../support/fixtures/form.ts'
import { test as appNavigationTest } from '../support/fixtures/navigation.ts'
import { test as randomUserTest } from '../support/fixtures/random-user.ts'
import { test as resultsTest } from '../support/fixtures/results.ts'
import { test as submitTest } from '../support/fixtures/submit.ts'
import { test as topBarTest } from '../support/fixtures/topBar.ts'
import { waitForApiResponse } from '../support/helpers.ts'
import {
LinearScaleSubtype,
QuestionType,
} from '../support/sections/QuestionType.ts'
import { FormsView } from '../support/sections/TopBarSection.ts'

const test = mergeTests(
randomUserTest,
appNavigationTest,
formTest,
topBarTest,
submitTest,
resultsTest,
)

test.describe('Rating question', () => {
test.beforeEach(async ({ page, appNavigation, form }) => {
await page.goto('apps/forms')
await page.waitForURL(/apps\/forms\/?$/)
await appNavigation.clickNewForm()
await form.fillTitle('Rating test form')

await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Rating)
const questions = await form.getQuestions()
await questions[0].fillTitle('Rate the service')
await questions[0].fillDescription('One star is poor')
})

test('Names the rating by its question and each option by its value', async ({
page,
topBar,
submitView,
}) => {
await expect(
page.getByRole('group', { name: 'Rate the service' }),
).toBeVisible()
await topBar.toggleView(FormsView.View)

const group = submitView.getQuestion('Rate the service').getByRole('group')
await expect(group).toHaveAccessibleName('Rate the service')
await expect(group).toHaveAccessibleDescription('One star is poor')
const options = group.getByRole('radio')
await expect(options).toHaveCount(5)
for (let value = 1; value <= 5; value++) {
await expect(options.nth(value - 1)).toHaveAccessibleName(
`${value} of 5`,
)
}
})

test('Restores the rating from local storage on reload', async ({
topBar,
submitView,
page,
}) => {
await topBar.toggleView(FormsView.View)
await submitView.checkRadio('Rate the service', '4 of 5')

await page.reload()

await expect(
submitView
.getQuestion('Rate the service')
.getByRole('radio', { name: '4 of 5' }),
).toBeChecked()
})

test('Restores the rating when editing a submission', async ({
topBar,
submitView,
resultsView,
page,
}) => {
await topBar.toggleView(FormsView.View)
await submitView.checkRadio('Rate the service', '4 of 5')
await submitView.submit()
await expect(submitView.successMessage).toBeVisible()

await page.goto(page.url().replace(/\/submit.*$/, '/results'))
await expect(page.getByText('Linear scale (Rating)')).toBeVisible()
await resultsView.switchToResponses()
await resultsView.editSubmission()

await expect(
submitView
.getQuestion('Rate the service')
.getByRole('radio', { name: '4 of 5' }),
).toBeChecked()
})

test('Shows an error when a required rating is left empty', async ({
form,
topBar,
submitView,
}) => {
const questions = await form.getQuestions()
await questions[0].toggleRequired()
await topBar.toggleView(FormsView.View)

await submitView.submitButton.click()

const question = submitView.getQuestion('Rate the service')
await expect(
question.getByText('You must answer this question'),
).toBeVisible()
await expect(question.getByRole('radio').first()).toHaveAttribute(
'aria-invalid',
'true',
)
})

test('Focuses a new rating question and offers to insert a question after it', async ({
form,
page,
}) => {
await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Rating)

const questions = await form.getQuestions()
await expect(questions[1].titleInput).toBeFocused()
await expect(
page.getByRole('button', {
name: 'Insert question after question 1',
}),
).toHaveCount(1)
})

test('Offers as many options as the highest rating chosen in the editor', async ({
form,
page,
topBar,
submitView,
}) => {
const questions = await form.getQuestions()
await questions[0].openActionsMenu()
const saved = waitForApiResponse(page, 'PATCH')
await page.getByRole('combobox', { name: 'Highest rating' }).click()
await page.getByRole('option', { name: '7', exact: true }).click()
await saved
await page.keyboard.press('Escape')
await topBar.toggleView(FormsView.View)

const options = submitView.getQuestion('Rate the service').getByRole('radio')
await expect(options).toHaveCount(7)
await expect(options.last()).toHaveAccessibleName('7 of 7')
})

test('Saves the icon chosen last in the editor', async ({ form, page }) => {
const questions = await form.getQuestions()
await questions[0].openActionsMenu()
const savedStars = page.waitForResponse(
(response) =>
response.request().method() === 'PATCH'
&& response.request().postDataJSON()?.keyValuePairs?.extraSettings
?.ratingIcon === null,
)
await page.getByRole('radio', { name: 'Hearts' }).click({ force: true })
await page.getByRole('radio', { name: 'Stars' }).click({ force: true })
await savedStars
await expect(page.getByRole('radio', { name: 'Stars' })).toBeChecked()
})
})
Loading
Loading