diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/__tests__/ClickableRegion.spec.js b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/__tests__/ClickableRegion.spec.js index 0106aaaf65..37bac43b60 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/__tests__/ClickableRegion.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/__tests__/ClickableRegion.spec.js @@ -99,4 +99,42 @@ describe('ClickableRegion', () => { expect(screen.getByRole('button', { name: 'Test label' })).toHaveFocus(); }); + + describe('pressed while suppressed, then unsuppressed before the click', () => { + const renderPressed = async () => { + const { emitted, container, updateProps } = render(ClickableRegion, { + props: { ariaLabel: 'Test label', suppressed: true }, + routes: new VueRouter(), + }); + await fireEvent.pointerDown(container.firstChild); + await updateProps({ suppressed: false }); + return { emitted, container }; + }; + + it('ignores the pointer click', async () => { + const { emitted, container } = await renderPressed(); + + await fireEvent.click(container.firstChild, { detail: 1 }); + + expect(emitted().click).toBeUndefined(); + }); + + it('emits a keyboard click', async () => { + const { emitted } = await renderPressed(); + + await fireEvent.click(screen.getByRole('button'), { detail: 0 }); + + expect(emitted().click).toHaveLength(1); + }); + + it('emits the next pointer click', async () => { + const { emitted, container } = await renderPressed(); + await fireEvent.click(container.firstChild, { detail: 1 }); + + await fireEvent.pointerDown(container.firstChild); + await fireEvent.click(container.firstChild, { detail: 1 }); + + expect(emitted().click).toHaveLength(1); + }); + }); }); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/index.vue b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/index.vue index 92439412fa..e4f1e27cbf 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/index.vue +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/ClickableRegion/index.vue @@ -7,6 +7,7 @@
+
+ `, + props: { + addMode: { type: String, default: 'button' }, + initialChips: { type: Array, default: () => CHIPS }, + }, + data() { + return { chips: [...this.initialChips], labels: LABELS, shown: true }; + }, +}; + +const list = () => screen.getByRole('list', { name: distractorsLabel$() }); +const chipTexts = () => + within(list()) + .queryAllByRole('listitem') + .map(item => item.textContent.trim()); +const button = name => screen.getByRole('button', { name }); +const editButton = number => button(editDistractorLabel$({ number })); +const openEditor = () => screen.queryByRole('textbox', { name: TipTapEditorLabel$() }); + +async function writeIn(user, opener) { + await user.click(opener); + await waitFor(() => expect(openEditor()).toContainElement(document.activeElement)); + await user.keyboard('!'); +} + +// Separate from EditableChipList.spec.js, which mocks TipTapEditor: these run the real one. +describe('EditableChipList with the real TipTapEditor', () => { + stubProseMirrorLayout(); + + let consoleError; + + beforeEach(() => { + consoleError = jest.spyOn(console, 'error'); + }); + + afterEach(() => { + try { + expect(consoleError).not.toHaveBeenCalled(); + } finally { + consoleError.mockRestore(); + } + }); + + const renderHost = (addMode, initialChips) => { + const user = userEvent.setup(); + render(Host, { props: { addMode, initialChips }, routes: new VueRouter() }); + return user; + }; + + describe.each(['button', 'region'])('in %s mode', addMode => { + it.each([ + ['a click on', user => user.click(button(saveChipBtn$()))], + [ + 'Enter on', + user => { + button(saveChipBtn$()).focus(); + return user.keyboard('{Enter}'); + }, + ], + ])('closes an open chip on %s its save button, keeping the edit', async (_, save) => { + const user = renderHost(addMode); + await writeIn(user, editButton(2)); + + await save(user); + + await waitFor(() => expect(editButton(2)).toHaveFocus()); + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Prospero!']); + }); + + it('closes and removes an open chip on a click on its delete button', async () => { + const user = renderHost(addMode); + await writeIn(user, editButton(2)); + + await user.click(button(deleteDistractorBtn$({ number: 2 }))); + + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio']); + }); + + it('keeps an open chip open when its image dialog closes, and saves it after', async () => { + const user = renderHost(addMode); + await writeIn(user, editButton(2)); + + await user.click(within(openEditor()).getByRole('button', { name: insertImage$() })); + // A browser runs Vue's render between a native click's listeners, unmounting the + // dialog before the click bubbles out of it; jsdom renders only after dispatch. + const closeButton = await screen.findByRole('button', { name: closeModal$() }); + closeButton.addEventListener('click', () => closeButton.remove()); + await user.click(closeButton); + + expect(openEditor()).not.toBeNull(); + await user.click(button(saveChipBtn$())); + + await waitFor(() => expect(editButton(2)).toHaveFocus()); + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Prospero!']); + }); + + describe.each([ + ['the gap beside the closed chips', list], + [ + "the space beside the open chip's save button", + () => document.querySelector('li.is-editing .save-row'), + ], + ])('on a click on %s', (_, target) => { + it('closes an open chip, keeping the edit, without opening another', async () => { + const user = renderHost(addMode); + await writeIn(user, editButton(2)); + + await user.click(target()); + + await waitFor(() => expect(openEditor()).toBeNull()); + expect(chipTexts()).toEqual(['Antonio', 'Prospero!']); + }); + + it('only dismisses an open toolbar menu, keeping the chip open', async () => { + const user = renderHost(addMode); + await writeIn(user, editButton(2)); + const formatButton = within(openEditor()).getByRole('button', { + name: textFormatOptions$(), + }); + await user.click(formatButton); + await waitFor(() => expect(formatButton).toHaveAttribute('aria-expanded', 'true')); + + await user.click(target()); + + await waitFor(() => expect(formatButton).toHaveAttribute('aria-expanded', 'false')); + expect(openEditor()).not.toBeNull(); + }); + }); + + describe('with a blank chip open', () => { + const BLANK_SECOND = [ + { id: 'choice_a', content: '

Antonio

' }, + { id: 'choice_b', content: '' }, + { id: 'choice_c', content: '

Caliban

' }, + { id: 'choice_d', content: '

Miranda

' }, + ]; + + const openBlank = async () => { + const user = renderHost(addMode, BLANK_SECOND); + await user.click(editButton(2)); + await waitFor(() => expect(openEditor()).toContainElement(document.activeElement)); + return user; + }; + + it('removes only it on a click on its delete button', async () => { + const user = await openBlank(); + + await user.click(button(deleteDistractorBtn$({ number: 2 }))); + + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Caliban', 'Miranda']); + }); + + it('removes a later chip whose delete button is clicked', async () => { + const user = await openBlank(); + + await user.click(button(deleteDistractorBtn$({ number: 3 }))); + + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Miranda']); + }); + + it('opens the chip that is clicked', async () => { + const user = await openBlank(); + + await user.click(editButton(3)); + + await waitFor(() => expect(openEditor()).toHaveTextContent('Caliban')); + expect(chipTexts()).toHaveLength(3); + }); + }); + + it('throws a written draft away on a click on its discard button', async () => { + const user = renderHost(addMode); + await writeIn(user, button(addDistractorBtn$())); + + await user.click(button(deleteDistractorBtn$({ number: 3 }))); + + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Prospero']); + }); + }); + + it('adds a region-mode draft on save without opening another', async () => { + const user = renderHost('region'); + await writeIn(user, button(addDistractorBtn$())); + + await user.click(button(saveChipBtn$())); + + await waitFor(() => expect(button(addDistractorBtn$())).toHaveFocus()); + expect(openEditor()).toBeNull(); + expect(chipTexts()).toEqual(['Antonio', 'Prospero', '!']); + }); + + describe('in region mode, rendering between listeners as a browser does', () => { + beforeEach(() => { + Vue.config.async = false; + }); + + afterEach(() => { + Vue.config.async = true; + }); + + it.each([ + ['a chip', () => editButton(2), () => document.querySelector('.pool-content')], + ['a draft', () => button(addDistractorBtn$()), () => document.querySelector('.pool-content')], + ['a draft', () => button(addDistractorBtn$()), list], + ['a chip', () => editButton(2), () => document.querySelector('li.is-editing .save-row')], + ])('closes %s on a click in the box without opening a draft', async (_, opener, target) => { + const user = renderHost('region'); + await writeIn(user, opener()); + + await user.click(target()); + + await waitFor(() => expect(openEditor()).toBeNull()); + }); + + it.each([ + ['an edited chip', () => editButton(2), ['Antonio', 'Prospero!']], + ['a written draft', () => button(addDistractorBtn$()), ['Antonio', 'Prospero', '!']], + ])('keeps %s on a click that unmounts the list', async (_, opener, expected) => { + const user = renderHost('region'); + await writeIn(user, opener()); + + await user.click(button('Close question')); + + const saved = within(screen.getByRole('list', { name: 'Saved' })).getAllByRole('listitem'); + expect(saved.map(item => item.textContent)).toEqual(expected); + }); + }); + + it('adds a draft on a save click that moves no focus', async () => { + const user = renderHost('region'); + await writeIn(user, button(addDistractorBtn$())); + + await fireEvent.click(button(saveChipBtn$())); + + expect(openEditor()).toBeNull(); + await waitFor(() => expect(chipTexts()).toEqual(['Antonio', 'Prospero', '!'])); + }); +}); diff --git a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/EditableChipList/index.vue b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/EditableChipList/index.vue index 2fd945a4d1..97325f4a46 100644 --- a/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/EditableChipList/index.vue +++ b/contentcuration/contentcuration/frontend/shared/views/QTIEditor/components/EditableChipList/index.vue @@ -102,6 +102,7 @@ -->
@@ -181,6 +182,7 @@ import { generateRandomSlug } from '../../utils/generateRandomSlug'; import { qtiEditorStrings } from '../../qtiEditorStrings'; import TipTapEditor from 'shared/views/TipTapEditor/TipTapEditor/TipTapEditor'; + import { provideEditorBoundary } from 'shared/views/TipTapEditor/TipTapEditor/composables/useEditorBoundary'; import EditorImageProcessor from 'shared/views/TipTapEditor/TipTapEditor/services/imageService'; import { hasRichTextContent } from 'shared/views/TipTapEditor/TipTapEditor/utils/comparisonKey'; @@ -202,6 +204,24 @@ const addButton = ref(null); const deleteButtons = ref([]); const chipRegions = ref([]); + const draftRow = ref(null); + + function isOnClosedChip(target) { + return chipRegions.value.some( + ({ $el, $props }) => !$props.suppressed && $el.contains(target), + ); + } + + function isOnOpenEditorButton(target) { + const button = target.closest('button'); + const openEditorRows = [ + ...chipRegions.value.filter(({ $props }) => $props.suppressed).map(({ $el }) => $el), + draftRow.value, + ]; + return Boolean(button) && openEditorRows.some(row => row?.contains(button)); + } + + provideEditorBoundary(target => isOnClosedChip(target) || isOnOpenEditorButton(target)); // The chip whose editor is open — `index` null for a new one — holding its // content as last written, since the chip prop lags a render behind. @@ -390,6 +410,7 @@ addButton, deleteButtons, chipRegions, + draftRow, open, draftKey, isDraftOpen, diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/TipTapEditor.vue index 60f5cd386b..1116f20719 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 @@ import EditorContentWrapper from './components/EditorContentWrapper.vue'; import { useEditor } from './composables/useEditor'; import { useClickOutside } from './composables/useClickOutside'; + import { injectEditorBoundary } from './composables/useEditorBoundary'; import ImageUploadModal from './components/image/ImageUploadModal.vue'; import { useImageHandling } from './composables/useImageHandling'; import '../assets/styles/code-theme-dark.css'; @@ -258,6 +259,7 @@ container: editorContainer, isFocused, isEditing: () => props.mode === 'edit', + isInsideBoundary: injectEditorBoundary(), syncContent: emitContentUpdate, close: minimize, }); diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useClickOutside.js b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useClickOutside.js index d76f48afd9..57413d6d32 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useClickOutside.js +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useClickOutside.js @@ -15,10 +15,19 @@ const hasOpenPopup = container => * @param {Ref} options.container the editor's root element * @param {Ref} options.isFocused whether the editor content has focus * @param {Function} options.isEditing whether the editor is open for editing + * @param {Function} [options.isInsideBoundary] (target: Element) => whether a click on `target` + * outside the editor only syncs its content, leaving it open * @param {Function} options.syncContent emits the content if it changed * @param {Function} options.close syncs the content and closes the editor */ -export function useClickOutside({ container, isFocused, isEditing, syncContent, close }) { +export function useClickOutside({ + container, + isFocused, + isEditing, + isInsideBoundary = null, + syncContent, + close, +}) { // A blur caused by a press syncs once the press ends, so the re-render it may cause // cannot move the pressed target away before the click. let isPressing = false; @@ -54,12 +63,16 @@ export function useClickOutside({ container, isFocused, isEditing, syncContent, const handleClick = event => { const root = container.value; const isOutside = isEditing() && root && !root.contains(event.target) && !hasOpenPopup(root); - if (isOutside) { + if (!isOutside) { + flushHeldSync(); + return; + } + hasHeldSync = false; + if (isInsideBoundary?.(event.target)) { + syncContent(); + } else { // `close` syncs the content itself. - hasHeldSync = false; close(); - } else { - flushHeldSync(); } }; diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useEditorBoundary.js b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useEditorBoundary.js new file mode 100644 index 0000000000..75ad64873b --- /dev/null +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/TipTapEditor/composables/useEditorBoundary.js @@ -0,0 +1,15 @@ +import { inject, provide } from 'vue'; + +const EditorBoundarySymbol = Symbol('tipTapEditorBoundary'); + +/** + * @param {Function} isInside (target: Element) => whether a click on `target`, outside a + * descendant editor, leaves that editor open + */ +export function provideEditorBoundary(isInside) { + provide(EditorBoundarySymbol, isInside); +} + +export function injectEditorBoundary() { + return inject(EditorBoundarySymbol, null); +} diff --git a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/useClickOutside.spec.js b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/useClickOutside.spec.js index d44e200ba9..960b851987 100644 --- a/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/useClickOutside.spec.js +++ b/contentcuration/contentcuration/frontend/shared/views/TipTapEditor/__tests__/useClickOutside.spec.js @@ -9,7 +9,7 @@ import { useClickOutside } from '../TipTapEditor/composables/useClickOutside'; * tests move by hand, and the menu trigger marks itself open the way KDropdownMenu does. The * dialog trigger stands in for content, such as a node view, whose popup renders outside. */ -function renderHarness({ editing = true } = {}) { +function renderHarness({ editing = true, isInsideBoundary } = {}) { const isFocused = ref(false); const syncContent = jest.fn(); const close = jest.fn(); @@ -21,6 +21,7 @@ function renderHarness({ editing = true } = {}) { container, isFocused, isEditing: () => props.editing, + isInsideBoundary, syncContent, close, }); @@ -42,6 +43,7 @@ function renderHarness({ editing = true } = {}) {

+
`, }), @@ -80,6 +82,33 @@ describe('useClickOutside', () => { expect(close).toHaveBeenCalledTimes(1); }); + describe('with a boundary', () => { + const isInsideBoundary = target => target.dataset.testid === 'save'; + + it('syncs and stays open on a click inside the boundary', async () => { + const user = userEvent.setup(); + const { close, syncContent } = renderHarness({ isInsideBoundary }); + let syncsAtHandler; + button('Save').addEventListener('click', () => { + syncsAtHandler = syncContent.mock.calls.length; + }); + + await user.click(button('Save')); + + expect(syncsAtHandler).toBe(1); + expect(close).not.toHaveBeenCalled(); + }); + + it('closes on a click outside the boundary', async () => { + const user = userEvent.setup(); + const { close } = renderHarness({ isInsideBoundary }); + + await user.click(button('Outside')); + + expect(close).toHaveBeenCalledTimes(1); + }); + }); + it('stays open on a click inside', async () => { const user = userEvent.setup(); const { close } = renderHarness(); diff --git a/docs/rich_text_editor.md b/docs/rich_text_editor.md index 92027d31fd..c2d53f8568 100644 --- a/docs/rich_text_editor.md +++ b/docs/rich_text_editor.md @@ -103,6 +103,13 @@ The context is re-evaluated on every transaction; no listener is needed. The edi - The editor knows a popup is open from its trigger: any element inside the editor with `aria-haspopup` and `aria-expanded="true"`. KDS's `KDropdownMenu` sets both on its trigger. - A node view whose button opens a panel rendered beside the editor sets both on that button for as long as the panel is open, and the editor stays open while the panel is used. The inline choice chip does this for its options panel. +### Controls beside the editor +- A click outside the editor closes it before the click's own handlers run. +- An ancestor that renders controls acting on the editor, such as Save, calls `provideEditorBoundary(isInside)` from `composables/useEditorBoundary.js`; `isInside(target)` says whether a click on `target` is on one. +- `isInside` is true only on the controls, not the space around them: a click there would sync and leave the editor open, with nothing to close it. +- A click outside the editor for which `isInside` is true syncs the content and leaves the editor open: the control's own handler reads the content and closes the editor if it should. +- One call covers every editor below that ancestor. + ### Node views reading consumer state - ProseMirror mounts node views outside the Vue render tree: no slots, no `$emit` listener. - tiptap mounts them with `parent: editor.contentComponent`, so `inject` reaches whatever an ancestor of `TipTapEditor` provides.