Skip to content
Open
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
11 changes: 11 additions & 0 deletions lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class Constants {
public const ANSWER_TYPE_MULTIPLE = 'multiple';
public const ANSWER_TYPE_MULTIPLEUNIQUE = 'multiple_unique';
public const ANSWER_TYPE_RANKING = 'ranking';
public const ANSWER_TYPE_RATING = 'rating';
public const ANSWER_TYPE_SHORT = 'short';
public const ANSWER_TYPE_TIME = 'time';

Expand All @@ -121,6 +122,7 @@ class Constants {
self::ANSWER_TYPE_MULTIPLE,
self::ANSWER_TYPE_MULTIPLEUNIQUE,
self::ANSWER_TYPE_RANKING,
self::ANSWER_TYPE_RATING,
self::ANSWER_TYPE_SHORT,
self::ANSWER_TYPE_TIME,
];
Expand Down Expand Up @@ -219,6 +221,15 @@ class Constants {
'rows' => ['array'],
];

/**
* How many icons a rating question offers, and which icon to draw.
* ratingIcon is one of 'star' (default), 'heart' or 'thumb'.
*/
public const EXTRA_SETTINGS_RATING = [
'maxRating' => ['integer', 'NULL'],
'ratingIcon' => ['string', 'NULL'],
];

public const EXTRA_SETTINGS_RANKING = [
'shuffleOptions' => ['boolean'],
];
Expand Down
1 change: 1 addition & 0 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,7 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType
Constants::ANSWER_TYPE_DATE => Constants::EXTRA_SETTINGS_DATE,
Constants::ANSWER_TYPE_GRID => Constants::EXTRA_SETTINGS_GRID,
Constants::ANSWER_TYPE_RANKING => Constants::EXTRA_SETTINGS_RANKING,
Constants::ANSWER_TYPE_RATING => Constants::EXTRA_SETTINGS_RATING,
Constants::ANSWER_TYPE_TIME => Constants::EXTRA_SETTINGS_TIME,
Constants::ANSWER_TYPE_LINEARSCALE => Constants::EXTRA_SETTINGS_LINEARSCALE,
default => [],
Expand Down
13 changes: 13 additions & 0 deletions lib/Service/SubmissionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,19 @@ public function validateSubmission(array $questions, array $answers, string $for
}

// Check if all answers are within the possible options
// A rating carries no options, so it is validated on its own rather than as a
// predefined-option type: the answer is the number of icons chosen.
if ($question['type'] === Constants::ANSWER_TYPE_RATING) {
$maxRating = $question['extraSettings']['maxRating'] ?? 5;
foreach ($answers[$questionId] as $answer) {
if (!ctype_digit((string)$answer)
|| (int)$answer < 1
|| (int)$answer > $maxRating) {
throw new \InvalidArgumentException(sprintf('The answer for question "%s" must be a whole number between 1 and %d.', $question['text'], $maxRating));
}
}
}

if (in_array($question['type'], Constants::ANSWER_TYPES_PREDEFINED) && empty($question['extraSettings']['allowOtherAnswer'])) {
// Normalize option IDs once for consistent comparison (DB may return ints, request may send strings)
$optionIds = $this->normalizeOptionIds($question['options'] ?? []);
Expand Down
272 changes: 272 additions & 0 deletions src/components/Questions/QuestionRating.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
<!--
- SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->

<template>
<Question
v-bind="questionProps"
:titlePlaceholder="answerType.titlePlaceholder"
:warningInvalid="answerType.warningInvalid"
:errorMessage="errorMessage"
v-on="commonListeners">
<template #actions>
<NcActionInput
:modelValue="maxRating"
type="multiselect"
:clearable="false"
:label="t('forms', 'Number of icons')"
labelOutside
:options="[2, 3, 4, 5, 6, 7, 8, 9, 10]"
required
@update:modelValue="onMaxRatingChange">
<template #icon>
<NcIconSvgWrapper :svg="outlineIcon" />
</template>
</NcActionInput>
<NcActionRadio
v-for="icon in iconChoices"
:key="icon.id"
:modelValue="ratingIcon"
:name="`ratingIcon_${id}`"
:value="icon.id"
@update:modelValue="onRatingIconChange(icon.id)">
{{ icon.label }}
</NcActionRadio>
</template>

<fieldset class="rating" :disabled="!readOnly">
<legend class="hidden-visually">
{{ text || t('forms', 'Rating') }}
</legend>
<label
v-for="value in maxRating"
:key="value"
class="rating__icon"
:class="{ 'rating__icon--on': value <= currentValue }">
<input
class="hidden-visually"
type="radio"
:name="`rating_${id}`"
:aria-label="
n('forms', '%n of {max}', '%n of {max}', value, {
max: maxRating,
})
"
:value="value"
:checked="value === currentValue"
:required="isRequired && !currentValue"
@change="onPick(value)" />
<NcIconSvgWrapper
:svg="value <= currentValue ? filledIcon : outlineIcon" />
</label>
<NcButton
v-if="readOnly && currentValue"
variant="tertiary"
@click="onPick(0)">
{{ t('forms', 'Clear') }}
</NcButton>
</fieldset>
</Question>
</template>

<script lang="ts">
import IconHeartFilled from '@material-symbols/svg-400/outlined/favorite-fill.svg?raw'
import IconHeart from '@material-symbols/svg-400/outlined/favorite.svg?raw'
import IconStarFilled from '@material-symbols/svg-400/outlined/star-fill.svg?raw'
import IconStar from '@material-symbols/svg-400/outlined/star.svg?raw'
import IconThumbFilled from '@material-symbols/svg-400/outlined/thumb_up-fill.svg?raw'
import IconThumb from '@material-symbols/svg-400/outlined/thumb_up.svg?raw'
import { n, t } from '@nextcloud/l10n'
import { computed, defineComponent } from 'vue'
import NcActionInput from '@nextcloud/vue/components/NcActionInput'
import NcActionRadio from '@nextcloud/vue/components/NcActionRadio'
import NcButton from '@nextcloud/vue/components/NcButton'
import NcIconSvgWrapper from '@nextcloud/vue/components/NcIconSvgWrapper'
import Question from './Question.vue'
import {
QUESTION_EMITS,
QUESTION_PROPS,
useQuestion,
} from '../../composables/useQuestion.ts'

/** Matches the default assumed server-side when maxRating is unset. */
const DEFAULT_MAX_RATING = 5

export default defineComponent({
name: 'QuestionRating',

components: {
NcActionInput,
NcActionRadio,
NcButton,
NcIconSvgWrapper,
Question,
},

props: QUESTION_PROPS,
emits: [...QUESTION_EMITS, 'update:values'],

setup(props, { emit }) {
const question = useQuestion(props, { emit })

const extraSettings = computed(
() => (props.extraSettings as Record<string, unknown> | undefined) ?? {},
)

const maxRating = computed<number>(() => {
const configured = extraSettings.value.maxRating
return typeof configured === 'number'
&& configured >= 2
&& configured <= 10
? configured
: DEFAULT_MAX_RATING
})

const ratingIcon = computed<string>(() => {
const icon = extraSettings.value.ratingIcon
return typeof icon === 'string'
&& ['star', 'heart', 'thumb'].includes(icon)
? icon
: 'star'
})

const iconChoices = computed(() => [
{ id: 'star', label: t('forms', 'Stars') },
{ id: 'heart', label: t('forms', 'Hearts') },
{ id: 'thumb', label: t('forms', 'Thumbs up') },
])

const outlineIcon = computed(
() =>
({ star: IconStar, heart: IconHeart, thumb: IconThumb })[
ratingIcon.value
],
)

const filledIcon = computed(
() =>
({
star: IconStarFilled,
heart: IconHeartFilled,
thumb: IconThumbFilled,
})[ratingIcon.value],
)

const currentValue = computed<number>(
() => parseInt((props.values as string[])?.[0]) || 0,
)

/**
* @param value the chosen count, or 0 to clear the answer
*/
function onPick(value: number): void {
emit('update:values', value ? [String(value)] : [])
question.errorMessage.value = null
}

/**
* @param value how many icons to offer
*/
function onMaxRatingChange(value: number): void {
question.onExtraSettingsChange({
maxRating: value === DEFAULT_MAX_RATING ? null : value,
})
}

/**
* @param icon the chosen icon set
*/
function onRatingIconChange(icon: string): void {
question.onExtraSettingsChange({
ratingIcon: icon === 'star' ? null : icon,
})
}

/**
* A rating cannot be partly filled in, so the only failure is a required
* question left unanswered.
*/
async function validate(): Promise<boolean> {
if (props.isRequired && !currentValue.value) {
question.errorMessage.value = t(
'forms',
'You must answer this question',
)
return false
}
question.errorMessage.value = null
return true
}

return {
...question,
currentValue,
filledIcon,
iconChoices,
maxRating,
n,
onMaxRatingChange,
onPick,
onRatingIconChange,
outlineIcon,
ratingIcon,
t,
validate,
}
},
})
</script>

<style lang="scss" scoped>
.rating {
align-items: center;
border: none;
display: flex;
// Ten icons plus a Clear button do not fit one line on a narrow screen.
flex-wrap: wrap;
gap: 2px;
margin: 0;
padding: 0;

&__icon {
align-items: center;
border-radius: var(--border-radius);
color: var(--color-text-maxcontrast);
cursor: pointer;
display: inline-flex;
justify-content: center;
// A comfortable pointer target; the icon itself stays small.
min-height: var(--default-clickable-area);
min-width: var(--default-clickable-area);
transition:
color 0.1s ease-in-out,
transform 0.1s ease-in-out;

&--on {
color: var(--color-favorite, var(--color-warning));
}

&:hover {
transform: scale(1.1);
}

&:focus-within {
outline: 2px solid var(--color-primary-element);
outline-offset: -2px;
}

@media (prefers-reduced-motion: reduce) {
transition: none;

&:hover {
transform: none;
}
}
}

&:disabled &__icon {
cursor: default;
}
}
</style>
12 changes: 12 additions & 0 deletions src/models/AnswerTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import IconPalette from '@material-symbols/svg-400/outlined/palette.svg?raw'
import IconRadioboxMarked from '@material-symbols/svg-400/outlined/radio_button_checked.svg?raw'
import IconClockOutline from '@material-symbols/svg-400/outlined/schedule.svg?raw'
import IconTextShort from '@material-symbols/svg-400/outlined/short_text.svg?raw'
import IconStar from '@material-symbols/svg-400/outlined/star.svg?raw'
import IconTextLong from '@material-symbols/svg-400/outlined/subject.svg?raw'
import IconSwapVertical from '@material-symbols/svg-400/outlined/swap_vert.svg?raw'
import { t } from '@nextcloud/l10n'
Expand All @@ -30,6 +31,7 @@ import QuestionLinearScale from '../components/Questions/QuestionLinearScale.vue
import QuestionLong from '../components/Questions/QuestionLong.vue'
import QuestionMultiple from '../components/Questions/QuestionMultiple.vue'
import QuestionRanking from '../components/Questions/QuestionRanking.vue'
import QuestionRating from '../components/Questions/QuestionRating.vue'
import QuestionShort from '../components/Questions/QuestionShort.vue'
import { OptionType } from './Constants.ts'

Expand Down Expand Up @@ -267,6 +269,16 @@ const answerTypes: Record<string, AnswerTypeConfig> = {
warningInvalid: t('forms', 'This question needs a title!'),
},

rating: {
component: markRaw(QuestionRating),
icon: IconStar,
label: t('forms', 'Rating'),
predefined: false,

titlePlaceholder: t('forms', 'Rating question title'),
warningInvalid: t('forms', 'This question needs a title!'),
},

color: {
component: markRaw(QuestionColor),
icon: IconPalette,
Expand Down
Loading