From 30641a4bdf4225a5437a07935f774a39782c37a5 Mon Sep 17 00:00:00 2001 From: rtibblesbot Date: Sat, 28 Nov 2026 18:48:26 -0800 Subject: [PATCH 1/4] Re-parse a closed QTI question card when its item changes - An open card keeps the author's version; closing it reloads from the current item unless the close reported a newer edit. - Inside a question card, TipTap reports only a changed document, so focusing the prompt and closing reports nothing. Co-Authored-By: Claude Opus 5.5 --- .../frontend/shared/views/QTIEditor/README.md | 2 +- .../__tests__/QTIItemEditor.spec.js | 167 ++++++++++++++++ .../components/QTIItemEditor/index.vue | 189 ++++++++++++------ .../views/QTIEditor/composables/useQtiItem.js | 43 ++-- .../TipTapEditor/TipTapEditor.vue | 8 + 5 files changed, 336 insertions(+), 73 deletions(-) diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md index 06f8615e01..b9b65a064e 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/README.md @@ -4,7 +4,7 @@ Edits an exercise's assessment items stored as [QTI 3](https://www.imsglobal.org ### Flow 1. `index.vue` lists the items; each is a `components/QTIItemEditor`. -2. `composables/useQtiItem.js` parses `raw_data` with `serialization/parseItem.js` into interaction blocks (`bodyXml` + `responseDeclarations`), hints and item metadata. +2. `composables/useQtiItem.js` parses `raw_data` with `serialization/parseItem.js` into interaction blocks (`bodyXml` + `responseDeclarations`), hints and item metadata. The card reloads the parsed item in view mode when its stored XML or type changes. 3. `components/InteractionSection` resolves each block's descriptor and question type with `composables/useInteractionDescriptor.js`. 4. The interaction's `Editor.vue` (`interactions/index.js`) edits a plain state object through `composables/useInteraction.js`: `descriptor.parse` → state → `descriptor.buildXML` → `descriptor.validate`. 5. `useQtiItem` rebuilds the full item with `serialization/assembleItem.js`; `QTIItemEditor` emits `update:rawData`. `validateItem.js` `isEditableItem` shows read-only any item holding content outside the body that this rebuild doesn't write or regenerate. diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/__tests__/QTIItemEditor.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/__tests__/QTIItemEditor.spec.js index 156a0d1c18..45ace25ee2 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/__tests__/QTIItemEditor.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/__tests__/QTIItemEditor.spec.js @@ -586,6 +586,122 @@ describe('QTIItemEditor', () => { }, }); + const refreshedItem = { + ...defaultProps.item, + assessment_id: 'item-id', + raw_data: NUMERIC_ITEM_DOCUMENT, + }; + + it('reloads a changed prompt without reporting an edit', async () => { + const { emitted, updateProps } = renderWithContent('view'); + await updateProps({ + item: { + ...refreshedItem, + raw_data: VALID_CHOICE_ITEM_DOCUMENT.replace('Pick one.', 'Pick a letter.'), + }, + }); + expect(screen.getByText('Pick a letter.')).toBeInTheDocument(); + expect(emitted()['update:rawData']).toBeUndefined(); + }); + + it('keeps the rendered prompt mounted when only the item title changes', async () => { + const { updateProps } = renderWithContent('view'); + const prompt = screen.getByText('Pick one.'); + await updateProps({ + item: { + ...refreshedItem, + raw_data: VALID_CHOICE_ITEM_DOCUMENT.replace(/ title="[^"]*"/, ' title="New title"'), + }, + }); + expect(screen.getByText('Pick one.')).toBe(prompt); + }); + + it('opens a converted legacy question with its prompt', async () => { + const { emitted, updateProps } = renderComponent({ + item: { ...refreshedItem, type: 'single_selection', raw_data: '' }, + }); + await updateProps({ item: { ...refreshedItem, raw_data: VALID_CHOICE_ITEM_DOCUMENT } }); + await fireEvent.click(screen.getByText('Pick one.')); + expect(emitted().open).toHaveLength(1); + }); + + it('clears an incomplete indicator when the replacement is valid', async () => { + const item = { ...refreshedItem, raw_data: CHOICE_ITEM_DOCUMENT_NO_CORRECT_ANSWER }; + const { updateProps } = renderComponent({ item }); + expect(await screen.findByTestId('incompleteIndicator')).toBeInTheDocument(); + await updateProps({ item: { ...item, raw_data: VALID_CHOICE_ITEM_DOCUMENT } }); + expect(screen.queryByTestId('incompleteIndicator')).not.toBeInTheDocument(); + }); + + it('shows and hides hints as the stored item gains and loses them', async () => { + const item = { ...refreshedItem, raw_data: VALID_CHOICE_ITEM_DOCUMENT }; + const { updateProps } = renderComponent({ item, showAnswers: true }); + await updateProps({ item: { ...item, raw_data: CHOICE_ITEM_DOCUMENT_WITH_HINTS } }); + const hintsButton = screen.getByRole('button', { name: hintsLabel$() }); + hintsButton.focus(); + await updateProps({ item }); + expect(screen.getByRole('heading', { level: 3 }).closest('.question-card')).toHaveFocus(); + expect(screen.queryByText(hintsLabel$())).not.toBeInTheDocument(); + }); + + it('clears the question type when an adaptive item disables editing', async () => { + const { updateProps } = renderWithContent('view'); + await updateProps({ + item: { + ...refreshedItem, + raw_data: VALID_CHOICE_ITEM_DOCUMENT.replace('adaptive="false"', 'adaptive="true"'), + }, + }); + expect(screen.getByText(unsupportedItemMessage$())).toBeInTheDocument(); + expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent(unknownTypeLabel$()); + }); + + it('clears the prompt and type when replacement XML is unreadable', async () => { + const { updateProps } = renderWithContent('view'); + await updateProps({ item: { ...refreshedItem, raw_data: '' } }); + expect(screen.queryByText('Pick one.')).not.toBeInTheDocument(); + expect(screen.getByText(unsupportedItemMessage$())).toBeInTheDocument(); + expect( + screen.getByText( + questionNumberAndTypeLabel$({ + number: 1, + total: 5, + type: unknownTypeLabel$(), + }), + ), + ).toBeInTheDocument(); + }); + + it('shows an editable placeholder when stored XML is cleared', async () => { + const { emitted, updateProps } = renderWithContent('view'); + await updateProps({ item: { ...refreshedItem, raw_data: '' } }); + expect(screen.queryByText('Pick one.')).not.toBeInTheDocument(); + await fireEvent.click(screen.getByText(questionContentPlaceholder$())); + expect(emitted().open).toHaveLength(1); + expect(emitted()['update:rawData']).toBeUndefined(); + }); + + it.each(['view', 'edit'])('shows refreshed content when viewed from %s mode', async mode => { + const { emitted, updateProps } = renderWithContent(mode); + await updateProps({ item: refreshedItem }); + + if (mode === 'edit') { + expect(screen.getByRole('button', { name: /add choice/i })).toBeInTheDocument(); + await updateProps({ mode: 'view' }); + } + + expect( + screen.getByText( + questionNumberAndTypeLabel$({ + number: 1, + total: 5, + type: qtiEditorStrings.numericLabel$(), + }), + ), + ).toBeInTheDocument(); + expect(emitted()['update:rawData']).toBeUndefined(); + }); + it('a card that is only being viewed reports nothing', async () => { // A closed card re-assembles its XML too; reporting that would rewrite every // question in the list just for being on screen. @@ -684,6 +800,57 @@ describe('QTIItemEditor', () => { expect(screen.getByText(hintsLabel$())).toBeInTheDocument(); }); + it('keeps mounted hints when only the item title changes', async () => { + const item = { ...defaultProps.item, raw_data: CHOICE_ITEM_DOCUMENT_WITH_HINTS }; + const { updateProps } = renderComponent({ item, mode: 'view', showAnswers: true }); + await fireEvent.click(screen.getByRole('button', { name: hintsLabel$() })); + const hint = screen.getByText('

test2 2

'); + const raw_data = item.raw_data.replace(/ title="[^"]*"/, ' title="Updated"'); + await updateProps({ item: { ...item, raw_data } }); + expect(screen.getByText('

test2 2

')).toBe(hint); + }); + + it.each([false, true])( + 'keeps hint editing after deletions with an intermediate echo of %s', + async intermediateEcho => { + const item = { ...defaultProps.item, raw_data: CHOICE_ITEM_DOCUMENT_WITH_HINTS }; + const { emitted, updateProps } = renderComponent({ item, mode: 'edit', showAnswers: true }); + await fireEvent.click(screen.getByRole('button', { name: hintsLabel$() })); + for (const button of screen.getAllByRole('button', { name: 'Delete hint' })) { + await fireEvent.click(button); + } + const [raw_data] = emitted()['update:rawData'].at(-1); + const [earlierXml] = emitted()['update:rawData'][0]; + await updateProps({ + item: { ...item, raw_data: intermediateEcho ? earlierXml : raw_data }, + }); + expect(screen.getByRole('button', { name: hintsLabel$() })).toBeInTheDocument(); + await updateProps({ mode: 'view' }); + await updateProps({ item: { ...item, raw_data } }); + expect(screen.queryByRole('button', { name: hintsLabel$() })).not.toBeInTheDocument(); + + await updateProps({ mode: 'edit' }); + await fireEvent.click(screen.getByRole('button', { name: hintsLabel$() })); + expect(screen.getByTestId('addHintBtn')).toBeInTheDocument(); + }, + ); + + it('shows only saved hints in view mode and keeps the empty draft on reopen', async () => { + const item = { ...defaultProps.item, raw_data: CHOICE_ITEM_DOCUMENT_WITH_HINTS }; + const { emitted, updateProps } = renderComponent({ item, mode: 'edit', showAnswers: true }); + await fireEvent.click(screen.getByRole('button', { name: hintsLabel$() })); + const savedCount = screen.getAllByTestId('hint').length; + await fireEvent.click(screen.getByTestId('addHintBtn')); + const [raw_data] = emitted()['update:rawData'].at(-1); + await updateProps({ item: { ...item, raw_data } }); + + await updateProps({ mode: 'view' }); + expect(screen.getAllByTestId('hint')).toHaveLength(savedCount); + + await updateProps({ mode: 'edit' }); + expect(screen.getAllByTestId('hint')).toHaveLength(savedCount + 1); + }); + it('reports the item XML when a hint changes', async () => { const { emitted } = renderComponent({ item: { ...defaultProps.item, raw_data: CHOICE_ITEM_DOCUMENT_WITH_HINTS }, diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/index.vue b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/index.vue index b92e5d5f42..f12a8e08ab 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/index.vue +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/QTIItemEditor/index.vue @@ -8,10 +8,17 @@ -->

@@ -64,6 +72,7 @@ - import { computed, nextTick, onMounted, ref, watch } from 'vue'; + import { computed, nextTick, onMounted, provide, ref, shallowRef, watch } from 'vue'; + import { v4 as uuidv4 } from 'uuid'; import { qtiEditorStrings } from '../../qtiEditorStrings'; import { AssessmentItemTypes, QuestionType } from '../../constants'; import useQtiItem from '../../composables/useQtiItem'; import { isEditableItem, validateItemShape, validateQtiItem } from '../../validateItem'; import InteractionSection from '../InteractionSection/index.vue'; + import { hintHasContent } from '../../serialization/hints'; import HintsSection from '../HintsSection/index.vue'; export default { @@ -127,6 +138,8 @@ components: { InteractionSection, HintsSection }, setup(props, { emit, listeners }) { + const headingId = `question-heading-${uuidv4()}`; + provide('tipTapRequireDocumentChange', true); const { questionNumberLabel$, questionNumberAndTypeLabel$, @@ -150,26 +163,92 @@ // Parse the item XML. rawData is a computed inside useQtiItem that // re-assembles the full XML whenever identifier/title/language or the // editor refs change — no need to duplicate assembleItemXml here. - const { interactions, itemBodyXml, hints, parseError, rawData } = useQtiItem( - props.item.raw_data, - { bodyXml: currentBodyXml, responseDeclarations: currentResponseDeclarations }, - ); + const { + interactions, + itemBodyXml, + hints, + parseError, + rawData, + load: parse, + } = useQtiItem(null, { + bodyXml: currentBodyXml, + responseDeclarations: currentResponseDeclarations, + }); - const isQti = computed(() => props.item.type === AssessmentItemTypes.QTI); + const loaded = shallowRef({}); + const revision = ref(0); + /** + * Tracks the current question type (a QuestionType value). + * Initialized to null — populated via the update:questionType event + * emitted by InteractionSection once the XML is parsed. + */ + const currentQuestionType = ref(null); + /** Errors the interaction editor reports about the state it holds. */ + const errors = ref([]); + /** + * Whether this question offers hints at all, which is settled by what the item arrived + * with: only a question that already has them shows the section (product decision). + * + * Read from the loaded item rather than from the live list, so removing the last + * hint does not take the section away while the author is still working in it. + */ + const hadHints = ref(false); + /** + * Whether the change the watcher below is about to report came from an edit in this + * card. Recorded as the change happens rather than read from `mode` when the watcher + * flushes: closing the card sets the parent's active item to none, and that re-render + * lands first, so a change made just before the close would look like it came from a + * card nobody was editing. + */ + let editedHere = false; + const lastReportedXml = ref(null); + let lastLocalSave; + + function load() { + const { raw_data, type } = props.item; + const previousType = loaded.value.type; + loaded.value = { raw_data, type }; + parse(raw_data); + hadHints.value = + lastLocalSave && lastLocalSave.xml === raw_data + ? lastLocalSave.hadHints + : hints.value.length > 0; + /* + * Seed the editor refs from the parsed item's first block, which for an inline + * passage holds every declaration. + */ + const [first] = interactions.value; + const bodyXml = first?.bodyXml ?? ''; + const declarations = first?.responseDeclarations ?? []; + if ( + previousType !== type || + bodyXml !== currentBodyXml.value || + JSON.stringify(declarations) !== JSON.stringify(currentResponseDeclarations.value) + ) { + currentBodyXml.value = bodyXml; + currentResponseDeclarations.value = declarations; + currentQuestionType.value = null; + errors.value = []; + revision.value += 1; + } + if (isUnsupported.value) currentQuestionType.value = null; + editedHere = false; + lastReportedXml.value = null; + } + const isQti = computed(() => loaded.value.type === AssessmentItemTypes.QTI); /** * Whether this editor can edit the item's XML faithfully: it is readable, and it is * either blank or holds exactly one interaction this editor knows, in the body shape its * builder writes, and nothing outside the body that an edit would drop. */ - const sourceXml = props.item.raw_data; const isEditableQti = computed( () => !parseError.value && - (!sourceXml || + (!loaded.value.raw_data || isEditableItem( { interactions: interactions.value, itemBodyXml: itemBodyXml.value }, - sourceXml, + loaded.value.raw_data, )), ); @@ -178,15 +257,7 @@ * faithfully are shown as read-only cards. */ const isUnsupported = computed(() => !isQti.value || !isEditableQti.value); - - /* - * Seed the editor refs from the parsed item's first block, which for an inline - * passage holds every declaration. - */ - if (interactions.value.length > 0) { - currentBodyXml.value = interactions.value[0].bodyXml; - currentResponseDeclarations.value = interactions.value[0].responseDeclarations; - } + load(); const currentInteraction = computed(() => ({ bodyXml: currentBodyXml.value, @@ -200,13 +271,6 @@ }), ); - /** - * Tracks the current question type (a QuestionType value). - * Initialized to null — populated via the update:questionType event - * emitted by InteractionSection once the XML is parsed on mount. - */ - const currentQuestionType = ref(null); - const interactionTypeLabel = computed(() => { const type = currentQuestionType.value; if (!type) return unknownTypeLabel$(); @@ -233,50 +297,61 @@ }), ); - /** - * Whether the change the watcher below is about to report came from an edit in this - * card. Recorded as the change happens rather than read from `mode` when the watcher - * flushes: closing the card sets the parent's active item to none, and that re-render - * lands first, so a change made just before the close would look like it came from a - * card nobody was editing. - */ - let editedHere = false; - let lastReported = null; - - // Watch the inputs, not rawData: watching the computed would assemble it for every card - // on screen, logging assembly warnings for items nobody is saving. - // Emit only when the assembled XML actually changes after initial mount. - watch([currentBodyXml, currentResponseDeclarations, hints], () => { - if (!editedHere) return; + function reportEdit() { + if (!editedHere) return false; editedHere = false; const newVal = rawData.value; - if (newVal === lastReported) return; - lastReported = newVal; + if (newVal === lastReportedXml.value) return false; + lastReportedXml.value = newVal; + lastLocalSave = { xml: newVal, hadHints: hadHints.value }; if (process.env.NODE_ENV === 'development') { // debug to help devs understand what the editor is sending to the parent // eslint-disable-next-line no-console console.debug('[QTIItemEditor] assembled XML:\n', newVal); } emit('update:rawData', newVal); + return true; + } + watch([() => props.item.raw_data, () => props.item.type, () => props.mode], () => { + if (props.mode === 'edit') return; + const reported = reportEdit(); + if (reported) return; + const held = lastReportedXml.value ?? loaded.value.raw_data; + if (props.item.raw_data === held && props.item.type === loaded.value.type) return; + const element = card.value?.$el; + const focused = document.activeElement; + load(); + if (element?.contains(focused)) { + nextTick(() => { + if ( + (!focused.isConnected || focused.disabled) && + (document.activeElement === document.body || document.activeElement === focused) + ) { + element.focus(); + } + }); + } }); + // Watch the inputs, not rawData: watching the computed would assemble it for every card + // on screen, logging assembly warnings for items nobody is saving. + // Emit only when the assembled XML actually changes after initial mount. + watch([currentBodyXml, currentResponseDeclarations, hints], reportEdit); + function onUpdateInteraction({ bodyXml, responseDeclarations }) { editedHere = props.mode === 'edit'; currentBodyXml.value = bodyXml; currentResponseDeclarations.value = responseDeclarations; } - /** - * Whether this question offers hints at all, which is settled by what the item arrived - * with: only a question that already has them shows the section (product decision). - * - * Read once from the parsed item rather than from the live list, so removing the last - * hint does not take the section away while the author is still working in it. - */ - const hasHints = hints.value.length > 0; + const savedHints = computed(() => + lastReportedXml.value === null ? hints.value : hints.value.filter(hintHasContent), + ); - const showHints = computed( - () => hasHints && (props.mode === 'edit' ? !isUnsupported.value : props.showAnswers), + const showHints = computed(() => + props.mode === 'edit' + ? hadHints.value && !isUnsupported.value + : props.showAnswers && savedHints.value.length > 0, ); function onUpdateHints(newHints) { @@ -329,9 +404,6 @@ { flush: 'post' }, ); - /** Errors the interaction editor reports about the state it holds. */ - const errors = ref([]); - function onUpdateErrors(newErrors) { errors.value = newErrors; } @@ -376,7 +448,9 @@ }); return { + headingId, card, + revision, interactionSection, currentQuestionType, interactions, @@ -394,6 +468,7 @@ onUpdateInteraction, onUpdateErrors, hints, + savedHints, showHints, onUpdateHints, }; diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQtiItem.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQtiItem.js index be848c42f9..209087c151 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQtiItem.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQtiItem.js @@ -3,14 +3,14 @@ import { parseItem } from '../serialization/parseItem'; import { assembleItemXml } from '../serialization/assembleItem'; /** - * Composable that parses a raw QTI XML string once and exposes the + * Composable that parses a raw QTI XML string and exposes the * structured item model as reactive refs. * * Optionally accepts reactive `bodyXml` and `responseDeclarations` refs * (owned by the editor) and exposes a `rawData` computed that re-assembles - * the full item XML whenever any of the five values change. + * the full item XML whenever any of its inputs change. * - * @param {string | null | undefined} rawData - Raw QTI XML string from item.raw_data + * @param {string | null | undefined} rawXml - Raw QTI XML string from item.raw_data * @param {{ bodyXml?: import('vue').Ref, * responseDeclarations?: import('vue').Ref }} [editorRefs] * @returns {{ @@ -22,6 +22,7 @@ import { assembleItemXml } from '../serialization/assembleItem'; * hints: import('vue').Ref>, * parseError: import('vue').Ref, * rawData: import('vue').ComputedRef, + * load: (xml: string|null|undefined) => void, * }} */ export default function useQtiItem(rawXml, { bodyXml, responseDeclarations } = {}) { @@ -38,20 +39,31 @@ export default function useQtiItem(rawXml, { bodyXml, responseDeclarations } = { const hints = ref([]); const parseError = ref(null); - if (rawXml) { - try { - const model = parseItem(rawXml); - identifier.value = model.identifier; - title.value = model.title; - label.value = model.label; - language.value = model.language; - itemBodyXml.value = model.itemBodyXml; - interactions.value = model.interactions; - hints.value = model.hints; - } catch (e) { - parseError.value = e.message; + function load(xml) { + let model = {}; + parseError.value = null; + if (xml) { + try { + model = parseItem(xml); + } catch (e) { + parseError.value = e.message; + } + } + identifier.value = model.identifier ?? ''; + title.value = model.title ?? ''; + label.value = model.label ?? ''; + language.value = model.language ?? ''; + itemBodyXml.value = model.itemBodyXml ?? ''; + interactions.value = model.interactions ?? []; + const parsedHints = model.hints ?? []; + if ( + parsedHints.length !== hints.value.length || + parsedHints.some((hint, index) => hint.content !== hints.value[index].content) + ) { + hints.value = parsedHints; } } + load(rawXml); /** * Re-assembles the full QTI item XML whenever identifier, title, language, @@ -79,5 +91,6 @@ export default function useQtiItem(rawXml, { bodyXml, responseDeclarations } = { hints, parseError, rawData, + load, }; } diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue index babb27ae2f..75ce258c75 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue @@ -89,6 +89,7 @@ provide, watch, computed, + inject, ref, toRef, nextTick, @@ -186,6 +187,8 @@ // detect when an incoming prop.value is just our own emitted value echoed // back, so we can skip unnecessary re-rendering of the editor content. let lastEmittedMarkdown = null; + let syncedDocument; + const requireDocumentChange = inject('tipTapRequireDocumentChange', false); /** * Focus the content once it is in the page. TipTap puts it there only when the editor is @@ -247,12 +250,14 @@ extensions: props.extensions, inlineOnly, }); + syncedDocument = editor.value.state.doc; return; } if (getContent() !== newValue) { editor.value.commands.setContent(processedContent, false); } + syncedDocument = editor.value.state.doc; }, { immediate: true }, ); @@ -263,6 +268,9 @@ return; } + const document = editor.value.state.doc; + if (requireDocumentChange && document.eq(syncedDocument)) return; + syncedDocument = document; const content = getContent(); if (content !== props.value) { lastEmittedMarkdown = content; From 596020d9df309332abc834a940bf09b11342d3d2 Mon Sep 17 00:00:00 2001 From: rtibblesbot Date: Sat, 28 Nov 2026 18:48:41 -0800 Subject: [PATCH 2/4] Report the edited question, move and placement from QTIEditor - `update` carries the edited question's id, a move, or an add's neighbours, so the parent writes only what the author changed. - Close the open question when it leaves the list. - Keep focus in the list when a question is removed or replaced. Co-Authored-By: Claude Opus 5.5 --- .../QTIEditor/__tests__/QTIEditor.spec.js | 130 +++++++++++++++++- .../__tests__/QTIEditorTyping.spec.js | 128 +++++++++++++++++ .../components/CollapsibleToolbar/index.vue | 6 +- .../composables/useQuestionListFocus.js | 50 +++++++ .../frontend/shared/views/QTIEditor/index.vue | 83 +++++++++-- .../views/QTIEditor/useQTIEditorActions.js | 4 +- 6 files changed, 381 insertions(+), 20 deletions(-) create mode 100644 contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditorTyping.spec.js create mode 100644 contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQuestionListFocus.js 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..ec7b4db83d 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditor.spec.js @@ -1,5 +1,5 @@ import Vue, { nextTick } from 'vue'; -import { render, screen, fireEvent } from '@testing-library/vue'; +import { render, screen, fireEvent, within } from '@testing-library/vue'; import VueRouter from 'vue-router'; import QTIEditor from '../index.vue'; import { qtiEditorStrings } from '../qtiEditorStrings'; @@ -18,6 +18,7 @@ jest.mock('kolibri-design-system/lib/composables/useKResponsiveWindow', () => { const { toolbarLabelEdit$, closeBtnLabel$, + newQuestionBtnLabel$, unsupportedItemMessage$, deleteUnsupportedItemMessage$, } = qtiEditorStrings; @@ -45,6 +46,25 @@ afterAll(() => { }); describe('QTIEditor', () => { + it('identifies the edited question in an update', async () => { + const { emitted } = renderComponent([QTI_ITEM]); + await fireEvent.click(editButton()); + await fireEvent.click(screen.getByRole('button', { name: /add choice/i })); + + expect(emitted().update).toEqual([ + [[{ ...QTI_ITEM, raw_data: expect.any(String) }], QTI_ITEM.assessment_id], + ]); + }); + + it('emits only the remaining list on delete', async () => { + const { emitted } = renderComponent([QTI_ITEM]); + await nextTick(); + await fireEvent.click(screen.getByRole('button', { name: /options/i })); + await fireEvent.click(await screen.findByText(qtiEditorStrings.toolbarLabelDelete$())); + + expect(emitted().update).toEqual([[[]]]); + }); + describe('opening a question', () => { it('opens a question from its Edit action', async () => { renderComponent([QTI_ITEM]); @@ -52,6 +72,114 @@ describe('QTIEditor', () => { expect(screen.getByRole('button', { name: closeBtnLabel$() })).toBeInTheDocument(); }); + it('keeps a removed question closed when it returns', async () => { + const otherItem = { ...QTI_ITEM, assessment_id: 'other-item' }; + const { updateProps } = renderComponent([QTI_ITEM, otherItem]); + const closeButton = () => screen.queryByRole('button', { name: closeBtnLabel$() }); + + await fireEvent.click(screen.getAllByRole('button', { name: toolbarLabelEdit$() })[0]); + await updateProps({ assessments: [otherItem] }); + expect(closeButton()).not.toBeInTheDocument(); + + await updateProps({ assessments: [QTI_ITEM, otherItem] }); + expect(closeButton()).not.toBeInTheDocument(); + + await updateProps({ assessments: [otherItem] }); + await fireEvent.click(editButton()); + expect(closeButton()).toBeInTheDocument(); + }); + + it('closes the active question when the assessment list becomes null', async () => { + const { updateProps } = renderComponent([QTI_ITEM]); + await fireEvent.click(editButton()); + screen.getByRole('button', { name: closeBtnLabel$() }).focus(); + await updateProps({ assessments: null }); + expect(screen.getByRole('button', { name: newQuestionBtnLabel$() })).toHaveFocus(); + await updateProps({ assessments: [QTI_ITEM] }); + + expect(editButton()).toBeEnabled(); + }); + + it('moves focus away from Edit when a replacement disables it', async () => { + const { updateProps } = renderComponent([QTI_ITEM]); + const edit = editButton(); + edit.focus(); + + await updateProps({ assessments: [{ ...QTI_ITEM, raw_data: '' }] }); + + expect(edit).toBeDisabled(); + expect(screen.getByTestId('item')).toHaveFocus(); + }); + + it('announces that the last question was removed', async () => { + const { updateProps } = renderComponent([QTI_ITEM]); + const status = screen.getByRole('status'); + expect(status).toBeEmptyDOMElement(); + + await updateProps({ assessments: [] }); + + expect(screen.getByRole('status')).toBe(status); + expect(status).toHaveTextContent(qtiEditorStrings.noQuestionsPlaceholder$()); + }); + + it('recovers focus from Show answers and adds a question to a null list', async () => { + const { updateProps, emitted } = renderComponent([QTI_ITEM]); + screen.getByRole('checkbox', { name: qtiEditorStrings.showAnswers$() }).focus(); + await updateProps({ assessments: null }); + const addButton = screen.getByRole('button', { name: newQuestionBtnLabel$() }); + expect(addButton).toHaveFocus(); + await fireEvent.click(addButton); + expect(emitted().update[0][0]).toHaveLength(1); + }); + + it('focuses Options when Close reveals an unreadable question', async () => { + const { updateProps } = renderComponent([QTI_ITEM]); + await fireEvent.click(editButton()); + await updateProps({ assessments: [{ ...QTI_ITEM, raw_data: '' }] }); + const close = screen.getByRole('button', { name: closeBtnLabel$() }); + close.focus(); + await fireEvent.click(close); + expect(screen.getByRole('button', { name: /options/i })).toHaveFocus(); + }); + + it('recovers focus only in the list owning the removed question', async () => { + const first = renderComponent([QTI_ITEM]); + const second = renderComponent([QTI_ITEM]); + within(second.container).getByRole('button', { name: toolbarLabelEdit$() }).focus(); + + await Promise.all([ + first.updateProps({ assessments: [] }), + second.updateProps({ assessments: [] }), + ]); + + expect( + within(second.container).getByRole('button', { name: newQuestionBtnLabel$() }), + ).toHaveFocus(); + }); + + it('recovers focus from the removed question’s Options menu', async () => { + const { updateProps } = renderComponent([QTI_ITEM]); + await nextTick(); + await fireEvent.click(screen.getByRole('button', { name: /options/i })); + const option = await screen.findByText(qtiEditorStrings.toolbarLabelDelete$()); + option.closest('[tabindex]').focus(); + expect(document.activeElement).toContainElement(option); + await updateProps({ assessments: [] }); + expect(screen.getByRole('button', { name: newQuestionBtnLabel$() })).toHaveFocus(); + }); + + it('opens a new question after an intervening list update', async () => { + const otherItem = { ...QTI_ITEM, assessment_id: 'other-item' }; + const { updateProps, emitted } = renderComponent([QTI_ITEM, otherItem]); + await fireEvent.click(screen.getByRole('button', { name: newQuestionBtnLabel$() })); + const [[updatedItems]] = emitted().update; + + await updateProps({ assessments: [otherItem, QTI_ITEM] }); + await updateProps({ assessments: updatedItems }); + + expect(screen.getByRole('button', { name: closeBtnLabel$() })).toBeInTheDocument(); + }); + it('opens a question when its card is clicked', async () => { renderComponent([QTI_ITEM]); await fireEvent.click(screen.getByTestId('item')); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditorTyping.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditorTyping.spec.js new file mode 100644 index 0000000000..900116f66d --- /dev/null +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/__tests__/QTIEditorTyping.spec.js @@ -0,0 +1,128 @@ +import { render, screen, waitFor, fireEvent, within } from '@testing-library/vue'; +import userEvent from '@testing-library/user-event'; +import VueRouter from 'vue-router'; +import QTIEditor from '../index.vue'; +import { qtiEditorStrings } from '../qtiEditorStrings'; +import { AssessmentItemTypes } from '../constants'; +import { VALID_CHOICE_ITEM_DOCUMENT } from '../utils/testingFixtures'; +import { stubProseMirrorLayout } from 'shared/utils/testing'; + +jest.mock('shared/utils/browserInfo', () => ({ isTouchDevice: false })); + +stubProseMirrorLayout(); + +jest.setTimeout(30000); + +it('saves the last prompt edit when the author clicks Close', async () => { + const user = userEvent.setup(); + const item = { + assessment_id: 'question', + type: AssessmentItemTypes.QTI, + raw_data: VALID_CHOICE_ITEM_DOCUMENT, + }; + const { container, emitted, updateProps } = render(QTIEditor, { + props: { assessments: [item] }, + routes: new VueRouter(), + }); + await user.click(screen.getByRole('button', { name: qtiEditorStrings.toolbarLabelEdit$() })); + const prompt = await waitFor(() => { + const editor = Array.from(container.querySelectorAll('.ProseMirror')).find(element => + element.textContent.includes('Pick one.'), + ); + expect(editor).toBeDefined(); + return editor; + }); + await updateProps({ assessments: [{ ...item, type: 'single_selection', raw_data: '' }] }); + prompt.focus(); + await user.keyboard('Updated prompt'); + expect(emitted().update).toBeUndefined(); + await user.click(screen.getByRole('button', { name: qtiEditorStrings.closeBtnLabel$() })); + + const [[updated]] = emitted().update.slice(-1); + expect(updated[0].raw_data).toContain('Updated prompt'); + expect(updated[0].type).toBe(AssessmentItemTypes.QTI); +}); + +it('shows a remote prompt when the author closes without editing', async () => { + const user = userEvent.setup(); + const item = { + assessment_id: 'question', + type: AssessmentItemTypes.QTI, + raw_data: VALID_CHOICE_ITEM_DOCUMENT, + }; + const { emitted, updateProps } = render(QTIEditor, { + props: { assessments: [item] }, + routes: new VueRouter(), + }); + await user.click(screen.getByRole('button', { name: qtiEditorStrings.toolbarLabelEdit$() })); + const prompt = await screen.findByText('Pick one.'); + prompt.closest('.ProseMirror').focus(); + await updateProps({ + assessments: [{ ...item, raw_data: item.raw_data.replace('Pick one.', 'Remote prompt') }], + }); + await user.click(screen.getByRole('button', { name: qtiEditorStrings.closeBtnLabel$() })); + + const remotePrompt = await screen.findByText('Remote prompt'); + expect(remotePrompt.closest('[data-assessment-id="question"]')).toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: qtiEditorStrings.closeBtnLabel$() }), + ).not.toBeInTheDocument(); + expect(emitted().update).toBeUndefined(); +}); + +it('recovers focus when the question owning the image upload error is removed', async () => { + const overlay = document.getElementById('k-overlay') ?? document.createElement('div'); + const createdOverlay = !overlay.isConnected; + if (createdOverlay) { + overlay.id = 'k-overlay'; + document.body.appendChild(overlay); + } + const assessments = ['a', 'b'].map(assessment_id => ({ + assessment_id, + type: AssessmentItemTypes.QTI, + raw_data: VALID_CHOICE_ITEM_DOCUMENT, + })); + const user = userEvent.setup(); + const other = render(QTIEditor, { + props: { + assessments: assessments.map(item => ({ + ...item, + assessment_id: 'other-' + item.assessment_id, + })), + }, + routes: new VueRouter(), + }); + const { container, updateProps, unmount } = render(QTIEditor, { + props: { assessments }, + routes: new VueRouter(), + }); + try { + other.container.querySelector('[data-assessment-id="other-a"]').focus(); + await user.click( + within(container).getAllByRole('button', { name: qtiEditorStrings.toolbarLabelEdit$() })[0], + ); + await waitFor(() => expect(container.querySelector('.ProseMirror')).not.toBeNull()); + const insert = within(container).getAllByRole('button', { name: /insert image/i })[0]; + insert.focus(); + await user.click(insert); + const input = await waitFor(() => { + const field = container.querySelector('.image-upload-modal input[type=file]'); + expect(field).not.toBeNull(); + return field; + }); + const file = new File(['x'], 'note.txt', { type: 'text/plain' }); + await fireEvent.change(input, { target: { files: [file] } }); + await waitFor(() => expect(overlay).toContainElement(document.activeElement)); + + await Promise.all([ + other.updateProps({ assessments: [{ ...assessments[1], assessment_id: 'other-b' }] }), + updateProps({ assessments: [assessments[1]] }), + ]); + + await waitFor(() => expect(container.querySelector('[data-assessment-id="b"]')).toHaveFocus()); + } finally { + other.unmount(); + unmount(); + if (createdOverlay) overlay.remove(); + } +}); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/CollapsibleToolbar/index.vue b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/CollapsibleToolbar/index.vue index 31959bbfb0..c215d705e1 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/CollapsibleToolbar/index.vue +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/CollapsibleToolbar/index.vue @@ -83,9 +83,11 @@ /** Moves focus to an action's button, or to the options menu holding it if collapsed. */ function focusAction(id) { - if (!props.actions.some(action => action.id === id)) return; - const button = actionButtons[id] ?? optionsButton.value; + const action = props.actions.find(action => action.id === id); + if (!action) return false; + const button = (!action.disabled && actionButtons[id]) || optionsButton.value; button?.$el.focus(); + return document.activeElement === button?.$el; } return { diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQuestionListFocus.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQuestionListFocus.js new file mode 100644 index 0000000000..231dc92a57 --- /dev/null +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/composables/useQuestionListFocus.js @@ -0,0 +1,50 @@ +import { nextTick, onBeforeUnmount, onMounted, watch } from 'vue'; + +let lastFocusedCard; + +export default function useQuestionListFocus(items, container, fallback) { + function rememberCard(event) { + if (!event.target.closest('#k-overlay')) { + lastFocusedCard = event.target.closest('[data-assessment-id]'); + } + } + onMounted(() => document.addEventListener('focusin', rememberCard)); + onBeforeUnmount(() => { + document.removeEventListener('focusin', rememberCard); + if (container()?.contains(lastFocusedCard)) lastFocusedCard = null; + }); + + watch( + () => items().map(item => item.assessment_id), + (ids, previousIds) => { + const focused = document.activeElement; + const list = container(); + // Tippy 4 exposes the trigger as reference on its popper instance. + const trigger = focused?.closest('.tippy-popper')?._tippy?.reference; + const inOverlay = Boolean(focused?.closest('#k-overlay')); + const owner = trigger ?? (inOverlay ? lastFocusedCard : focused); + if (!owner || !list?.contains(owner)) return; + const card = owner.closest('[data-assessment-id]'); + const id = card?.dataset.assessmentId; + nextTick(() => { + if (document.activeElement !== document.body && document.activeElement !== focused) return; + if (inOverlay && focused.isConnected) return; + if (ids.includes(id)) { + if (!focused.isConnected || focused.disabled) { + card.focus(); + } else if (document.activeElement === document.body) { + focused.focus(); + } + return; + } + if (!card) { + if (!focused.isConnected) fallback()?.focus(); + return; + } + const cards = list.querySelectorAll('[data-assessment-id]'); + const next = cards[previousIds.indexOf(id)]; + (next ?? cards[cards.length - 1] ?? fallback())?.focus(); + }); + }, + ); +} diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/index.vue b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/index.vue index e2b44b2b0b..a379e8c9f9 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/index.vue +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/index.vue @@ -1,6 +1,9 @@