diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md
index 06f8615e01..db298be9d8 100644
--- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md
+++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md
@@ -39,7 +39,9 @@ Prompts, choices, items and hints are edited in `TipTapEditor` with `format="htm
> [!IMPORTANT]
> In `parse`, read any field TipTap loads as HTML with `getContentHTML` (or `getPromptHTML`) from `serialization/xml.js`, never `innerHTML` or `XMLSerializer`. XML serialization self-closes empty elements (``); the HTML parser doesn't treat `/>` as closing, so everything after it is nested inside and lost.
>
-> On build, pass the HTML to `buildXmlNode({ innerHTML })`, which parses it as HTML and re-creates it as XML.
+> On build, pass the HTML to `buildXmlNode({ innerHTML })`, which parses it as HTML and re-creates it as XML. Stored MathML travels through TipTap in `span[data-mathml]`; pasted carriers keep LaTeX or text instead.
+
+List the HTML fields and their editor modes in the interaction descriptor's `richTextFields`. `isEditableItem` checks them against the TipTap schema; a lossy field makes the item read-only without suppressing `validateQtiItem` errors.
> [!NOTE]
> A node view that shows itself as selected, like the inline choice chip, uses `--brand-secondary-v100`, the background of KDS's global `::selection`, with `--tokens-text` for its text.
diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js
index 13e17d418f..48d997cf6c 100644
--- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js
+++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js
@@ -45,6 +45,20 @@ afterAll(() => {
});
describe('QTIEditor', () => {
+ it('enables Edit on the first render of a list of editable rich-text questions', () => {
+ const raw_data = VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', 'Pick one.');
+ renderComponent(
+ Array.from({ length: 24 }, (_, index) => ({
+ ...QTI_ITEM,
+ raw_data,
+ assessment_id: `question-${index}`,
+ })),
+ );
+ const editActions = screen.getAllByRole('button', { name: toolbarLabelEdit$() });
+ expect(editActions).toHaveLength(24);
+ editActions.forEach(action => expect(action).toBeEnabled());
+ });
+
describe('opening a question', () => {
it('opens a question from its Edit action', async () => {
renderComponent([QTI_ITEM]);
diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/validateItem.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/validateItem.spec.js
index cbd4769568..a70a4fb884 100644
--- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/validateItem.spec.js
+++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/validateItem.spec.js
@@ -1,11 +1,16 @@
+import { DOMParser as SchemaParser } from '@tiptap/pm/model';
import { isEditableItem, validateItemShape, validateQtiItem } from '../validateItem';
-import { QuestionType, ValidationError } from '../constants';
+import { QuestionType, ResponseProcessingTemplate, ValidationError } from '../constants';
import { assembleItemXml } from '../serialization/assembleItem';
import { parseItem } from '../serialization/parseItem';
+import { choiceInteractionDescriptor } from '../interactions/choice/Descriptor';
import { textEntryInteractionDescriptor } from '../interactions/textEntry/Descriptor';
+import { inlineChoiceInteractionDescriptor } from '../interactions/inlineChoice/Descriptor';
import { validateTextEntryInteraction } from '../interactions/textEntry/validation';
import {
+ CHOICE_ITEM_DOCUMENT_WITH_CATALOG_REFERENCE,
VALID_CHOICE_ITEM_DOCUMENT,
+ NUMERIC_ITEM_DOCUMENT,
CHOICE_ITEM_DOCUMENT_NO_PROMPT,
CHOICE_ITEM_DOCUMENT_NO_CORRECT_ANSWER,
CHOICE_ITEM_DOCUMENT_NO_CORRECT_ANSWER_WITH_STIMULUS,
@@ -15,6 +20,8 @@ import {
NO_INTERACTION_ITEM_DOCUMENT,
INLINE_CHOICE_ITEM_DOCUMENT,
VALID_MATCH_ITEM_DOCUMENT,
+ VALID_ASSOCIATE_ITEM_DOCUMENT,
+ ORDERING_ITEM_DOCUMENT_NO_PROMPT,
MATCH_THREE_SETS_XML,
MATCH_XML,
MULTI_TEXT_ENTRY_ITEM_DOCUMENT,
@@ -22,6 +29,19 @@ import {
MULTI_INTERACTION_ITEM_DOCUMENT,
UNRECOGNIZED_INTERACTION_ITEM_DOCUMENT,
} from '../utils/testingFixtures';
+import { XSI_NS } from '../serialization/xml';
+
+it('reports duplicate associate choices even with a large match capacity', () => {
+ const xml = VALID_ASSOCIATE_ITEM_DOCUMENT.replace(
+ /match-max="1">Antonio/,
+ 'match-max="6">Antonio',
+ ).replace('>Capulet<', '>Antonio<');
+ expect(validateQtiItem(xml)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ code: ValidationError.DUPLICATE_DISTRACTOR_CONTENT }),
+ ]),
+ );
+});
const codesOf = errors => errors.map(error => error.code);
@@ -30,6 +50,14 @@ describe('validateQtiItem', () => {
expect(validateQtiItem(VALID_CHOICE_ITEM_DOCUMENT)).toEqual([]);
});
+ it('reports a missing correct answer for a catalog reference', () => {
+ const xml = CHOICE_ITEM_DOCUMENT_WITH_CATALOG_REFERENCE.replace(
+ / Context Lysander Mammal test test The sky is ', 'The sky is '],
+ ['match row', VALID_MATCH_ITEM_DOCUMENT, '>Dog', 'Dog'],
+ ['ordering option', completeOrder, '>Mercury ${text}${formula}`;
+ const xml = source.replace(
+ before,
+ before.startsWith(' ') ? paragraph : before.replace(text, `${paragraph} First ${math(' Pick one.A Context Extra \n\nA\n
\n\nA\n
', '
');
+ expect(isEditableItem(parseItem(wrapped), wrapped)).toBe(true);
+});
+
+it.each([
+ ['xml:id', '\n\nA\n
test
', 'Pick one.
'; + const xml = VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', prompt); + const { container, emitted } = renderDocument(xml, { mode: 'view' }, { open: jest.fn() }); + const card = container.querySelector('.question-card'); + + if (kept) { + expect(card).toHaveClass('is-clickable'); + } else { + expect(card).not.toHaveClass('is-clickable'); + expect(screen.getByText(tr.unsupportedItemMessage$())).toBeVisible(); + } + await fireEvent.click(card); + expect(emitted().open?.length ?? 0).toBe(kept ? 1 : 0); + }, +); + +const readFixture = filename => + fs.readFileSync( + path.join(__dirname, '../../../../../../../tests/utils/qti/fixtures', filename), + 'utf8', + ); + +const readConverterFixture = filename => + readFixture(filename) + .split('\n') + .map(line => line.trim()) + .join(''); + +const convertedInput = readFixture('input_question.xml'); + +it.each(['textEntryLabel', 'singleSelectLabel'])( + 'converts the displayed numeric answer to %s without saving on open', + async type => { + const user = userEvent.setup(); + const { emitted, updateProps } = renderDocument( + NUMERIC_ITEM_DOCUMENT.replace('1234.5', '1,234.5'), + { mode: 'view', language: 'fr' }, + ); + await updateProps({ mode: 'edit', language: 'en' }); + expect(screen.getByRole('textbox', { name: tr.answerValuePlaceholder$() })).toHaveValue( + '1234.5', + ); + expect(emitted()['update:rawData']).toBeUndefined(); + + const selector = screen.getByRole('group', { name: tr.$tr('typeLabel') }); + await user.click(within(selector).getByText(tr.$tr('responseTypeLabel'))); + await user.click(screen.getAllByText(tr.$tr(type)).at(-1)); + const confirm = screen.queryByRole('button', { name: tr.$tr('changeQuestionTypeAction') }); + if (confirm) await user.click(confirm); + await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() })); + + const [saved] = emitted()['update:rawData'].at(-1); + const doc = parseXML(saved); + const answerSelector = + type === 'textEntryLabel' ? 'qti-correct-response qti-value' : 'qti-simple-choice'; + expect(doc.querySelector(answerSelector).textContent).toBe('1234.5'); + }, +); + +it('shows Incomplete when stored XML gets an invalid numeric answer in view mode', async () => { + const { emitted, updateProps } = renderDocument(NUMERIC_ITEM_DOCUMENT, { mode: 'view' }); + expect(screen.queryByTestId('incompleteIndicator')).not.toBeInTheDocument(); + + await updateProps({ + item: { + assessment_id: 'item-id', + type: AssessmentItemTypes.QTI, + raw_data: NUMERIC_ITEM_DOCUMENT.replace('1234.5', 'bad'), + }, + }); + + expect(screen.getByTestId('incompleteIndicator')).toBeVisible(); + expect(emitted()['update:rawData']).toBeUndefined(); +}); + +it('clears the publishing error when a malformed item is replaced with valid XML', async () => { + const { emitted, updateProps } = renderDocument('Pick .
`, + ); + expect(parseXML(xml).querySelector('mtext').textContent).toBe('a\rb'); + const { emitted } = renderDocument(xml); + expect(await screen.findByTestId('unsupportedMessage')).toBeVisible(); + expect(emitted()['update:rawData']).toBeUndefined(); +}); + +it.each([ + [ + VALID_ASSOCIATE_ITEM_DOCUMENT.replace('match-max="1">Antonio', 'match-max="12">Antonio'), + 'qti-simple-associable-choice[identifier="choice_aaa11111"]', + 'match-max', + '12', + ], + [ + CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace( + 'First
Second
Pick one.

After.
', + ); + const { emitted } = renderDocument(xml); + const image = await screen.findByRole('img', { name: 'diagram' }); + Object.defineProperties(image, { + naturalWidth: { value: 400 }, + naturalHeight: { value: 200 }, + }); + Object.defineProperty(image.closest('.ProseMirror'), 'clientWidth', { value: 300 }); + await fireEvent.load(image); + await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() })); + expect(emitted()['update:rawData']).toBeUndefined(); +}); + +it('keeps the converter placeholder after editing the numeric answer', async () => { + const { emitted } = renderDocument(convertedInput); + const [answer] = await screen.findAllByRole('textbox', { name: tr.answerValuePlaceholder$() }); + await fireEvent.update(answer, '5'); + + const [xml] = emitted()['update:rawData'].at(-1); + expect(xml).toContain(' a b ', '\n'])(
+ 'reopens saved prompt code %j in the real editor',
+ async markup => {
+ const xml = VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', `Pick one.${markup}`);
+ const { container, emitted } = renderDocument(xml);
+ const code = await waitFor(() => {
+ const code = container.querySelector('.ProseMirror[contenteditable="true"] code');
+ expect(code).not.toBeNull();
+ return code;
+ });
+ if (markup.startsWith('')) expect(code.textContent).toBe('\n');
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ expect(emitted()['update:rawData']).toBeUndefined();
+ },
+);
+
+it('shows the unsupported message for a catalog reference without its catalog', () => {
+ renderDocument(CHOICE_ITEM_DOCUMENT_WITH_CATALOG_REFERENCE);
+
+ expect(screen.getByText(tr.unsupportedItemMessage$())).toBeVisible();
+});
+
+it('leaves raw data untouched when a card with a catalog reference opens and closes', async () => {
+ const { emitted, updateProps } = renderDocument(CHOICE_ITEM_DOCUMENT_WITH_CATALOG_REFERENCE, {
+ mode: 'view',
+ });
+ await updateProps({ mode: 'edit' });
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+
+ expect(emitted()['update:rawData']).toBeUndefined();
+});
+
+function expectMathPreserved(original, saved) {
+ const originalMath = parseXML(original).querySelector('math');
+ const savedMath = parseXML(saved).getElementsByTagNameNS(MATHML_NS, 'math')[0];
+ const contents = node => [
+ node.getAttribute('display'),
+ node.innerHTML.replaceAll(` xmlns="${node.namespaceURI}"`, ''),
+ ];
+ expect(contents(savedMath)).toEqual(contents(originalMath));
+}
+
+it('saves an empty paragraph pasted from the native clipboard into a choice prompt', async () => {
+ const original = VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', 'Heading
');
+ const { container, emitted } = renderDocument(original);
+ const editor = await waitFor(() => {
+ const editor = container.querySelector('.ProseMirror[contenteditable="true"]')?.editor;
+ expect(editor?.isInitialized).toBe(true);
+ return editor;
+ });
+ editor.commands.selectAll();
+ expect(editor.getHTML()).toBe('Heading
');
+ editor.commands.selectAll();
+ const { dom } = editor.view.serializeForClipboard(editor.state.selection.content());
+ expect(dom.lastElementChild.localName).toBe('p');
+ editor.view.pasteHTML(dom.innerHTML, new Event('paste'));
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+
+ const [saved] = emitted()['update:rawData'].at(-1);
+ expect(parseXML(saved).querySelector('qti-prompt > h2 + p').textContent).toBe('');
+});
+
+it('keeps a legacy MathML prompt across opening, closing, and editing', async () => {
+ const original = readConverterFixture('math_content_choice_interaction.xml');
+ const { emitted, updateProps, container } = renderDocument(original, {
+ mode: 'view',
+ language: 'en',
+ });
+ await updateProps({ mode: 'edit' });
+ await waitFor(() => expect(container.querySelector('.ProseMirror')?.editor).toBeDefined());
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+ expect(emitted()['update:rawData']).toBeUndefined();
+
+ await updateProps({ mode: 'edit' });
+ await waitFor(() => expect(container.querySelector('.ProseMirror')?.editor).toBeDefined());
+ const prompt = container.querySelector('.ProseMirror');
+ prompt.editor.chain().focus('end').insertContent(' Show your work.').run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+ const [xml] = emitted()['update:rawData'].at(-1);
+ expect(xml).toContain('Show your work.');
+ expectMathPreserved(original, xml);
+});
+
+it('edits a prompt with prefixed MathML', async () => {
+ const original = CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace(
+ /[\s\S]*?<\/qti-prompt>/,
+ 'Solve x + 1 .
',
+ );
+ const { emitted, container } = renderDocument(original);
+ const selector = '.ProseMirror[contenteditable="true"]';
+ await waitFor(() => expect(container.querySelector(selector)?.editor).toBeDefined());
+ expect(container.querySelector(selector)).toHaveTextContent(/x\+1/);
+ container
+ .querySelector(selector)
+ .editor.chain()
+ .focus('end')
+ .insertContent(' Show your work.')
+ .run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+
+ const [xml] = emitted()['update:rawData'].at(-1);
+ expect(xml).toBe(readFixture('editor/prefixed_mathml_edited.xml').trim());
+});
+
+it('keeps a block formula and the placeholder on an edit, but does not save an untouched Close', async () => {
+ const original = readConverterFixture('free_response_with_maths.xml');
+ const { emitted, container, updateProps } = renderDocument(original);
+ await waitFor(() => expect(container.querySelector('.ProseMirror')?.editor).toBeDefined());
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+ expect(emitted()['update:rawData']).toBeUndefined();
+
+ await updateProps({ mode: 'edit' });
+ await fireEvent.click(screen.getByRole('button', { name: tr.editQuestionLabel$() }));
+ await waitFor(() =>
+ expect(container.querySelector('.ProseMirror[contenteditable="true"]')?.editor).toBeDefined(),
+ );
+ container
+ .querySelector('.ProseMirror[contenteditable="true"]')
+ .editor.chain()
+ .focus('end')
+ .insertContent(' Show your work.')
+ .run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+
+ const [xml] = emitted()['update:rawData'].at(-1);
+ expect(xml).toContain('Show your work.');
+ expectMathPreserved(original, xml);
+ expect(xml).toContain('placeholder-text="Enter your answer here"');
+ expect(parseXML(xml).querySelector('math').parentNode.localName).toBe('p');
+});
+
+const gapMatch = CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace(
+ //,
+ `
+ Fill in the blank.
+ winter
+ It is .
+ `,
+)
+ .replace(
+ 'cardinality="single" base-type="identifier"',
+ 'cardinality="multiple" base-type="directedPair"',
+ )
+ .replace('choice-a ', 'choice-a gap-a ');
+
+it('keeps a locally declared MathML formula when editing a gap match passage', async () => {
+ const xml = gapMatch.replace(
+ 'It is ',
+ '
x It is ',
+ );
+ const user = userEvent.setup();
+ const { emitted } = renderDocument(xml);
+ const button = await screen.findByRole('button', { name: tr.editPassageLabel$() });
+ const region = button.parentElement;
+ await user.click(button);
+ const passage = await waitFor(() => {
+ const field = region.querySelector('.ProseMirror');
+ expect(field).toHaveAttribute('contenteditable', 'true');
+ return field.editor;
+ });
+ passage.chain().focus('end').insertContent(' Today.').run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ const [saved] = emitted()['update:rawData'].at(-1);
+ expect(saved).toContain('Today.');
+ const [formula] = parseXML(saved).getElementsByTagNameNS(MATHML_NS, 'math');
+ expect(formula.getElementsByTagNameNS(MATHML_NS, 'mi')[0].textContent).toBe('x');
+});
+
+it('opens a gap match read-only when a distractor has a line break', () => {
+ const { container, emitted } = renderDocument(
+ gapMatch.replace(
+ '',
+ 'First
second ',
+ ),
+ );
+ expect(screen.getByTestId('unsupportedMessage')).toHaveTextContent(tr.unsupportedItemMessage$());
+ expect(container.querySelector('[contenteditable="true"]')).not.toBeInTheDocument();
+ expect(emitted()['update:rawData']).toBeUndefined();
+});
+
+it('reopens an incomplete Gap Match draft generated by the editor', async () => {
+ const draft = gapMatch
+ .replace(/[\s\S]*?<\/qti-correct-response>/, '')
+ .replace(/]*>winter<\/qti-gap-text>/, '');
+ const first = renderDocument(draft);
+ const prompt = await waitFor(() => {
+ const field = first.container.querySelector('.ProseMirror[contenteditable="true"]');
+ expect(field?.editor).toBeDefined();
+ return field.editor;
+ });
+ prompt.chain().focus('end').insertContent(' Show your work.').run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ const [saved] = first.emitted()['update:rawData'].at(-1);
+ first.unmount();
+ expect(saved).toContain('data-studio-sentinel');
+ const { container } = renderDocument(saved);
+ await waitFor(() =>
+ expect(container.querySelector('.ProseMirror[contenteditable="true"]')).toBeVisible(),
+ );
+ expect(screen.getByTestId('incompleteIndicator')).toBeVisible();
+});
+
+it.each([
+ [
+ 'single selection',
+ CHOICE_ITEM_DOCUMENT_WITH_HINTS,
+ [tr.editAnswerOptionLabel$({ number: 1 }), tr.editHintLabel$({ number: 1 })],
+ ],
+ [
+ 'single selection with a trailing image',
+ CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace(
+ 'Pick one.',
+ 'Pick one.
',
+ ),
+ ],
+ ['multiple selection', readConverterFixture('multiple_selection.xml')],
+ ['true or false', readConverterFixture('true_false.xml')],
+ ['text entry', convertedInput.replace('base-type="float"', 'base-type="string"')],
+ [
+ 'free response',
+ readConverterFixture('free_response_with_maths.xml')
+ .replace(/[\s\S]*?<\/qti-correct-response>/, '')
+ .replace(/]*\/>/, ''),
+ ],
+ ['ordering', ORDERING_ITEM_DOCUMENT_NO_PROMPT],
+ [
+ 'associate',
+ VALID_ASSOCIATE_ITEM_DOCUMENT,
+ [tr.editPairItemLabel$({ number: 1, position: 1 }), tr.editDistractorLabel$({ number: 1 })],
+ ],
+ ['match', VALID_MATCH_ITEM_DOCUMENT, [tr.editRowLabel$({ number: 1 })]],
+ ['inline choice', INLINE_CHOICE_ITEM_DOCUMENT],
+ ['gap match', gapMatch],
+])(
+ 'saves a %s card only after editing, not on an untouched Close',
+ async (name, xml, nested = []) => {
+ const { emitted, container, updateProps } = renderDocument(xml, { mode: 'view' });
+ await updateProps({ mode: 'edit' });
+ if (name === 'free response') {
+ expect(container.querySelector('.select-value-text')).toHaveTextContent(
+ tr.freeResponseLabel$(),
+ );
+ }
+ await waitFor(() => expect(container.querySelector('.ProseMirror')?.editor).toBeDefined());
+ for (const field of container.querySelectorAll('.ProseMirror')) {
+ field.focus();
+ await fireEvent.blur(field);
+ }
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+
+ expect(emitted()['update:rawData']).toBeUndefined();
+
+ for (const name of nested) {
+ await updateProps({ mode: 'edit' });
+ if (name === tr.editHintLabel$({ number: 1 })) {
+ const hintsButton = screen.getByRole('button', { name: tr.hintsLabel$() });
+ if (hintsButton.getAttribute('aria-expanded') === 'false')
+ await fireEvent.click(hintsButton);
+ }
+ const editable = '.ProseMirror[contenteditable="true"]';
+ const promptFields = new Set(container.querySelectorAll(editable));
+ await fireEvent.click(screen.getByRole('button', { name }));
+ await waitFor(() => {
+ expect(
+ [...container.querySelectorAll(editable)].some(
+ field => field.editor && !promptFields.has(field),
+ ),
+ ).toBe(true);
+ });
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ await updateProps({ mode: 'view' });
+ expect(emitted()['update:rawData']).toBeUndefined();
+ }
+
+ await updateProps({ mode: 'edit' });
+ const prompt = await waitFor(() => {
+ const field = container.querySelector('.ProseMirror[contenteditable="true"]');
+ expect(field?.editor).toBeDefined();
+ return field.editor;
+ });
+ prompt.chain().focus('end').insertContent(' Show your work.').run();
+ await fireEvent.click(screen.getByRole('button', { name: tr.closeBtnLabel$() }));
+ expect(emitted()['update:rawData'].at(-1)[0]).toContain('Show your work.');
+ },
+);
+
+describe.each([
+ ['catalog reference', CHOICE_ITEM_DOCUMENT_WITH_CATALOG_REFERENCE],
+ [
+ 'audio prompt',
+ CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace('Pick one.', 'Pick one. '),
+ ],
+ [
+ 'video choice',
+ CHOICE_ITEM_DOCUMENT_WITH_HINTS.replace(
+ '>A',
+ '>A ',
+ ),
+ ],
+ [
+ 'printed variable',
+ INLINE_CHOICE_ITEM_DOCUMENT.replace(
+ 'identifier="RESPONSE_2" cardinality="single" base-type="identifier" />',
+ 'identifier="RESPONSE_2" cardinality="single" base-type="identifier">green
The sky is', '
| a | b |
test
', + 'test
', + ), + ], + [ + 'newline between inline formulas', + VALID_CHOICE_ITEM_DOCUMENT.replace( + 'Pick one.', + `\n
`, + ), + ], + [ + 'inline code in preformatted text', + VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', 'Output: answer.'),
+ ],
+ [
+ 'div with an inline image',
+ VALID_CHOICE_ITEM_DOCUMENT.replace(
+ 'Pick one.',
+ 'Pick one.

It is
`; + const answers = list(CorrectCriterion.ORDERED, [item(formula(2)), item(formula(3))]); + const result = carryAnswers( + answers, + format(CorrectCriterion.ACCEPTED, { contentLevel: ContentLevel.PLAIN }), + ); + expect(result.losses).toContain(ConversionLoss.ANSWERS_REMOVED); + }); + describe('from selected answers', () => { const answers = list(CorrectCriterion.SELECTED, [ item('
A
', true), diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/__tests__/convertInteraction.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/__tests__/convertInteraction.spec.js index 05a0b6458a..9bffeced5e 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/__tests__/convertInteraction.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/__tests__/convertInteraction.spec.js @@ -553,3 +553,41 @@ describe('convertInteraction', () => { ); }); }); + +it.each([QuestionType.TEXT_ENTRY, QuestionType.NUMERIC])( + 'reports a MathML-only distractor removed by conversion to %s', + toType => { + const fromType = QuestionType.SINGLE_SELECT; + const interaction = descriptorFor(fromType).buildXML( + { + prompt: 'Q
', + choices: [ + { id: 'a', content: '2
', correct: true }, + { id: 'b', content: '', correct: false }, + ], + }, + fromType, + ); + const result = convertInteraction({ interaction, fromType, toType }); + expect(result.losses).toContain(ConversionLoss.INCORRECT_ANSWERS_REMOVED); + expect(reopen(result.interaction, toType).answers.map(({ value }) => value)).toEqual(['2']); + }, +); + +it('omits stored MathML from a choice converted to a plain text answer', () => { + const fromType = QuestionType.SINGLE_SELECT; + const toType = QuestionType.TEXT_ENTRY; + const source = descriptorFor(fromType).buildXML( + { + prompt: 'Q
', + choices: [ + { id: 'a', content: 'A
', correct: true }, + { id: 'b', content: 'B
', correct: false }, + ], + }, + fromType, + ); + const { interaction, losses } = convertInteraction({ interaction: source, fromType, toType }); + expect(reopen(interaction, toType).answers.map(({ value }) => value)).toEqual(['A']); + expect(losses).toContain(ConversionLoss.FORMATTING_REMOVED); +}); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/answers.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/answers.js index 4ae2284d5e..956ce719b0 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/answers.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/conversion/answers.js @@ -35,8 +35,10 @@ const keep = items => items; const RULES = { [CorrectCriterion.SELECTED]: { [CorrectCriterion.SELECTED]: keep, - [CorrectCriterion.ACCEPTED]: (items, filled, losses) => { - if (filled.some(item => !item.correct)) losses.push(ConversionLoss.INCORRECT_ANSWERS_REMOVED); + [CorrectCriterion.ACCEPTED]: (items, filled, losses, hasSourceContent) => { + if (items.some(item => !item.correct && hasSourceContent(item))) { + losses.push(ConversionLoss.INCORRECT_ANSWERS_REMOVED); + } // Every correct choice had to be selected; any one accepted answer is enough. if (filled.filter(item => item.correct).length > 1) { losses.push(ConversionLoss.ANY_CORRECT_ANSWER_ACCEPTED); @@ -66,8 +68,8 @@ const RULES = { return markAll(false)(items); }, // No item is an accepted answer, and making them all accepted would invent correct answers. - [CorrectCriterion.ACCEPTED]: (items, filled, losses) => { - if (filled.length) losses.push(ConversionLoss.ANSWERS_REMOVED); + [CorrectCriterion.ACCEPTED]: (items, _filled, losses, hasSourceContent) => { + if (items.some(hasSourceContent)) losses.push(ConversionLoss.ANSWERS_REMOVED); return []; }, [CorrectCriterion.ORDERED]: keep, @@ -120,6 +122,7 @@ export function carryAnswers(answers, format) { answers.items, filled, losses, + item => hasContent(item.content, answers.contentLevel), ); if (format.single) { items = keepOneCorrect(items, counts, losses); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/InteractionDescriptor.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/InteractionDescriptor.js index e4432a01fc..08c2bf03a8 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/InteractionDescriptor.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/InteractionDescriptor.js @@ -29,6 +29,10 @@ const REQUIRED_METHODS = [ ]; export class InteractionDescriptor { + richTextFields({ prompt }) { + return [{ html: prompt }]; + } + /** * @param {object} options * @param {string} options.type - The interaction's XML tag name, e.g. 'qti-choice-interaction' diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/Descriptor.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/Descriptor.js index e23c7e90bd..9f0a565036 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/Descriptor.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/Descriptor.js @@ -1,5 +1,6 @@ import { QtiInteraction, QuestionType, BaseType, Cardinality } from '../../constants'; import { InteractionDescriptor } from '../InteractionDescriptor'; +import { getContentHTML, getPromptHTML, parseXML } from '../../serialization/xml'; import { parseAssociateInteraction, buildAssociateInteractionXML } from './parse'; import { exportAssociateContent, @@ -48,13 +49,14 @@ export class AssociateInteractionDescriptor extends InteractionDescriptor { }; } - /** - * ParseSolve for x
'; const parseXmlString = xml => parseXML(xml).documentElement; +it('removes only one slot when a repeated distractor is deleted', () => { + const state = parse(ASSOCIATE_XML.replace('match-max="1">Lysander', 'match-max="8">Lysander'), [ + ASSOCIATE_DECL_XML, + ]); + state.distractors.pop(); + const { bodyXml } = buildXML(state, QuestionType.ASSOCIATE, SCHEMA); + expect( + parseXmlString(bodyXml) + .querySelector('[identifier="choice_eee55555"]') + .getAttribute('match-max'), + ).toBe('7'); +}); + +it('raises an imported association limit that would exclude an edited key', () => { + const state = parse(ASSOCIATE_XML.replace('max-associations="2"', 'max-associations="3"'), [ + ASSOCIATE_DECL_XML, + ]); + state.pairs.push(...state.pairs); + const { bodyXml } = buildXML(state, QuestionType.ASSOCIATE, SCHEMA); + expect(parseXmlString(bodyXml).getAttribute('max-associations')).toBe('4'); +}); + describe('parse()', () => { describe('fallbacks', () => { it('seeds one pair of two blank choices with distinct ids when bodyXml is empty', () => { diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/parse.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/parse.js index c2f6370882..eaed39dcc7 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/parse.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/associate/parse.js @@ -1,7 +1,13 @@ import flatMap from 'lodash/flatMap'; import flatten from 'lodash/flatten'; import { QTIDeclaration } from '../../serialization/qti/QTIDeclaration'; -import { buildXmlNode, getContentHTML, getPromptHTML, parseXML } from '../../serialization/xml'; +import { + buildXmlNode, + extraAttributesOf, + getContentHTML, + getPromptHTML, + parseXML, +} from '../../serialization/xml'; import CorrectResponse from '../../serialization/qti/declarations/correctResponse'; import { generateRandomSlug } from '../../utils/generateRandomSlug'; import { RESPONSE_IDENTIFIER } from '../../constants'; @@ -109,6 +115,11 @@ export function parseAssociateInteraction(bodyXml, responseDeclarations) { return { responseIdentifier: root.getAttribute('response-identifier') || RESPONSE_IDENTIFIER, prompt: getPromptHTML(root), + extraAttributes: extraAttributesOf(root, [ + 'response-identifier', + 'shuffle', + 'max-associations', + ]), distractors, pairs, }; @@ -193,6 +204,7 @@ export function buildAssociateInteractionXML(state, _questionType, declarationSc const interactionEl = buildXmlNode({ tag: 'qti-associate-interaction', + extraAttributes: state.extraAttributes, attrs: { 'response-identifier': responseIdentifier, shuffle: 'true', diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/choice/Descriptor.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/choice/Descriptor.js index 151c7e7403..d1936cd4d1 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/choice/Descriptor.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/choice/Descriptor.js @@ -65,6 +65,14 @@ export class ChoiceInteractionDescriptor extends InteractionDescriptor { questionType === QuestionType.SINGLE_SELECT ? Cardinality.SINGLE : Cardinality.MULTIPLE, }; } + + richTextFields(state) { + return [ + ...super.richTextFields(state), + ...state.choices.map(({ content }) => ({ html: content })), + ]; + } + /** * Parse${gap('gap_m', ``)}
`, + mode: 'view', + showAnswers: true, + }); + const chip = await screen.findByRole('group', { + name: gapWithAnswer$({ answer: 'one divided by two', number: 1 }), + }); + const fallback = await screen.findByText('one divided by two'); + expect(chip).toContainElement(fallback); + expect(fallback).toHaveAttribute('dir', 'rtl'); + expect(chip).not.toHaveTextContent(errorEmptyChoiceContent$()); + }); + + it('announces the MathML answer when a TeX annotation contains only whitespace', async () => { + const math = + ''; + await renderPassage({ + value: `${gap('gap_m', ``)}
`, + mode: 'view', + showAnswers: true, + }); + expect( + await screen.findByRole('group', { + name: gapWithAnswer$({ answer: 'x2', number: 1 }), + }), + ).toHaveTextContent('x2'); + }); + + it('reveals presentation text when the MathML alternative is blank', async () => { + const math = + ''; + await renderPassage({ + value: `${gap('gap_m', ``)}
`, + mode: 'view', + showAnswers: true, + }); + const chip = await screen.findByRole('group', { + name: gapWithAnswer$({ answer: 'x', number: 1 }), + }); + expect(chip).toHaveTextContent('x'); + expect(chip).not.toHaveTextContent(errorEmptyChoiceContent$()); + }); + + it('treats whitespace-only TeX as an empty answer', async () => { + await renderPassage({ + value: `${gap('gap_m', '')}
`, + mode: 'view', + showAnswers: true, + }); + expect(await screen.findByRole('group', { name: gapEmpty$({ number: 1 }) })).toHaveTextContent( + errorEmptyChoiceContent$(), + ); + }); + it('renames a gap as its answer is typed', async () => { const { editor } = await renderPassage({ value: PASSAGE }); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/parse.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/parse.spec.js index c6dac9a1ef..a71b293a34 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/parse.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/parse.spec.js @@ -9,6 +9,12 @@ import { import { BaseType, Cardinality, QuestionType, SENTINEL_MARKER } from '../../../constants'; import { parseXML } from '../../../serialization/xml'; import { QTIDeclaration } from '../../../serialization/qti/QTIDeclaration'; +import { renderPassage } from './renderPassage'; +import { stubProseMirrorLayout } from 'shared/utils/testing'; + +jest.mock('shared/utils/browserInfo', () => ({ isTouchDevice: false })); + +stubProseMirrorLayout(); const SCHEMA = { baseType: BaseType.DIRECTED_PAIR, cardinality: Cardinality.MULTIPLE }; @@ -35,6 +41,17 @@ const BODY = interaction( ); const DECL = declaration('choice_winter gap_a', 'choice_spring gap_b'); +it('rebuilds the imported limit when the author adds two answered gaps', () => { + const state = parse( + interaction(PROMPT, gapText('choice_winter', 'winter'), 'a
' }); + const { schema } = editor; + const formula = schema.nodes.math.create({ mathml }); + const parse = jest.spyOn(DOMParser.prototype, 'parseFromString'); + try { + const gap = schema.nodes.gap.create({ identifier: 'gap_m' }, [formula]); + const updated = schema.nodes.gap.create(gap.attrs, [formula, schema.text(' plus x')]); + expect(gapAnswerText(gap)).toBe(expected); + expect(gapAnswerText(updated)).toBe(expected + ' plus x'); + expect(parse).toHaveBeenCalledTimes(1); + } finally { + parse.mockRestore(); + } + }, + ); + describe('after a failed MathLive load', () => { const RETRY_WAIT = 10000; let now; diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/validation.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/validation.spec.js index 1f0d5b752d..7757f30352 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/validation.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/interactions/gapMatch/__tests__/validation.spec.js @@ -74,6 +74,22 @@ describe('validateGapMatchInteraction()', () => { }); describe('DUPLICATE_DISTRACTOR_CONTENT', () => { + it('flags a MathML distractor that differs from the answer only in indentation', () => { + const carrier = body => + ``; + const answer = carrier('${gap('gap_math', answer)}
`; + const distractors = [ + distractor('choice_copy', carrier('\nSolve for x
'; @@ -70,15 +79,32 @@ const INTERACTIONS = [ }, ]; -const load = html => { +const load = (html, options) => { const { initializeEditor, editor } = useEditor(); - initializeEditor(html, 'edit'); + initializeEditor(html, 'edit', options); const loaded = editor.value.getHTML(); editor.value.destroy(); return loaded; }; -const buildItem = interaction => { +it.each([ + ['y', 'y'], + ['', 'x'], +])( + 'prefers explicit TeX when rejecting a pasted carrier with an ID (data-latex=%j)', + (latex, expected) => { + const markup = + ''; + const content = load( + transformPastedHTML(``), + ); + const saved = buildXmlNode({ tag: 'prompt', innerHTML: content }); + expect(saved.querySelector('math')).toBeNull(); + expect(saved.querySelector('span').getAttributeNS(null, 'data-latex')).toBe(expected); + }, +); + +const buildItem = (interaction, hintContent = CONTENT) => { const { bodyXml, responseDeclarations } = interaction.descriptor.buildXML( interaction.state, interaction.questionType, @@ -90,7 +116,7 @@ const buildItem = interaction => { language: 'en', bodyXml, responseDeclarations, - hints: [{ id: 'hint_1', content: CONTENT }], + hints: [{ id: 'hint_1', content: hintContent }], }), ); }; @@ -115,3 +141,120 @@ it('keeps the text after a formula in a hint once loaded into the editor', () => const item = buildItem(INTERACTIONS[0]); expect(load(item.hints[0].content)).toBe(CONTENT); }); + +it.each([ + '
Solve ${markup} for x
Solve for x
'); + } + saveMath(latex); + + const saved = buildXmlNode({ tag: 'prompt', innerHTML: mathEditor.getHTML() }); + if (keepsMathML) { + expect(saved.querySelector('math').isEqualNode(prompt.querySelector('math'))).toBe(true); + } else { + expect(saved.querySelector('math')).toBeNull(); + const placeholder = buildXmlNode({ tag: 'span', attrs: { 'data-latex': savedLatex } }); + expect(saved.querySelector('span').isEqualNode(placeholder)).toBe(true); + } + mathEditor.destroy(); + } finally { + jest.useRealTimers(); + } +}); + +it('keeps stored MathML in an inline-only editor', () => { + const body = parseXML(`${storedMath}
Nested hint
Nested hint
']); + }); + + it('ignores a hint catalog embedded in MathML', () => { + const doc = `Not a hint
Divide by two first
Divide by two first
Divide by two first
']); + }); it('reads every hint card, in document order', () => { expect(hintContents(CHOICE_ITEM_DOCUMENT_WITH_HINTS)).toEqual([ 'test
', @@ -25,6 +51,19 @@ describe('parseHints', () => { expect(hintContents(VALID_CHOICE_ITEM_DOCUMENT)).toEqual([]); }); + it('does not read a foreign catalog as item hints', () => { + const item = VALID_CHOICE_ITEM_DOCUMENT.replace( + 'no
Pick one.
') + .replace('Label'),
+ ],
+ [
+ 'a secondary response declaration',
+ xml =>
+ xml
+ .replace(
+ ' Text b a b c Read the passage. fileInput.value.click();
const onFileSelect = event => handleFileChange(event.target.files[0]);
- const onInsert = () => emit('insert', { src: previewSrc.value, alt: altText.value });
+ const onInsert = () =>
+ emit('insert', { src: previewSrc.value, alt: altText.value }, previewImage.value);
const onSave = () =>
- emit('update', {
- src: previewSrc.value,
- alt: altText.value,
- permanentSrc: previewSrc.value,
- });
+ emit(
+ 'update',
+ { src: previewSrc.value, alt: altText.value, permanentSrc: previewSrc.value },
+ previewImage.value,
+ );
useFocusTrap(modalRoot);
@@ -286,6 +289,7 @@
modalRoot,
modalState,
fileInput,
+ previewImage,
previewSrc,
altText,
fileName,
diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue
index 5fb8e13f45..5ff983ad0f 100644
--- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue
+++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/FormulasMenu.vue
@@ -125,6 +125,7 @@
useFocusTrap(rootEl);
const currentLatex = ref('');
+ let initialExpandedLatex;
// Load MathLive dynamically
const loadMathLive = async () => {
@@ -158,6 +159,7 @@
if (mathfieldEl.value) {
mathfieldEl.value.mathVirtualKeyboardPolicy = 'manual';
mathfieldEl.value.value = props.initialLatex;
+ initialExpandedLatex = mathfieldEl.value.getValue?.('latex-expanded');
mathfieldEl.value.focus();
mathfieldEl.value.addEventListener('input', updateLatex);
currentLatex.value = props.initialLatex;
@@ -223,7 +225,11 @@
const onSave = () => {
if (mathfieldEl.value && mathLiveLoaded.value) {
const newLatex = mathfieldEl.value.getValue('latex');
- emit('save', newLatex);
+ emit(
+ 'save',
+ newLatex,
+ initialExpandedLatex === mathfieldEl.value.getValue('latex-expanded'),
+ );
}
};
diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue
index d05933c9c1..a5a59e32bb 100644
--- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue
+++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/components/math/LazyMathNodeView.vue
@@ -4,13 +4,22 @@
as="span"
class="math-node-wrapper"
>
-