Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { render } from '@testing-library/vue';
import VueRouter from 'vue-router';
import useKLiveRegion from 'kolibri-design-system/lib/composables/useKLiveRegion';
import ValidationMessage from '../index.vue';

jest.mock('kolibri-design-system/lib/composables/useKLiveRegion');

let sendPoliteMessage;

beforeEach(() => {
sendPoliteMessage = jest.fn();
useKLiveRegion.mockReturnValue({ sendPoliteMessage });
});

const renderWarning = props =>
render(ValidationMessage, {
props: { warning: true, ...props },
slots: { default: 'Too many options.' },
routes: new VueRouter(),
});

describe('ValidationMessage', () => {
it('announces a warning politely as it appears', () => {
renderWarning();
expect(sendPoliteMessage).toHaveBeenCalledWith('Too many options.');
});

it('does not announce a warning with alert off', () => {
renderWarning({ alert: false });
expect(sendPoliteMessage).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
// A polite region inserted already filled is often skipped by screen readers,
// so announce through KDS's persistent live region instead.
function announceWarning() {
if (props.warning) {
if (props.warning && props.alert) {
sendPoliteMessage(warningText.value.textContent.trim());
}
}
Expand All @@ -56,8 +56,8 @@
default: false,
},
/**
* Whether an error is an alert, read out as it appears. Off when the component showing
* it announces its messages itself.
* Whether the message is read out as it appears: an error as an alert, a warning
* politely. Off when the component showing it announces its messages itself.
*/
alert: {
type: Boolean,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ export const ConversionLoss = Object.freeze({
SETTINGS_REMOVED: 'SETTINGS_REMOVED',
});

export const RECOMMENDED_MAX_OPTIONS = 5;

export const RESPONSE_IDENTIFIER = 'RESPONSE';

export const SENTINEL_MARKER = 'data-studio-sentinel';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,18 @@
<div
v-if="mode === 'edit' || showAnswers"
class="editor-section"
data-testid="pairsSection"
>
<ValidationMessage v-if="tooFewPairsError">
{{ errorTooFewPairs$() }}
</ValidationMessage>
<ValidationMessage
v-if="tooManyPairsWarning"
key="too-many-pairs-warning"
warning
>
{{ tooManyPairsWarning }}
</ValidationMessage>

<div class="section-headers">
<h4
Expand Down Expand Up @@ -196,7 +204,14 @@
<div
v-if="mode === 'edit'"
class="editor-section"
data-testid="distractorsSection"
>
<ValidationMessage
v-if="tooManyDistractorsWarning"
warning
>
{{ tooManyDistractorsWarning }}
</ValidationMessage>
<div class="section-headers">
<h4
class="section-label"
Expand Down Expand Up @@ -240,7 +255,7 @@
import useKResponsiveWindow from 'kolibri-design-system/lib/composables/useKResponsiveWindow';
import { themeTokens } from 'kolibri-design-system/lib/styles/theme';
import { qtiEditorStrings } from '../../qtiEditorStrings';
import { ValidationError } from '../../constants';
import { RECOMMENDED_MAX_OPTIONS, ValidationError } from '../../constants';
import { useAssociateInteraction } from '../../composables/useAssociateInteraction';
import { useInteractionUpdates } from '../../composables/useInteractionUpdates';
import ValidationMessage from '../../components/ValidationMessage/index.vue';
Expand Down Expand Up @@ -301,6 +316,8 @@
errorRepeatedPair$,
errorDuplicateDistractorContent$,
errorEmptyChoiceContent$,
warningTooManyPairs$,
warningTooManyDistractors$,
} = qtiEditorStrings;

const questionTypeRef = computed(() => props.questionType);
Expand Down Expand Up @@ -448,6 +465,18 @@
errorCodes.value.includes(ValidationError.TOO_FEW_PAIRS),
);

const tooManyPairsText = warningTooManyPairs$({ count: RECOMMENDED_MAX_OPTIONS });
const tooManyPairsWarning = computed(() =>
props.mode === 'edit' && state.value.pairs.length > RECOMMENDED_MAX_OPTIONS
? tooManyPairsText
: null,
);

const tooManyDistractorsText = warningTooManyDistractors$({ count: RECOMMENDED_MAX_OPTIONS });
const tooManyDistractorsWarning = computed(() =>
state.value.distractors.length > RECOMMENDED_MAX_OPTIONS ? tooManyDistractorsText : null,
);

// Blankness is re-derived from the content rather than read off the
// EMPTY_CHOICE_CONTENT error's id, because an id may repeat across choices.
function isBlank(choice) {
Expand Down Expand Up @@ -580,6 +609,8 @@
onAddPair,
promptHasError,
tooFewPairsError,
tooManyPairsWarning,
tooManyDistractorsWarning,
pairErrorMessages,
distractorErrorMessages,
pairItemStyles,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { fireEvent, render, screen, within, waitFor } from '@testing-library/vue
import userEvent from '@testing-library/user-event';
import { nextTick } from 'vue';
import VueRouter from 'vue-router';
import useKLiveRegion from 'kolibri-design-system/lib/composables/useKLiveRegion';
import AssociateEditor from '../Editor.vue';
import { renderFocused } from '../../__tests__/renderFocused';

Expand All @@ -18,6 +19,15 @@ import { qtiEditorStrings as tr } from '../../../qtiEditorStrings';

jest.mock('shared/views/TipTapEditor/TipTapEditor/TipTapEditor');

jest.mock('kolibri-design-system/lib/composables/useKLiveRegion');

let sendPoliteMessage;

beforeEach(() => {
sendPoliteMessage = jest.fn();
useKLiveRegion.mockReturnValue({ sendPoliteMessage });
});

let mockWindowIsLarge = true;
let mockWindowIsSmall = false;
jest.mock('kolibri-design-system/lib/composables/useKResponsiveWindow', () => {
Expand Down Expand Up @@ -407,6 +417,134 @@ describe('AssociateEditor', () => {
});
});

describe('too many pairs and distractors warnings', () => {
const pairsWarning = () => tr.$tr('warningTooManyPairs', { count: 5 });
const distractorsWarning = () => tr.$tr('warningTooManyDistractors', { count: 5 });
const range = count => Array.from({ length: count }, (_, i) => i);
const choice = (id, content) =>
`<qti-simple-associable-choice identifier="${id}" match-max="1">${content}</qti-simple-associable-choice>`;
const countedXml = (
pairs,
distractors,
) => `<qti-associate-interaction response-identifier="RESPONSE">
<qti-prompt><p>Match each character to his adversary.</p></qti-prompt>
${range(pairs)
.map(i => choice(`left${i}`, `Left ${i}`) + choice(`right${i}`, `Right ${i}`))
.join('')}
${range(distractors)
.map(i => choice(`extra${i}`, `Extra ${i}`))
.join('')}
</qti-associate-interaction>`;
const countedDecl =
pairs => `<qti-response-declaration identifier="RESPONSE" cardinality="multiple" base-type="pair">
<qti-correct-response>
${range(pairs)
.map(i => `<qti-value>left${i} right${i}</qti-value>`)
.join('')}
</qti-correct-response>
</qti-response-declaration>`;
const renderCounted = (pairs, distractors, props = {}) =>
renderEditor({
interaction: blockWithDecl(countedXml(pairs, distractors), countedDecl(pairs)),
...props,
});

it('does not warn at 5 pairs and 5 distractors', () => {
renderCounted(5, 5);
expect(screen.queryByText(pairsWarning())).not.toBeInTheDocument();
expect(screen.queryByText(distractorsWarning())).not.toBeInTheDocument();
expect(sendPoliteMessage).not.toHaveBeenCalled();
});

it('warns only about pairs at 6 pairs, without reporting an error', () => {
const { emitted } = renderCounted(6, 5);
expect(
within(screen.getByTestId('pairsSection')).getByText(pairsWarning()),
).toBeInTheDocument();
expect(sendPoliteMessage).toHaveBeenCalledWith(pairsWarning());
expect(screen.queryByText(distractorsWarning())).not.toBeInTheDocument();
expect(emitted()['update:errors'].at(-1)[0]).toEqual([]);
});

it('warns only about distractors at 6 distractors, without reporting an error', () => {
const { emitted } = renderCounted(5, 6);
expect(
within(screen.getByTestId('distractorsSection')).getByText(distractorsWarning()),
).toBeInTheDocument();
expect(sendPoliteMessage).toHaveBeenCalledWith(distractorsWarning());
expect(screen.queryByText(pairsWarning())).not.toBeInTheDocument();
expect(emitted()['update:errors'].at(-1)[0]).toEqual([]);
});

it('warns and announces both at 6 pairs and 6 distractors', () => {
renderCounted(6, 6);
expect(
within(screen.getByTestId('pairsSection')).getByText(pairsWarning()),
).toBeInTheDocument();
expect(
within(screen.getByTestId('distractorsSection')).getByText(distractorsWarning()),
).toBeInTheDocument();
expect(sendPoliteMessage).toHaveBeenCalledWith(pairsWarning());
expect(sendPoliteMessage).toHaveBeenCalledWith(distractorsWarning());
});

it('warns and announces as soon as a blank 6th pair is added', async () => {
const user = userEvent.setup();
renderCounted(5, 0);
await user.click(button(tr.$tr('addPairBtn')));
expect(
within(screen.getByTestId('pairsSection')).getByText(pairsWarning()),
).toBeInTheDocument();
expect(sendPoliteMessage).toHaveBeenCalledWith(pairsWarning());
});

it('warns and announces once a 6th distractor is saved', async () => {
const user = userEvent.setup();
renderCounted(1, 5);
await user.click(button(tr.$tr('addDistractorBtn')));
await user.type(openTextarea(), 'Demetrius');
await user.click(button(tr.$tr('saveChipBtn')));
expect(
within(screen.getByTestId('distractorsSection')).getByText(distractorsWarning()),
).toBeInTheDocument();
expect(sendPoliteMessage).toHaveBeenCalledWith(distractorsWarning());
});

it('stops warning once a pair is deleted, leaving 5', async () => {
const user = userEvent.setup();
renderCounted(6, 0);
await user.click(button(tr.$tr('deletePairBtn', { number: 6 })));
expect(screen.queryByText(pairsWarning())).not.toBeInTheDocument();
});

it('stops warning once a distractor is deleted, leaving 5', async () => {
const user = userEvent.setup();
renderCounted(1, 6);
await user.click(button(tr.$tr('deleteDistractorBtn', { number: 6 })));
expect(screen.queryByText(distractorsWarning())).not.toBeInTheDocument();
});

it('still adds a 7th pair, without announcing the warning again', async () => {
const user = userEvent.setup();
renderCounted(6, 0);
await user.click(button(tr.$tr('addPairBtn')));
expect(
within(screen.getByTestId('pairsSection')).getByText(
tr.$tr('pairNumberLabel', { number: 7 }),
),
).toBeInTheDocument();
expect(openTextarea()).toHaveFocus();
expect(sendPoliteMessage.mock.calls.filter(([m]) => m === pairsWarning())).toHaveLength(1);
});

it('does not warn in view mode', () => {
renderCounted(6, 6, { mode: 'view', showAnswers: true });
expect(screen.queryByText(pairsWarning())).not.toBeInTheDocument();
expect(screen.queryByText(distractorsWarning())).not.toBeInTheDocument();
expect(sendPoliteMessage).not.toHaveBeenCalled();
});
});

describe('view mode', () => {
const viewProps = { mode: 'view' };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<div
v-if="mode === 'edit' || showAnswers"
class="choice-editor__section"
data-testid="answersSection"
>
<ValidationMessage v-if="noCorrectAnswerError">
{{ errorNoCorrectAnswer$() }}
Expand All @@ -74,6 +75,13 @@
>
{{ warningSingleChoice$() }}
</ValidationMessage>
<ValidationMessage
v-if="tooManyChoicesWarning"
key="too-many-choices-warning"
warning
>
{{ tooManyChoicesWarning }}
</ValidationMessage>
<h4
:id="answersHeaderId"
class="answers-header field-label"
Expand Down Expand Up @@ -267,7 +275,7 @@
import useKResponsiveWindow from 'kolibri-design-system/lib/composables/useKResponsiveWindow';
import { themePalette, themeTokens } from 'kolibri-design-system/lib/styles/theme';
import { qtiEditorStrings } from '../../qtiEditorStrings';
import { ValidationError } from '../../constants';
import { RECOMMENDED_MAX_OPTIONS, ValidationError } from '../../constants';
import { generateRandomSlug } from '../../utils/generateRandomSlug';
import { useChoiceInteraction } from '../../composables/useChoiceInteraction';
import { useInteractionUpdates } from '../../composables/useInteractionUpdates';
Expand Down Expand Up @@ -312,6 +320,7 @@
errorEmptyChoiceContent$,
errorDuplicateChoiceContent$,
warningSingleChoice$,
warningTooManyChoices$,
questionLabel$,
answersLabel$,
answersDescriptionSingleChoice$,
Expand Down Expand Up @@ -454,6 +463,12 @@
() =>
props.mode === 'edit' && errors.value.length === 0 && state.value.choices.length === 1,
);
const tooManyChoicesText = warningTooManyChoices$({ count: RECOMMENDED_MAX_OPTIONS });
const tooManyChoicesWarning = computed(() =>
props.mode === 'edit' && state.value.choices.length > RECOMMENDED_MAX_OPTIONS
? tooManyChoicesText
: null,
);

function onToggleCorrect(id) {
// Readonly controls can still emit `change`, e.g. arrow keys on a radio
Expand Down Expand Up @@ -562,6 +577,7 @@
noCorrectAnswerError,
tooManyCorrectError,
singleChoiceWarning,
tooManyChoicesWarning,
emptyChoiceIds,
duplicateChoiceIds,
choiceHasError,
Expand Down
Loading
Loading