diff --git a/apps/app/e2e/shell/editor-citations.spec.ts b/apps/app/e2e/shell/editor-citations.spec.ts index d0764e15..76ca2bd0 100644 --- a/apps/app/e2e/shell/editor-citations.spec.ts +++ b/apps/app/e2e/shell/editor-citations.spec.ts @@ -19,6 +19,8 @@ import { openFinding, openTab, place, + referenceDialog, + referenceSettled, saveDraft, seedDraft, serverDocument, @@ -251,9 +253,13 @@ test.describe('citations sheet, editing', () => { await expect( root.getByRole('button', { name: /Source B/ }), ).toHaveAttribute('aria-expanded', 'true') + // Filtered by the finding the sheet belonged to: its three citations (R2F-6). await expect( root.locator('button[aria-controls][id$="-header"]'), - ).toHaveCount(4) + ).toHaveCount(3) + await expect(root.getByTestId('editor-references-filter')).toContainText( + 'Constat A', + ) // The move is an entry of its own: Back returns to the finding with its sheet on top. await page.goBack() await expect(place(page, 'citations')).toBeVisible() @@ -264,26 +270,42 @@ test.describe('citations sheet, editing', () => { await expect(place(page, 'references')).toBeVisible() }) - test('Escape in a field of a tile neither closes the sheet nor commits; ✕ then commits', async ({ + test('« Modifier » opens the reference dialog over the sheet; « Enregistrer » closes it only, one undo', async ({ page, }) => { test.setTimeout(150_000) const { seed } = await open(page) await openCitations(page, dict, 'Constat A') await heads(page).first().click() - await panel(page) - .getByRole('button', { name: dict['editor.references.edit'] }) - .click() - const field = panel(page).getByLabel(dict['editor.reference.citation']) + const modify = panel(page).getByRole('button', { + name: dict['editor.references.edit'], + }) + await modify.click() + await expect(referenceDialog(page)).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(3) + const field = referenceDialog(page).getByLabel( + dict['editor.reference.citation'], + ) await field.fill('Référence A, révisée') + // Escape asks (the draft is kept), it neither closes the sheet nor writes. await field.press('Escape') - await expect(panel(page)).toBeVisible() - await expect(field).toHaveValue('Référence A, révisée') - // A user close applies a valid draft first (P22''), then the sheet exits. - await panel(page) - .getByRole('button', { name: dict['editor.references.close'] }) + await expect( + referenceDialog(page).getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(3) + await referenceDialog(page) + .getByRole('button', { name: dict['editor.findings.keep_typing'] }) .click() - await expect(panel(page)).toHaveCount(0) + await expect(field).toHaveValue('Référence A, révisée') + await referenceDialog(page) + .getByRole('button', { name: dict['editor.findings.save'] }) + .click() + await expect(referenceDialog(page)).toHaveCount(0) + await referenceSettled(page) + await expect(panel(page)).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) + await expect(modify).toBeFocused() + await closeCitations(page, dict) await closeFinding(page, dict) await expect(undo(page)).toBeEnabled() await saveDraft(page, dict, seed.revision + 1) @@ -293,7 +315,7 @@ test.describe('citations sheet, editing', () => { expect(saved.references[0].citation).toBe('Référence A, révisée') }) - test('a refused draft cancels every move that unmounts the sheet: ✕, scrim, Back, « Tout afficher »', async ({ + test('a dirty reference dialog keeps its draft on ✕ and on Back; « Abandonner » leaves the sheet open', async ({ page, }) => { test.setTimeout(150_000) @@ -303,28 +325,38 @@ test.describe('citations sheet, editing', () => { await panel(page) .getByRole('button', { name: dict['editor.references.edit'] }) .click() - const field = panel(page).getByLabel(dict['editor.reference.citation']) - await field.fill('') - await panel(page) - .getByRole('button', { name: dict['editor.references.close'] }) + const form = referenceDialog(page) + const field = form.getByLabel(dict['editor.reference.citation']) + await field.fill('Brouillon') + await form + .getByRole('button', { name: dict['common.close'], exact: true }) .click() - await expect(panel(page)).toBeVisible() - await expect(field).toBeFocused() - await expect(panel(page).getByRole('alert')).toBeVisible() - await page - .getByTestId('references-scrim') - .click({ position: { x: 4, y: 40 } }) - await expect(panel(page)).toBeVisible() - await link(page).click() - await expect(panel(page)).toBeVisible() - await expect(page.getByRole('tab', { selected: true })).toHaveText( - new RegExp(`^${dict['editor.tab.findings']}`), - ) - // Back: the page stays, the view is pushed again, the refusal shows. + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await form + .getByRole('button', { name: dict['editor.findings.keep_typing'] }) + .click() + // Back: the dialog stays, the view is pushed again, the confirmation shows. await page.goBack() + await expect(form).toBeVisible() + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await expect(field).toHaveValue('Brouillon') + await form + .getByRole('button', { name: dict['editor.findings.keep_typing'] }) + .click() + await form + .getByRole('button', { name: dict['editor.findings.cancel'] }) + .click() + await form + .getByRole('button', { name: dict['editor.findings.discard'] }) + .click() + await expect(referenceDialog(page)).toHaveCount(0) await expect(panel(page)).toBeVisible() await expect(findingDialog(page)).toBeVisible() - await expect(panel(page).getByRole('alert')).toBeVisible() + await expect(undo(page)).toHaveAttribute('aria-disabled', 'true') }) test('the exiting sheet is inert, and a second close finds nothing to close', async ({ diff --git a/apps/app/e2e/shell/editor-reference-journey.spec.ts b/apps/app/e2e/shell/editor-reference-journey.spec.ts new file mode 100644 index 00000000..d8915c5a --- /dev/null +++ b/apps/app/e2e/shell/editor-reference-journey.spec.ts @@ -0,0 +1,348 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + editorActor, + expectNoDialog, + findingDialog, + historyButton, + libraryRoot, + openEditor, + openFinding, + openTab, + place, + referenceDialog, + referenceSettled, + seedDraft, + showCitations, + standardShape, +} from '../support/editor' + +// R2 UX finish, task 3 (R2F-5, R2F-6): the reference dialog, the reading tiles, the +// references filtered by a finding, and the owner's journey through the browser history: +// finding A, its sheet, « Tout afficher », the filtered tab, a reference edited, Back, +// Forward, « Revenir au constat », then every Back down to the first entry. The top +// layer, the focus and the history rules are the browser's, so they are proved here. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const panel = (page: Page) => page.getByTestId('editor-citations-panel') +const chip = (page: Page) => + libraryRoot(page).getByTestId('editor-references-filter') +const headers = (page: Page) => + libraryRoot(page).locator('button[aria-controls][id$="-header"]') +const undo = (page: Page) => historyButton(page, dict, 'undo') +const dialogs = (page: Page) => page.locator('dialog[open]') + +/** « Constat A » cites A and B; « Source libre » is cited by nobody. */ +function shape(document: Record) { + standardShape(document) + const reference = (id: string, citation: string) => ({ + id, + type: 'book', + citation, + url: null, + doi: null, + }) + document.references = [ + reference('ref-a', 'Référence A'), + reference('ref-b', 'Référence B'), + reference('ref-c', 'Source libre'), + ] + const zone = (document.finding_zones as { categories: unknown[] }[])[0] + const family = zone.categories[0] as { + children: { reference_ids: string[] }[] + } + family.children[0].reference_ids = ['ref-a', 'ref-b'] +} + +async function open(page: Page) { + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape }) + await openEditor(page, dict, actor, seed.sheetId) + return seed +} + +/** The id of the history entry on top: it changes with every push, never with a replace. */ +const entryId = (page: Page) => + page.evaluate(() => history.state?.usr?.editorEntry?.id as string) + +/** Waits until the entry on top satisfies `view`: the adapter writes a moment after a move. */ +async function entryHolds(page: Page, test: string) { + const view = 'history.state?.usr?.editorEntry?.view' + await page.waitForFunction( + `(() => { const view = ${view}; return !!(${test}) })()`, + ) +} + +/** Whether the sheet is the dialog on top at the right edge of the viewport. */ +const sheetOnTop = (page: Page) => + page.evaluate(() => { + const top = document.elementFromPoint(window.innerWidth - 40, 100) + return !!top?.closest('dialog')?.querySelector('[data-place="citations"]') + }) + +/** Finding A, its sheet, then « Tout afficher »: the References tab filtered by Constat A. */ +async function filteredTab(page: Page) { + await openFinding(page, dict, 'Constat A') + await entryHolds(page, 'view.finding !== null') + await showCitations(page) + await entryHolds(page, 'view.finding && view.finding.citations') + await panel(page) + .getByRole('button', { name: dict['editor.references.panel_show_all'] }) + .click() + await expectNoDialog(page) + await entryHolds(page, "view.tab === 'references' && !!view.referenceFilter") + await expect(chip(page)).toContainText('Constat A') +} + +test.describe('the owner journey through the history', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }) => { + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({ + page, + }, info) => { + test.setTimeout(240_000) + await open(page) + // 1 to 3: the finding dialog, its sheet, « Tout afficher »; 4: the filtered tab. + await filteredTab(page) + await expect(headers(page)).toHaveCount(2) + await expect( + libraryRoot(page).getByText('2 références', { exact: true }), + ).toBeVisible() + await expect(page.getByText('Source libre')).toHaveCount(0) + const filteredId = await entryId(page) + if (!isPhone(info)) { + // 5: « Modifier » a tile: the dialog is a layer above the filtered tab, one entry. + await headers(page).first().click() + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.edit'] }) + .click() + const form = referenceDialog(page) + await expect(form).toBeVisible() + await entryHolds(page, 'view.reference !== null') + await form + .getByLabel(dict['editor.reference.citation']) + .fill('Référence A bis') + await form + .getByRole('button', { name: dict['editor.findings.save'] }) + .click() + await expectNoDialog(page) + await referenceSettled(page) + // One command, one undo; the entry on top is the filtered tab again, no orphan. + await expect(undo(page)).toHaveAttribute('aria-disabled', 'false') + expect(await entryId(page)).toBe(filteredId) + await expect(chip(page)).toBeVisible() + } + // 6: Back lands on finding A with its sheet open and on top; Forward, on the filter. + await page.goBack() + await expect(dialogs(page)).toHaveCount(2) + expect(await sheetOnTop(page)).toBe(true) + await expect(findingDialog(page)).toBeVisible() + await page.goForward() + await expectNoDialog(page) + await expect(chip(page)).toBeVisible() + await expect(headers(page)).toHaveCount(2) + // 7: « Revenir au constat » pops to the dialog with its sheet (the entry below shows it). + await page + .getByRole('button', { name: dict['editor.references.filter_back'] }) + .click() + await expect(dialogs(page)).toHaveCount(2) + expect(await sheetOnTop(page)).toBe(true) + await entryHolds(page, 'view.finding && view.finding.citations') + // 8: every Back down to the first entry: sheet, dialog, tab, drawing, then it leaves. + await page.goBack() + await expect(dialogs(page)).toHaveCount(1) + await expect(findingDialog(page)).toBeVisible() + await page.goBack() + await expectNoDialog(page) + await expect(place(page, 'findings')).toBeVisible() + await page.goBack() + await expect(page.getByRole('tab', { selected: true })).toHaveText( + new RegExp(`^${dict['editor.tab.annotations']}`), + ) + const here = page.url() + await page.goBack() + await expect.poll(() => page.url()).not.toBe(here) + }) + + test('a reload keeps the filtered tab and the chip, never a form; Back then returns to the sheet', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await filteredTab(page) + await page.reload() + await expect(place(page, 'references')).toBeVisible() + await expect(chip(page)).toContainText('Constat A') + await expect(headers(page)).toHaveCount(2) + await page.goBack() + await expect(dialogs(page)).toHaveCount(2) + expect(await sheetOnTop(page)).toBe(true) + }) + + test('the × removes the filter by replace; the search text is not in the history', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await filteredTab(page) + const id = await entryId(page) + await libraryRoot(page).getByRole('searchbox').fill('Référence') + await chip(page) + .getByRole('button', { + name: dict['editor.references.filter_remove'].replace( + '{name}', + 'Constat A', + ), + }) + .click() + await entryHolds(page, 'view.referenceFilter === null') + expect(await entryId(page)).toBe(id) + expect( + await page.evaluate(() => JSON.stringify(history.state?.usr)), + ).not.toContain('Référence') + // The search is a personal one: removing the filter keeps it (two titles start with it). + await expect(headers(page)).toHaveCount(2) + await expect(chip(page)).toHaveCount(0) + }) +}) + +test.describe('the reference dialog and the history', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; the reading journey above runs at 375 + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + /** The References tab with the dialog of the first tile open on its pushed entry. */ + async function dialogOpen(page: Page) { + await open(page) + await openTab(page, dict, 'references') + await entryHolds(page, "view.tab === 'references'") + const base = await entryId(page) + await headers(page).first().click() + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.edit'] }) + .click() + await expect(referenceDialog(page)).toBeVisible() + await entryHolds(page, 'view.reference !== null') + return base + } + + test('a double click on ✕ and on « Enregistrer » pops at most one entry', async ({ + page, + }) => { + test.setTimeout(150_000) + const base = await dialogOpen(page) + const form = referenceDialog(page) + await form + .getByRole('button', { name: dict['common.close'], exact: true }) + .dblclick() + await expectNoDialog(page) + await referenceSettled(page) + expect(await entryId(page)).toBe(base) + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.edit'] }) + .click() + await entryHolds(page, 'view.reference !== null') + await form + .getByLabel(dict['editor.reference.citation']) + .fill('Référence A bis') + await form + .getByRole('button', { name: dict['editor.findings.save'] }) + .dblclick() + await expectNoDialog(page) + await referenceSettled(page) + expect(await entryId(page)).toBe(base) + // One command: one « Défaire » restores the citation. + await expect(libraryRoot(page).getByText('Référence A bis')).toBeVisible() + await undo(page).click() + await expect(libraryRoot(page).getByText('Référence A bis')).toHaveCount(0) + await expect(undo(page)).toHaveAttribute('aria-disabled', 'true') + }) + + test('a held Escape closes a pristine dialog and pops at most one entry', async ({ + page, + }) => { + test.setTimeout(150_000) + const base = await dialogOpen(page) + await page.keyboard.down('Escape') + await page.keyboard.down('Escape') + await page.keyboard.down('Escape') + await page.keyboard.up('Escape') + await expectNoDialog(page) + await referenceSettled(page) + expect(await entryId(page)).toBe(base) + await expect(place(page, 'references')).toBeVisible() + }) + + test('a real dialog.close() on a dirty dialog keeps it, with its confirmation', async ({ + page, + }) => { + test.setTimeout(150_000) + await dialogOpen(page) + const form = referenceDialog(page) + await form.getByLabel(dict['editor.reference.doi']).fill('10.1000/x') + await page.evaluate(() => { + const open = [...document.querySelectorAll('dialog[open]')] + ;(open.at(-1) as HTMLDialogElement).close() + }) + await expect(form).toBeVisible() + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await expect(form.getByLabel(dict['editor.reference.doi'])).toHaveValue( + '10.1000/x', + ) + }) + + test('a dirty dialog keeps its draft on Back, one step and a jump across tabs', async ({ + page, + }) => { + test.setTimeout(180_000) + await open(page) + await openTab(page, dict, 'findings') + await entryHolds(page, "view.tab === 'findings'") + await openTab(page, dict, 'references') + await entryHolds(page, "view.tab === 'references'") + await headers(page).first().click() + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.edit'] }) + .click() + await entryHolds(page, 'view.reference !== null') + const form = referenceDialog(page) + const doi = form.getByLabel(dict['editor.reference.doi']) + await doi.fill('10.1000/x') + const top = await entryId(page) + await page.goBack() + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await expect(doi).toHaveValue('10.1000/x') + await form + .getByRole('button', { name: dict['editor.findings.keep_typing'] }) + .click() + // The refused Back pushed the view again: a jump of two entries is refused the same way. + await entryHolds(page, 'view.reference !== null') + await page.evaluate(() => history.go(-2)) + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await expect(doi).toHaveValue('10.1000/x') + await expect(form).toBeVisible() + expect(await entryId(page)).not.toBe(top) + await entryHolds(page, 'view.reference !== null') + }) +}) diff --git a/apps/app/e2e/shell/editor-references.spec.ts b/apps/app/e2e/shell/editor-references.spec.ts index 9e938a8f..9eeeb873 100644 --- a/apps/app/e2e/shell/editor-references.spec.ts +++ b/apps/app/e2e/shell/editor-references.spec.ts @@ -9,22 +9,27 @@ import { import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { editorActor, + expectNoDialog, historyButton, libraryRoot, openEditor, openTab, place, + referenceDialog, + referenceSettled, saveDraft, seedDraft, serverDocument, serverRevision, standardShape, + startReference, } from '../support/editor' -// V1-2.6 R2.2: the collapsible reference tiles of the Références tab (boards 23, 24, 27): -// closed, open and edit states with axe on each, the keyboard walk through the tile -// headers, the leave guard of the edit view, and the read-only twin at 375 px. The spec -// seeds its own sheet and never touches another. +// V1-2.6 R2.2 and R2F-5: the collapsible reference tiles of the Références tab (boards 23, +// 24, 27): closed and open states with axe on each, the reference dialog (« Modifier », +// « Ajouter ») with axe, the keyboard walk through the tile headers, the dialog's draft +// and its read-only flip, and the read-only twin at 375 px. The spec seeds its own sheet +// and never touches another. const dict = fr @@ -79,7 +84,7 @@ const REF_DOI = 1 const REF_A = 0 const REF_FREE = 2 -test.describe('reference tiles, edit mode', () => { +test.describe('reference tiles and the reference dialog', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { test.skip( @@ -92,7 +97,7 @@ test.describe('reference tiles, edit mode', () => { await dropLateReplays(context) }) - test('closed, open and edit tiles, accessible in each state', async ({ + test('closed and open tiles, then the reference dialog, accessible in each state', async ({ page, requests, }) => { @@ -139,23 +144,30 @@ test.describe('reference tiles, edit mode', () => { ).toBeVisible() await expectAccessible(page, 'the open reference tiles') - // Edit: the title, the focused citation, « Terminer » only. - await cited - .getByRole('button', { name: dict['editor.references.edit'] }) - .click() + // « Modifier » opens the dialog: named, over the page, accessible; the tile has no field. + const modify = cited.getByRole('button', { + name: dict['editor.references.edit'], + }) + await modify.click() + const form = referenceDialog(page) + await expect(form).toBeVisible() await expect( - cited.getByText(dict['editor.references.edit_title']), + form.getByRole('heading', { name: dict['editor.references.edit_title'] }), ).toBeVisible() + await expect(form.locator(':focus')).toHaveCount(1) await expect( cited.getByLabel(dict['editor.reference.citation']), - ).toBeFocused() - await expect( - cited.getByRole('button', { name: dict['editor.action.move_up'] }), ).toHaveCount(0) - await expectAccessible(page, 'a reference tile in edit') + await expectAccessible(page, 'the reference dialog') + await form + .getByRole('button', { name: dict['editor.findings.cancel'] }) + .click() + await expectNoDialog(page) + await referenceSettled(page) + await expect(modify).toBeFocused() }) - test('« Terminer » keeps the edit view while a field is refused', async ({ + test('« Enregistrer » refuses a bad address on its field, then saves one command', async ({ page, }) => { test.setTimeout(120_000) @@ -166,29 +178,26 @@ test.describe('reference tiles, edit mode', () => { await tile .getByRole('button', { name: dict['editor.references.edit'] }) .click() - const url = tile.getByLabel(dict['editor.reference.url']) + const form = referenceDialog(page) + const url = form.getByLabel(dict['editor.reference.url']) await url.fill('exemple.org') - await tile - .getByRole('button', { - name: dict['editor.references.done'], - exact: true, - }) + await form + .getByRole('button', { name: dict['editor.findings.save'] }) .click() await expect(url).toBeFocused() - await expect( - tile.getByRole('button', { - name: dict['editor.references.done'], - exact: true, - }), - ).toBeVisible() + await expect(url).toHaveAccessibleDescription( + dict['editor.reference.url_invalid'], + ) + await expect(historyButton(page, dict, 'undo')).toHaveAttribute( + 'aria-disabled', + 'true', + ) await url.fill('https://exemple.org/page') - await tile - .getByRole('button', { - name: dict['editor.references.done'], - exact: true, - }) + await form + .getByRole('button', { name: dict['editor.findings.save'] }) .click() - await expect(tile.getByLabel(dict['editor.reference.url'])).toHaveCount(0) + await expectNoDialog(page) + await referenceSettled(page) await expect( tile.getByRole('link', { name: /exemple\.org/ }), ).toHaveAttribute('href', 'https://exemple.org/page') @@ -363,7 +372,7 @@ test.describe('reference tiles, search, sort and add', () => { expect(await serverRevision(seed.draftId)).toBe(revision) }) - test('add a reference, save it, then delete an uncited one', async ({ + test('add a reference: the list stays, a notice offers « Afficher »; then delete an uncited one', async ({ page, requests, }) => { @@ -374,28 +383,36 @@ test.describe('reference tiles, search, sort and add', () => { const bar = toolbar(page) await bar.sort.selectOption('count') await bar.search.fill('alpha') - await libraryRoot(page) - .getByRole('button', { name: dict['editor.references.add'] }) - .click() - await expect(bar.search).toHaveValue('') - await expect(bar.sort).toHaveValue('sheet') - const citation = libraryRoot(page).getByLabel( - dict['editor.reference.citation'], - ) - await expect(citation).toBeFocused() - // The focus scrolled the toolbar under the sticky header: axe judges what is covered. - await libraryRoot(page).getByRole('searchbox').scrollIntoViewIfNeeded() - await expectAccessible(page, 'the draft tile') - await libraryRoot(page) - .getByLabel(dict['editor.reference.type']) - .selectOption('manual') - await citation.fill('Nouvelle source') - await libraryRoot(page) + await startReference(page, dict) + // The dialog is a layer over the page: the search and the sort are untouched. + await expect(bar.search).toHaveValue('alpha') + await expect(bar.sort).toHaveValue('count') + const form = referenceDialog(page) + await expectAccessible(page, 'the creation dialog') + await form.locator('#reference-form-type').selectOption('manual') + await form.locator('#reference-form-citation').fill('Nouvelle source') + await form .getByRole('button', { name: dict['editor.reference.add'] }) .click() + await expectNoDialog(page) + await referenceSettled(page) + await expect(headers(page)).toHaveCount(1) + const notice = libraryRoot(page).getByText( + dict['editor.references.added'].replace('{citation}', 'Nouvelle source'), + ) + await expect(notice).toBeVisible() + await expect( + libraryRoot(page).getByRole('button', { + name: dict['editor.references.add'], + }), + ).toBeFocused() + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.added_show'] }) + .click() + await expect(notice).toHaveCount(0) + await expect(bar.search).toHaveValue('') await expect(headers(page)).toHaveCount(5) - const added = headers(page).last() - await expect(added).toContainText('Nouvelle source') + const added = headers(page).filter({ hasText: 'Nouvelle source' }) await expect(added).toHaveAttribute('aria-expanded', 'true') await expect(added).toBeFocused() await saveDraft(page, dict, seed.revision + 1) @@ -408,6 +425,7 @@ test.describe('reference tiles, search, sort and add', () => { ]) // Delete an uncited reference (Étude): the dialog confirms, the tile goes. + await bar.sort.selectOption('sheet') await headers(page).nth(3).click() await tileAt(page, 3) .getByRole('button', { name: dict['editor.action.delete'] }) @@ -420,7 +438,7 @@ test.describe('reference tiles, search, sort and add', () => { await expect(libraryRoot(page).getByText('Étude')).toHaveCount(0) }) - test("« Annuler l'ajout » and Escape drop the draft and write nothing", async ({ + test('« Annuler » and Escape ask before they drop a typed draft, and write nothing', async ({ page, requests, }) => { @@ -434,61 +452,41 @@ test.describe('reference tiles, search, sort and add', () => { }) const count = await headers(page).count() const states = async () => [ - await historyButton(page, dict, 'undo').isEnabled(), - await historyButton(page, dict, 'redo').isEnabled(), + await historyButton(page, dict, 'undo').getAttribute('aria-disabled'), + await historyButton(page, dict, 'redo').getAttribute('aria-disabled'), ] const before = await states() - const draft = root.getByRole('region', { - name: dict['editor.reference.new'], - }) - const type = root.getByLabel(dict['editor.reference.type']) - await add.click() - await type.selectOption('manual') - await root.getByLabel(dict['editor.reference.citation']).fill('Brouillon') - await root - .getByRole('button', { name: dict['editor.references.add_cancel'] }) + await startReference(page, dict) + const form = referenceDialog(page) + await form.locator('#reference-form-type').selectOption('manual') + await form.locator('#reference-form-citation').fill('Brouillon') + await form + .getByRole('button', { name: dict['editor.findings.cancel'] }) .click() - await expect(draft).toHaveCount(0) - await expect(headers(page)).toHaveCount(count) - await expect(add).toBeFocused() - expect(await states()).toEqual(before) - // A typed draft, then Escape on the type select (not a text target): it cancels. - await add.click() - await root.getByLabel(dict['editor.reference.citation']).fill('Brouillon') - await type.focus() + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await form + .getByRole('button', { name: dict['editor.findings.keep_typing'] }) + .click() + await expect(form.locator('#reference-form-citation')).toHaveValue( + 'Brouillon', + ) await page.keyboard.press('Escape') - await expect(draft).toHaveCount(0) + await expect( + form.getByText(dict['editor.findings.discard_ask']), + ).toBeVisible() + await form + .getByRole('button', { name: dict['editor.findings.discard'] }) + .click() + await expectNoDialog(page) + await referenceSettled(page) await expect(headers(page)).toHaveCount(count) await expect(add).toBeFocused() expect(await states()).toEqual(before) }) - test('a tile in edit keeps its place under a sort and under a search', async ({ - page, - requests, - }) => { - test.setTimeout(150_000) - const { actor } = await open(page, sortShape) - requests.forbid(actor.account.email, actor.account.password) - await openTab(page, dict, 'references') - const bar = toolbar(page) - await bar.sort.selectOption('citation') - await headers(page).nth(3).click() - await tileAt(page, 3) - .getByRole('button', { name: dict['editor.references.edit'] }) - .click() - await bar.sort.selectOption('count') - await expect( - tileAt(page, 3).getByLabel(dict['editor.reference.citation']), - ).toBeVisible() - await bar.search.fill('alpha') - await expect(headers(page)).toHaveCount(2) - await expect( - libraryRoot(page).getByLabel(dict['editor.reference.citation']), - ).toBeVisible() - }) - - test('a tile edited out of the search stays after « Terminer », with its line, until the next search', async ({ + test('a tile edited out of the search stays after « Enregistrer », with its line, until the next search', async ({ page, requests, }) => { @@ -505,14 +503,12 @@ test.describe('reference tiles, search, sort and add', () => { await tile .getByRole('button', { name: dict['editor.references.edit'] }) .click() - const citation = tile.getByLabel(dict['editor.reference.citation']) - await citation.fill('Autre titre') - await tile - .getByRole('button', { - name: dict['editor.references.done'], - exact: true, - }) + const form = referenceDialog(page) + await form.getByLabel(dict['editor.reference.citation']).fill('Autre titre') + await form + .getByRole('button', { name: dict['editor.findings.save'] }) .click() + await expectNoDialog(page) await expect( tile.getByText(dict['editor.references.outside_search']), ).toBeVisible() @@ -523,42 +519,45 @@ test.describe('reference tiles, search, sort and add', () => { await expect(headers(page)).toHaveCount(0) }) - test('a refused draft is never dropped silently by a read-only flip', async ({ + test('a draft is never dropped by a read-only flip: the dialog keeps it, read-only, with its notice', async ({ page, }) => { test.setTimeout(150_000) await open(page) await openTab(page, dict, 'references') - const bar = toolbar(page) await headers(page).nth(REF_DOI).click() - const tile = libraryRoot(page) - .locator('button[id$="-ref-doi-header"]') - .locator('xpath=ancestor::li[1]') - await tile + await tileAt(page, REF_DOI) .getByRole('button', { name: dict['editor.references.edit'] }) .click() - await bar.search.fill('libre') - const url = tile.getByLabel(dict['editor.reference.url']) + const form = referenceDialog(page) + const url = form.getByLabel(dict['editor.reference.url']) await url.fill('exemple.org') - const note = dict['editor.references.draft_dropped'].replace( - '{field}', - dict['editor.reference.url'], - ) const size = page.viewportSize() ?? { width: 1280, height: 900 } await page.setViewportSize({ width: 800, height: size.height }) - await expect(tile.getByText(note)).toBeVisible() - await expect(page.locator('p.sr-only[aria-live="polite"]')).toHaveText(note) - await expect(url).toHaveCount(0) + await expect(form).toBeVisible() + await expect(url).toHaveAttribute('readonly', '') + await expect(url).toHaveValue('exemple.org') + await expect( + form.getByText(dict['editor.findings.flip_narrow']), + ).toBeVisible() + await expect( + form.getByRole('button', { name: dict['editor.findings.save'] }), + ).toBeDisabled() await page.setViewportSize(size) - await expect(tile.getByText(note)).toBeVisible() - await expect(url).toHaveValue(`https://doi.org/${DOI}`) - await tile - .getByRole('button', { - name: dict['editor.references.done'], - exact: true, - }) + await expect(url).not.toHaveAttribute('readonly', '') + await expect(url).toHaveValue('exemple.org') + await form + .getByRole('button', { name: dict['editor.findings.cancel'] }) .click() - await expect(tile.getByText(note)).toHaveCount(0) + await form + .getByRole('button', { name: dict['editor.findings.discard'] }) + .click() + await expectNoDialog(page) + await expect( + tileAt(page, REF_DOI) + .getByRole('link', { name: new RegExp(DOI) }) + .first(), + ).toBeVisible() }) }) diff --git a/apps/app/e2e/shell/editor-shell-crossing.spec.ts b/apps/app/e2e/shell/editor-shell-crossing.spec.ts index a7d82654..cc50d3bc 100644 --- a/apps/app/e2e/shell/editor-shell-crossing.spec.ts +++ b/apps/app/e2e/shell/editor-shell-crossing.spec.ts @@ -8,9 +8,9 @@ import { closeFinding, copyKeyOf, editorActor, + expectNoDialog, geometryField, historyButton, - libraryRoot, openEditor, openCitations, openTab, @@ -23,6 +23,7 @@ import { selectTab, shapeWith, standardShape, + startReference, storedCopy, UNSAVED_LINE, } from '../support/editor' @@ -217,21 +218,37 @@ test.describe('editor shell, width crossing (H)', () => { ) }) - test('the references form keeps its typed text, in the Références tab', async ({ + test('the reference dialog stays while narrow: draft, focus and a notice kept (R2F-5)', async ({ page, }) => { await open(page) await openTab(page, dict, 'references') + await startReference(page, dict) + const field = page.locator('#reference-form-citation') + await field.fill('Saisie') + await expect(field).toBeFocused() + await page.setViewportSize(NARROW) + await expect(field).toBeVisible() + await expect(field).toHaveAttribute('readonly', '') + await expect(field).toHaveValue('Saisie') + await expect(field).toBeFocused() + await expect( + page.getByText(dict['editor.findings.flip_narrow']), + ).toBeVisible() + await expect( + page.getByRole('button', { name: dict['editor.reference.add'] }), + ).toBeDisabled() + await page.setViewportSize(WIDE) + await expect(field).not.toHaveAttribute('readonly', '') + await expect(field).toHaveValue('Saisie') + await expect(field).toBeFocused() + await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE) + await page.keyboard.press('Escape') await page - .getByRole('button', { name: dict['editor.references.add'] }) + .locator('dialog[open]') + .getByRole('button', { name: dict['editor.findings.discard'] }) .click() - await keepsTypedValue( - page, - page.locator('#tab-reference-new-citation'), - dict['editor.reference.add'], - 'references', - ) - await expect(libraryRoot(page).getByRole('searchbox')).toBeVisible() + await expectNoDialog(page) }) test('the annotation edit body keeps its tool and its pending creation', async ({ diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index 2a4b6d66..296a7a8f 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -3,6 +3,7 @@ import type { Locator, Page, TestInfo } from '@playwright/test' import { expect, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + addReference, backToDrawing, copyKeyOf, storedCopy, @@ -94,20 +95,18 @@ test.describe('editor shell, kept places (B2a)', () => { expect(await layerTransform(page)).toBe(zoomed) }) - test('the Références tab keeps its form text and no id repeats, panel open included', async ({ + test('the Références tab keeps its search and no id repeats, panel open included', async ({ page, }) => { await open(page) await openTab(page, dict, 'references') - await page - .getByRole('button', { name: dict['editor.references.add'] }) - .click() - await page.locator('#tab-reference-new-citation').fill('Smith 1999') + const search = page.getByRole('searchbox', { + name: dict['editor.references.search'], + }) + await search.fill('Smith 1999') await openTab(page, dict, 'general') await openTab(page, dict, 'references') - await expect(page.locator('#tab-reference-new-citation')).toHaveValue( - 'Smith 1999', - ) + await expect(search).toHaveValue('Smith 1999') for (const tab of ['general', 'findings', 'verification']) { await selectTab(page, dict, tab) } @@ -133,14 +132,7 @@ test.describe('editor shell, kept places (B2a)', () => { await open(page) // An edit first, so « Enregistrer » is enabled: a reference added in its tab. await openTab(page, dict, 'references') - await page - .getByRole('button', { name: dict['editor.references.add'] }) - .click() - await page.locator('#tab-reference-new-type').selectOption('book') - await page.locator('#tab-reference-new-citation').fill('Smith 1999') - await page - .getByRole('button', { name: dict['editor.reference.add'] }) - .click() + await addReference(page, dict, 'Smith 1999') await openCitations(page, dict, 'Constat A') const targets = [ page.getByRole('button', { name: dict['common.save'], exact: true }), diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts index 4d0a59fd..8eb0fc69 100644 --- a/apps/app/e2e/shell/editor-structures.spec.ts +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -3,6 +3,7 @@ import type { Locator, Page, TestInfo } from '@playwright/test' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { + addReference, bareShape, closeFinding, editorActor, @@ -85,17 +86,10 @@ test.describe('editor structures (A4)', () => { // « Référence A » stays first: it is cited by « Constat A »). await openTab(page, dict, 'references') for (const citation of ['Première référence', 'Seconde référence']) { - await page - .getByRole('button', { name: dict['editor.references.add'] }) - .click() - await page.locator('#tab-reference-new-type').selectOption('book') - await page.locator('#tab-reference-new-citation').fill(citation) - await page - .getByRole('button', { name: dict['editor.reference.add'] }) - .click() + await addReference(page, dict, citation) await expect( page.getByRole('button', { name: new RegExp(`^${citation}`) }), - ).toBeFocused() + ).toBeVisible() } const tiles = page.locator('[id^="tab-reference-"][id$="-header"]') const tileOf = (citation: string) => @@ -112,17 +106,13 @@ test.describe('editor structures (A4)', () => { await expect(tiles).toHaveCount(1) await search.fill('') await expect(tiles).toHaveCount(3) - // An added tile stays open (P24): no click, a click would close it. - await expect( - tiles.filter({ hasText: 'Seconde référence' }), - ).toHaveAttribute('aria-expanded', 'true') + // An added tile is closed (the list does not move, R2F-5): open it, then move it. + await tiles.filter({ hasText: 'Seconde référence' }).click() await tileOf('Seconde référence') .getByRole('button', { name: dict['editor.action.move_up'] }) .click() await expect(tiles.nth(1)).toContainText('Seconde référence') - await expect( - tiles.filter({ hasText: 'Première référence' }), - ).toHaveAttribute('aria-expanded', 'true') + await tiles.filter({ hasText: 'Première référence' }).click() await tileOf('Première référence') .getByRole('button', { name: dict['editor.action.delete'] }) .click() diff --git a/apps/app/e2e/support/editor.ts b/apps/app/e2e/support/editor.ts index e2465d18..dc0dd084 100644 --- a/apps/app/e2e/support/editor.ts +++ b/apps/app/e2e/support/editor.ts @@ -427,11 +427,58 @@ export async function openTab(page: Page, dict: Dict, tab: string) { ).toBeVisible() } -/** The open finding dialog: the layer dialog that is not the citations sheet. */ +/** The open finding dialog: the layer dialog that is neither the sheet nor the reference form. */ export const findingDialog = (page: Page): Locator => + page.locator('dialog[open][data-layer]').filter({ + hasNot: page.locator('[data-place="citations"], #reference-form-citation'), + }) + +/** The open reference dialog (R2F-5): the layer dialog that holds the reference form. */ +export const referenceDialog = (page: Page): Locator => page .locator('dialog[open][data-layer]') - .filter({ hasNot: page.locator('[data-place="citations"]') }) + .filter({ has: page.locator('#reference-form-citation') }) + +/** + * Waits for the history to settle on a view without the reference layer (or, with + * `keepDialog`, with one): a close pops its entry from an effect, and a move made before + * the pop lands would be undone by it (a user cannot be that quick, a script can). + */ +export async function referenceSettled(page: Page, keepDialog = false) { + await page.waitForFunction((stays) => { + const view = history.state?.usr?.editorEntry?.view + if (!view) return true + return stays ? view.reference !== null : view.reference === null + }, keepDialog) +} + +/** Opens « Ajouter une référence » (the References tab is shown): the form is ready. */ +export async function startReference(page: Page, dict: Dict) { + await libraryRoot(page) + .getByRole('button', { name: dict['editor.references.add'] }) + .click() + await expect(referenceDialog(page)).toBeVisible() +} + +/** + * Creates a reference through the dialog and waits for every layer to be gone. The list + * does not move and the focus goes back to « Ajouter » (R2F-5): nothing is focused on the + * new tile. + */ +export async function addReference( + page: Page, + dict: Dict, + citation: string, + type = 'book', +) { + await startReference(page, dict) + const form = referenceDialog(page) + await form.locator('#reference-form-type').selectOption(type) + await form.locator('#reference-form-citation').fill(citation) + await form.getByRole('button', { name: dict['editor.reference.add'] }).click() + await expectNoDialog(page) + await referenceSettled(page) +} /** Waits until no modal dialog is open: nothing is typed or pressed before (LRN-111/116). */ export const expectNoDialog = (page: Page) => diff --git a/apps/app/tests/helpers/findingsHost.tsx b/apps/app/tests/helpers/findingsHost.tsx index 7eb6d60b..d065db56 100644 --- a/apps/app/tests/helpers/findingsHost.tsx +++ b/apps/app/tests/helpers/findingsHost.tsx @@ -28,10 +28,10 @@ export default function FindingsHost({ undefined} navigate={nav.navigate} + onEdit={nav.references.open} returnFocus={nav.citationsTrigger} /> diff --git a/apps/app/tests/helpers/referencesHost.tsx b/apps/app/tests/helpers/referencesHost.tsx new file mode 100644 index 00000000..e378afb3 --- /dev/null +++ b/apps/app/tests/helpers/referencesHost.tsx @@ -0,0 +1,55 @@ +import { vi } from 'vitest' +import ReferenceDialog from '@/components/editor/references/ReferenceDialog' +import ReferencesTab from '@/components/editor/tabs/ReferencesTab' +import { ReadOnlyContext } from '@/editor/editingContext' +import { referenceLayerOf } from '@/editor/findingLayer' +import { AnnounceContext } from '@/editor/focusRequest' +import { defaultView, type EditorView } from '@/editor/navigation' +import type { EditorPlaceProps } from '@/editor/tabs' +import { + useEditorNavigation, + type EditorNavigation, +} from '@/editor/useEditorNavigation' + +interface Props extends Partial { + /** The view the editor starts on (a filter, a dialog); the References tab by default. */ + view?: EditorView + /** Reads the navigation each render, for a test that drives or inspects it. */ + onNav?: (nav: EditorNavigation) => void + /** Renders the polite live region (the workspace's), for a test that reads announcements. */ + live?: boolean +} + +/** + * The References tab with the navigation that drives its dialog and its filter (what the + * workspace gives it), without the rest of the editor. + */ +export default function ReferencesHost({ + readOnly = false, + view, + onNav, + live = false, + ...extra +}: Props) { + const nav = useEditorNavigation( + 'references', + view ?? defaultView('references'), + ) + onNav?.(nav) + const references = referenceLayerOf(nav) + return ( + + + + + + {live &&

{nav.live}

} +
+ ) +} diff --git a/apps/app/tests/unit/editor-focus-request.test.tsx b/apps/app/tests/unit/editor-focus-request.test.tsx index d5e63a4d..b667016b 100644 --- a/apps/app/tests/unit/editor-focus-request.test.tsx +++ b/apps/app/tests/unit/editor-focus-request.test.tsx @@ -13,13 +13,13 @@ import type { AnatomicalSheetDocument, ElementKey, } from '@faunosteo/core-wasm/types' -import { findingLayerOf } from '@/editor/findingLayer' +import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer' import { testLayer } from '../helpers/findingsHost' +import ReferencesHost from '../helpers/referencesHost' import FindingsTab from '@/components/editor/tabs/FindingsTab' import RegionsSection from '@/components/editor/annotations/sections/RegionsSection' import EditorTabBody from '@/components/editor/EditorTabBody' import EditorTabs from '@/components/editor/EditorTabs' -import ReferencesTab from '@/components/editor/tabs/ReferencesTab' import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' import { FocusConsumedContext, @@ -164,7 +164,7 @@ describe('focus requests', () => { }) await openReady({ text }) render( - , @@ -200,9 +200,9 @@ describe('focus requests', () => { }) await openReady({ text }) const focus = request({ kind: 'reference', id: 'ref-a' }) - const view = render() + const view = render() ;(document.activeElement as HTMLElement).blur() - view.rerender() + view.rerender() expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull() }) @@ -271,6 +271,7 @@ function Probe({ go, tier }: { go: EditorTarget; tier: 'wide' | 'small' }) { {...base} navigate={nav.navigate} layer={findingLayerOf(nav)} + references={referenceLayerOf(nav)} focus={state.focus} annotations={{ section: state.section, @@ -288,7 +289,17 @@ function ShowAllProbe() { return ( <> - + ) } @@ -419,7 +430,7 @@ function Harness() { switch {shown === 'references' ? ( - + ) : ( )} diff --git a/apps/app/tests/unit/editor-history-entry.test.ts b/apps/app/tests/unit/editor-history-entry.test.ts index 0e91da19..e971f05f 100644 --- a/apps/app/tests/unit/editor-history-entry.test.ts +++ b/apps/app/tests/unit/editor-history-entry.test.ts @@ -86,6 +86,43 @@ describe('sanitizeView', () => { expect(sanitizeView(odd)?.finding).toBeNull() }) + it('the reference dialog is a form: over References or the sheet, never at a reload', () => { + const edit = { edit: 'ref-a' } + const tab = { ...view('references'), reference: edit } + expect(sanitizeView(tab)?.reference).toEqual(edit) + expect(sanitizeView(tab, false)?.reference).toBeNull() + const sheet = { + ...view('findings'), + finding: { key: node, citations: true }, + reference: edit, + } + expect(sanitizeView(sheet)?.reference).toEqual(edit) + const noSheet = { ...sheet, finding: { key: node, citations: false } } + expect(sanitizeView(noSheet)?.reference).toBeNull() + const creation = { ...view('references'), reference: { create: true } } + expect(sanitizeView(creation)?.reference).toEqual({ create: true }) + const elsewhere = { ...view('general'), reference: { create: true } } + expect(sanitizeView(elsewhere)?.reference).toBeNull() + expect( + sanitizeView({ ...tab, reference: { edit: '' } })?.reference, + ).toBeNull() + }) + + it('the finding filter names a finding node and lives on the References tab only', () => { + const filtered = view('references', { referenceFilter: node }) + expect(sanitizeView(filtered)?.referenceFilter).toEqual(node) + expect(sanitizeView(filtered, false)?.referenceFilter).toEqual(node) + expect( + sanitizeView({ ...view('general'), referenceFilter: node }) + ?.referenceFilter, + ).toBeNull() + const zone = { kind: 'zone', id: 'z' } + expect( + sanitizeView({ ...view('references'), referenceFilter: zone }) + ?.referenceFilter, + ).toBeNull() + }) + it('drops what is no view: an unknown tab, a non-object', () => { expect(sanitizeView({ tab: 'nowhere', section: 'views' })).toBeNull() expect(sanitizeView('general')).toBeNull() @@ -211,6 +248,46 @@ describe('planWrite', () => { }) }) +describe('planWrite and the reference layers', () => { + const sheet = view('findings', { finding: { key: node, citations: true } }) + const dialog = { ...sheet, reference: { edit: 'ref-a' } } + const top = (v: EditorView, below: EditorView | null) => + entry({ view: v, below }) + + it('the reference dialog is a layer: added pushes, removed goes back to the view below', () => { + expect(planWrite(top(sheet, null), dialog, false)).toBe('push') + expect(planWrite(top(dialog, sheet), sheet, false)).toBe('back') + expect(planWrite(top(dialog, view('general')), sheet, false)).toBe( + 'replace', + ) + expect(layerCount(dialog)).toBe(3) + }) + + it('a creation turned into its element is a replace; the filter removal is a replace hint', () => { + const creating = view('references', { reference: { create: true } }) + const editing = view('references', { reference: { edit: 'ref-n' } }) + expect(planWrite(top(creating, null), editing, true)).toBe('replace') + const filtered = view('references', { referenceFilter: node }) + expect(planWrite(top(filtered, sheet), view('references'), true)).toBe( + 'replace', + ) + }) + + it('« Revenir au constat » goes back when the entry below shows that finding, else pushes', () => { + const filtered = view('references', { referenceFilter: node }) + const dialogOnly = view('findings', { + finding: { key: node, citations: false }, + }) + expect(planWrite(top(filtered, sheet), dialogOnly, false, node)).toBe( + 'back', + ) + expect( + planWrite(top(filtered, view('general')), dialogOnly, false, node), + ).toBe('push') + expect(planWrite(top(filtered, sheet), dialogOnly, false)).toBe('push') + }) +}) + describe('createWriteBudget', () => { it('lets the limit through per window, then refuses until the window slides', () => { const take = createWriteBudget(3, 1000) diff --git a/apps/app/tests/unit/editor-history-guards.test.tsx b/apps/app/tests/unit/editor-history-guards.test.tsx index 10e8eed4..2827aa41 100644 --- a/apps/app/tests/unit/editor-history-guards.test.tsx +++ b/apps/app/tests/unit/editor-history-guards.test.tsx @@ -131,19 +131,23 @@ describe('the guard stack', () => { const { result } = renderHook(() => useEditorNavigation('general')) const { guards } = result.current const order: string[] = [] - guards.register('citations', () => { - order.push('citations') + guards.register('reference', () => { + order.push('reference') return { allowed: true, note: 'a' } }) guards.register('finding', () => { order.push('finding') return { allowed: false, note: 'b' } }) - expect(guards.ask('reference', false)).toEqual({ allowed: true }) + expect(guards.ask('reference', false)).toEqual({ + allowed: true, + note: 'a', + }) expect(guards.ask('finding', true).allowed).toBe(false) order.length = 0 - expect(guards.askAll(false)).toEqual({ allowed: false, note: 'b. a' }) - expect(order).toEqual(['finding', 'citations']) + // The reference dialog is the top layer: it is asked first. + expect(guards.askAll(false)).toEqual({ allowed: false, note: 'a. b' }) + expect(order).toEqual(['reference', 'finding']) guards.register('finding', null) expect(guards.askAll(false).allowed).toBe(true) }) diff --git a/apps/app/tests/unit/editor-keep-alive.test.tsx b/apps/app/tests/unit/editor-keep-alive.test.tsx index 20dddf87..3cf8c527 100644 --- a/apps/app/tests/unit/editor-keep-alive.test.tsx +++ b/apps/app/tests/unit/editor-keep-alive.test.tsx @@ -10,7 +10,6 @@ import { within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' import EditorTabBody from '@/components/editor/EditorTabBody' import KeptPlace from '@/components/editor/KeptPlace' import { useSheetDocument } from '@/editor/sheetDocument' @@ -36,7 +35,6 @@ import { versionAnswer, } from '../helpers/editorHarness' import { testLayer } from '../helpers/findingsHost' -import { openFinding } from '../helpers/findingDialog' import { mountDraft, setWidth } from '../helpers/editorRoute' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) @@ -112,26 +110,6 @@ function findingsText(from = baseText(), nodeRefs?: string[]): string { }) } -function referenceText(): string { - return insert(baseText(), { - kind: 'reference', - value: { - id: 'ref-1', - type: 'journal', - citation: 'Doe 2020', - url: null, - doi: null, - }, - }) -} - -/** Constats, the node selected, its « 1 référence » trigger pressed. */ -async function openCitations(user: Awaited>) { - await user.click(tab('Constats')) - await openFinding(user, /Node A/) - await user.click(screen.getByRole('button', { name: '1 référence' })) -} - async function mount(text = baseText()) { serverHas(text, 3) const user = userEvent.setup() @@ -199,22 +177,17 @@ describe('text typed in a place that is left', () => { expect(store.getState().unsaved).toBe(false) }) - it('the reference add form survives leaving and returning to the Références tab', async () => { + it('the references search survives leaving and returning to the Références tab', async () => { const user = await mount() await user.click(tab('Références')) - await user.click( - inPlace('references').getByRole('button', { - name: 'Ajouter une référence', - }), - ) - const field = inPlace('references').getByLabelText('Citation', { - selector: '#tab-reference-new-citation', + const box = inPlace('references').getByRole('searchbox', { + name: 'Rechercher une référence', }) - await user.type(field, 'Smith 1999') + await user.type(box, 'Smith 1999') await user.click(tab('Annotations')) expect(place('references')).not.toBeVisible() await user.click(tab('Références')) - expect(field).toHaveValue('Smith 1999') + expect(box).toHaveValue('Smith 1999') expect(store.getState().unsaved).toBe(false) }) }) @@ -328,67 +301,6 @@ describe('a field still focused while a place is left', () => { act(() => void store.getState().undoStep()) expect(store.getState().documentText).toBe(before) }) - - it('a tab click without a focus move commits the Références text, as one undo entry', async () => { - const user = await mount(referenceText()) - const before = store.getState().documentText - await user.click(tab('Références')) - await user.click(inPlace('references').getByRole('button', { name: /Doe/ })) - await user.click( - inPlace('references').getByRole('button', { name: 'Modifier' }), - ) - const field = inPlace('references').getByLabelText('Citation', { - selector: '#tab-reference-0-ref-1-citation', - }) - await user.click(field) - fireEvent.change(field, { target: { value: 'Doe 2023' } }) - fireEvent.click(tab(/Vérification/)) - expect( - JSON.parse(store.getState().documentText).references[0].citation, - ).toBe('Doe 2023') - expect(store.getState().unsaved).toBe(true) - expect(place('references')).not.toBeVisible() - act(() => void store.getState().undoStep()) - expect(store.getState().documentText).toBe(before) - }) - - /** The panel's first tile opened in edit, its citation field typed in (not blurred). */ - async function typeInPanelTile(user: Awaited>) { - await openCitations(user) - const panel = inPlace('citations') - await user.click(panel.getByRole('button', { name: /Doe/ })) - await user.click(panel.getByRole('button', { name: 'Modifier' })) - const field = panel.getByLabelText('Citation', { - selector: '#panel-reference-0-ref-1-citation', - }) - await user.click(field) - fireEvent.change(field, { target: { value: 'Doe 2021' } }) - return field - } - - const savedCitation = () => - (JSON.parse(store.getState().documentText) as AnatomicalSheetDocument) - .references[0].citation - - it('Escape in a field of a panel tile neither closes the panel nor commits the text (A5)', async () => { - const user = await mount(findingsText(referenceText(), ['ref-1'])) - const before = store.getState().documentText - await typeInPanelTile(user) - await user.keyboard('{Escape}') - expect(screen.getByTestId('editor-citations-panel')).toBeInTheDocument() - expect(store.getState().documentText).toBe(before) - }) - - it('the scrim (no focus move) commits the typed text, then closes the panel after its exit', async () => { - const user = await mount(findingsText(referenceText(), ['ref-1'])) - await typeInPanelTile(user) - fireEvent.click(screen.getByTestId('references-scrim')) - expect(savedCitation()).toBe('Doe 2021') - await waitFor(() => - expect(screen.queryByTestId('editor-citations-panel')).toBeNull(), - ) - expect(store.getState().unsaved).toBe(true) - }) }) describe('ids and parses', () => { diff --git a/apps/app/tests/unit/editor-navigation.test.ts b/apps/app/tests/unit/editor-navigation.test.ts index 3a8fee00..8e90371f 100644 --- a/apps/app/tests/unit/editor-navigation.test.ts +++ b/apps/app/tests/unit/editor-navigation.test.ts @@ -147,16 +147,69 @@ describe('navigationReducer', () => { const state = run( initialNavigation('findings'), { type: 'open_citations', citedBy: node }, - { type: 'show_all_references' }, + { type: 'show_all_references', filter: node }, ) expect(state).toMatchObject({ tab: 'references', finding: null, + referenceFilter: node, libraryReset: 1, focus: undefined, }) expect(state.visitedTabs).toEqual(['findings', 'references']) - expect(run(state, { type: 'show_all_references' }).libraryReset).toBe(2) + const again = run(state, { type: 'show_all_references', filter: node }) + expect(again.libraryReset).toBe(2) + }) + + it('the reference dialog is a layer above the place and the sheet', () => { + const open = run( + initialNavigation('findings'), + { type: 'open_citations', citedBy: node }, + { type: 'open_reference', id: 'ref-a' }, + ) + expect(open).toMatchObject({ + tab: 'findings', + finding: { key: node, citations: true }, + reference: { edit: 'ref-a' }, + }) + expect(run(open, { type: 'close_reference' }).reference).toBeNull() + const created = run(initialNavigation('general'), { + type: 'create_reference', + }) + expect(created).toMatchObject({ + tab: 'references', + reference: { create: true }, + }) + }) + + it('the filter belongs to the References tab: any move to another tab drops it', () => { + const filtered = run(initialNavigation('findings'), { + type: 'show_all_references', + filter: node, + }) + expect( + run(filtered, { type: 'select_tab', tab: 'references' }), + ).toMatchObject({ + referenceFilter: node, + }) + expect(run(filtered, { type: 'select_tab', tab: 'general' })).toMatchObject( + { + referenceFilter: null, + }, + ) + expect(run(filtered, { type: 'open_finding', key: node })).toMatchObject({ + tab: 'findings', + referenceFilter: null, + finding: { key: node, citations: false }, + }) + const toReference = run(filtered, { + type: 'go_to', + target: targetOfKey({ kind: 'reference', id: 'x' }), + }) + expect(toReference.referenceFilter).toBeNull() + expect( + run(filtered, { type: 'clear_reference_filter' }).referenceFilter, + ).toBeNull() }) it('a plain go_to a reference leaves the library reset alone', () => { diff --git a/apps/app/tests/unit/editor-no-loss.test.tsx b/apps/app/tests/unit/editor-no-loss.test.tsx index ecb4b6d5..6f7c29ef 100644 --- a/apps/app/tests/unit/editor-no-loss.test.tsx +++ b/apps/app/tests/unit/editor-no-loss.test.tsx @@ -143,18 +143,6 @@ describe('typed values come back after a 1 024 px crossing', () => { ) }) - it('the reference creation form, in the Références tab', async () => { - const user = await mount() - await user.click(tab('Références')) - await user.click(button('Ajouter une référence')) - await keepsTypedValue( - user, - 'tab-reference-new-citation', - 'Citation', - 'Ajouter la référence', - ) - }) - it('the region creation form', async () => { const user = await mount() await user.click(tab('Annotations')) diff --git a/apps/app/tests/unit/editor-reference-dialog.test.tsx b/apps/app/tests/unit/editor-reference-dialog.test.tsx new file mode 100644 index 00000000..d5fd3cea --- /dev/null +++ b/apps/app/tests/unit/editor-reference-dialog.test.tsx @@ -0,0 +1,534 @@ +/** R2F-5 and R2F-6: the reference dialog, the reading tiles, the finding filter, their history. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { Location, NavigateFunction } from 'react-router-dom' +import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry' +import { useLocaleStore } from '@/state/localeStore' +import { edit, insert } from '../helpers/editorFixtures' +import { + baseText, + resetStore, + serverHas, + store, +} from '../helpers/editorHarness' +import { mountDraft, setWidth } from '../helpers/editorRoute' +import { findingDialog, openFinding } from '../helpers/findingDialog' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +let navigate: NavigateFunction +let location: Location +const probe = (n: NavigateFunction, l: Location) => { + navigate = n + location = l +} +const written = () => + (location.state as Record | null)?.[ENTRY_KEY] +const back = () => act(async () => navigate(-1)) + +beforeEach(() => useLocaleStore.setState({ locale: 'fr' })) +afterEach(() => { + cleanup() + resetStore() + setWidth(1024) +}) + +const name = (n: string) => ({ fr: n, en: n }) +const ref = (id: string, citation: string, url = '') => + ({ + kind: 'reference', + value: { id, type: 'book', citation, url: url || null, doi: null }, + }) as const + +/** Three references; Node A (under Cat A) cites ref-a and ref-b. */ +function sheetText(): string { + let text = baseText() + text = insert(text, ref('ref-a', 'Barone, Ostéologie')) + text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/p')) + text = insert(text, ref('ref-c', 'Code rural')) + text = insert(text, { + kind: 'zone', + value: { id: 'zone-a', name: name('Zone A'), categories: [] }, + }) + text = edit(text, { + op: 'insert', + parent: { kind: 'zone', id: 'zone-a' }, + element: { + kind: 'finding_category', + value: { + id: 'fcat-a', + kind: 'dysfunction', + name: name('Cat A'), + description: {}, + reference_ids: [], + review_status: 'to_confirm', + children: [], + }, + }, + }) + return edit(text, { + op: 'insert', + parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }, + element: { + kind: 'finding_node', + value: { + id: 'fnode-a', + name: name('Node A'), + description: {}, + requires_vet_referral: false, + reference_ids: ['ref-a', 'ref-b'], + review_status: 'to_confirm', + children: [], + }, + }, + }) +} + +type User = ReturnType + +async function mount(width = 1280): Promise { + serverHas(sheetText(), 3) + const user = userEvent.setup() + mountDraft({ width, probe }) + await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) + await user.click(screen.getByRole('tab', { name: 'Références' })) + await waitFor(() => expect(written()?.view.tab).toBe('references')) + return user +} + +const doc = () => JSON.parse(store.getState().documentText) +const entries = () => store.getState().undo.length +const dialogs = () => document.querySelectorAll('dialog[open]') +const refDialog = () => + [...dialogs()].find((d) => d.querySelector('[data-draft-form]')) as + | HTMLElement + | undefined +const inRef = () => within(refDialog()!) +const closed = () => waitFor(() => expect(refDialog()).toBeUndefined()) +const tab = () => screen.getByRole('tabpanel', { name: 'Références' }) +const header = (citation: string) => + within(tab()).getByRole('button', { name: new RegExp(`^${citation}`) }) +const modify = async (user: User, citation: string) => { + if (header(citation).getAttribute('aria-expanded') === 'false') { + await user.click(header(citation)) + } + const tile = header(citation).closest('li')! + await user.click(within(tile).getByRole('button', { name: 'Modifier' })) + await waitFor(() => expect(refDialog()).toBeDefined()) +} +const field = (label: string) => inRef().getByLabelText(label) +const save = (user: User) => + user.click( + inRef().getByRole('button', { + name: /^(Enregistrer|Ajouter la référence)$/, + }), + ) +const live = () => document.querySelector('p.sr-only[aria-live="polite"]')! + +describe('the dialog', () => { + it('opens from « Modifier » with the first control focused, one entry on top', async () => { + const user = await mount() + const first = written()!.id + await modify(user, 'Barone') + expect( + inRef().getByRole('heading', { name: 'Modifier la référence' }), + ).toBeVisible() + expect(refDialog()!.contains(document.activeElement)).toBe(true) + expect(field('Citation')).toHaveValue('Barone, Ostéologie') + await waitFor(() => expect(written()?.id).not.toBe(first)) + expect(written()?.view.reference).toEqual({ edit: 'ref-a' }) + expect(written()?.below?.reference).toBeNull() + }) + + it('a pristine « Enregistrer » closes with no command; a changed one is one entry', async () => { + const user = await mount() + await modify(user, 'Barone') + const before = entries() + await save(user) + await closed() + expect(entries()).toBe(before) + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1000/x') + await user.clear(field('Citation')) + await user.type(field('Citation'), 'Neuf') + await user.type(field('Adresse web (URL)'), 'https://a.org/') + await save(user) + await closed() + expect(entries()).toBe(before + 1) + expect(doc().references[0]).toMatchObject({ + citation: 'Neuf', + doi: '10.1000/x', + url: 'https://a.org/', + }) + act(() => void store.getState().undoStep()) + expect(doc().references[0]).toMatchObject({ + citation: 'Barone, Ostéologie', + doi: null, + url: null, + }) + }) + + it('a double click on « Enregistrer » writes once and pops at most one entry', async () => { + const user = await mount() + const mounted = written()!.id + await modify(user, 'Barone') + await user.clear(field('Citation')) + await user.type(field('Citation'), 'Neuf') + const button = inRef().getByRole('button', { name: 'Enregistrer' }) + fireEvent.click(button) + fireEvent.click(button) + await closed() + expect(entries()).toBe(1) + await waitFor(() => expect(written()?.id).toBe(mounted)) + }) + + it('a blank citation and a non-http address are refused on their field', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.clear(field('Citation')) + await save(user) + expect(field('Citation')).toHaveFocus() + expect(field('Citation')).toHaveAccessibleDescription( + 'Ce champ est obligatoire.', + ) + await user.type(field('Citation'), 'Barone') + await user.type(field('Adresse web (URL)'), 'exemple.org') + await save(user) + expect(field('Adresse web (URL)')).toHaveFocus() + expect(field('Adresse web (URL)')).toHaveAccessibleDescription( + /http:\/\/ ou https:\/\//, + ) + expect(entries()).toBe(0) + expect(refDialog()).toBeDefined() + }) + + it('« Annuler » with changes asks, « Abandonner » writes nothing', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1/x') + await user.click(inRef().getByRole('button', { name: 'Annuler' })) + expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible() + expect( + inRef().getByRole('button', { name: 'Continuer la saisie' }), + ).toHaveFocus() + await user.click( + inRef().getByRole('button', { name: 'Continuer la saisie' }), + ) + expect(field('DOI')).toHaveValue('10.1/x') + await user.click(inRef().getByRole('button', { name: 'Annuler' })) + await user.click(inRef().getByRole('button', { name: 'Abandonner' })) + await closed() + expect(entries()).toBe(0) + }) + + it('a real dialog.close() on a dirty dialog keeps it, with its confirmation', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1/x') + act(() => (refDialog() as HTMLDialogElement).close()) + await waitFor(() => + expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible(), + ) + expect(refDialog()!.hasAttribute('open')).toBe(true) + expect(field('DOI')).toHaveValue('10.1/x') + }) + + it('Escape asks once when dirty; a held Escape (repeat) is ignored', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1/x') + fireEvent.keyDown(field('DOI'), { key: 'Escape', repeat: true }) + expect(inRef().queryByText('Abandonner les modifications ?')).toBeNull() + fireEvent.keyDown(field('DOI'), { key: 'Escape' }) + expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible() + }) + + it('Défaire is unreachable under the dialog and a mode flip leaves the draft untouched', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1/x') + fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) + expect(field('DOI')).toHaveValue('10.1/x') + const same = field('DOI') + act(() => { + setWidth(900) + window.dispatchEvent(new Event('resize')) + }) + expect(field('DOI')).toBe(same) + expect(same).toHaveAttribute('readonly') + expect(inRef().getByText(/Élargissez la fenêtre/)).toBeVisible() + expect(inRef().getByRole('button', { name: 'Enregistrer' })).toBeDisabled() + expect(entries()).toBe(0) + act(() => { + setWidth(1280) + window.dispatchEvent(new Event('resize')) + }) + expect(same).not.toHaveAttribute('readonly') + expect(same).toHaveValue('10.1/x') + }) + + it('a reference that vanishes closes its dialog by replace and says so', async () => { + const user = await mount() + await modify(user, 'Code rural') + const open = written()! + act(() => { + store + .getState() + .commit({ op: 'remove', key: { kind: 'reference', id: 'ref-c' } }) + }) + await closed() + await waitFor(() => + expect(live()).toHaveTextContent("Cette référence n'existe plus"), + ) + expect(written()?.id).toBe(open.id) + expect(written()?.view.reference).toBeNull() + }) +}) + +describe('creation', () => { + const add = () => + screen.getByRole('button', { name: 'Ajouter une référence' }) + + it('needs a type and a citation, creates in one command, leaves the list and says so', async () => { + const user = await mount() + await user.click(add()) + await waitFor(() => expect(refDialog()).toBeDefined()) + expect(written()?.view.reference).toEqual({ create: true }) + await save(user) + expect(field('Type')).toHaveFocus() + await user.selectOptions(field('Type'), 'book') + await user.type(field('Citation'), 'Nouvelle source') + await save(user) + await closed() + expect(entries()).toBe(1) + expect(doc().references).toHaveLength(4) + // Appended after the three, the sheet order untouched: nothing moved. + expect(within(tab()).getAllByRole('listitem')).toHaveLength(4) + expect( + within(tab()).getByText('Référence ajoutée : Nouvelle source'), + ).toBeVisible() + await waitFor(() => + expect(live()).toHaveTextContent('Référence ajoutée : Nouvelle source'), + ) + expect(add()).toHaveFocus() + }) + + it('« Afficher » shows the new tile open and focuses it', async () => { + const user = await mount() + await user.click(add()) + await waitFor(() => expect(refDialog()).toBeDefined()) + await user.selectOptions(field('Type'), 'book') + await user.type(field('Citation'), 'Nouvelle source') + await save(user) + await closed() + await user.click(within(tab()).getByRole('button', { name: 'Afficher' })) + expect(within(tab()).queryByText(/Référence ajoutée/)).toBeNull() + await waitFor(() => + expect(header('Nouvelle source')).toHaveAttribute( + 'aria-expanded', + 'true', + ), + ) + await waitFor(() => expect(header('Nouvelle source')).toHaveFocus()) + }) + + it('the entry becomes the reference’s own: Back, then Forward, reopens an edit, never a creation', async () => { + const user = await mount() + const first = written()!.id + await user.click(add()) + await waitFor(() => + expect(written()?.view.reference).toEqual({ create: true }), + ) + const entry = written()!.id + await user.selectOptions(field('Type'), 'book') + await user.type(field('Citation'), 'Nouvelle source') + await save(user) + await closed() + await waitFor(() => expect(written()?.id).toBe(first)) + await act(async () => navigate(1)) + await waitFor(() => expect(written()?.id).toBe(entry)) + const created = doc().references[3].id + expect(written()?.view.reference).toEqual({ edit: created }) + }) + + it('a dirty creation asks before it closes and writes nothing', async () => { + const user = await mount() + await user.click(add()) + await waitFor(() => expect(refDialog()).toBeDefined()) + await user.type(field('Citation'), 'x') + await user.keyboard('{Escape}') + await user.click(inRef().getByRole('button', { name: 'Abandonner' })) + await closed() + expect(entries()).toBe(0) + await waitFor(() => expect(add()).toHaveFocus()) + }) +}) + +describe('history', () => { + it('Back closes the dialog and the opener holds the focus; Forward reopens it', async () => { + const user = await mount() + await modify(user, 'Barone') + const opener = within(header('Barone').closest('li')!).getByRole('button', { + name: 'Modifier', + }) + await back() + await closed() + await waitFor(() => expect(opener).toHaveFocus()) + await act(async () => navigate(1)) + await waitFor(() => expect(refDialog()).toBeDefined()) + expect(field('Citation')).toHaveValue('Barone, Ostéologie') + }) + + it('a dirty dialog keeps its draft when Back asks, then Abandonner pops once', async () => { + const user = await mount() + await modify(user, 'Barone') + await user.type(field('DOI'), '10.1/x') + await back() + expect(inRef().getByText('Abandonner les modifications ?')).toBeVisible() + fireEvent.click( + inRef().getByRole('button', { name: 'Continuer la saisie' }), + ) + expect(field('DOI')).toHaveValue('10.1/x') + fireEvent.click(inRef().getByRole('button', { name: 'Annuler' })) + await user.click(inRef().getByRole('button', { name: 'Abandonner' })) + await closed() + await waitFor(() => expect(written()?.view.reference).toBeNull()) + expect(entries()).toBe(0) + }, 20_000) + + it('a reload keeps the tab but never reopens the form', async () => { + const user = await mount() + await modify(user, 'Barone') + const entry = written()! + cleanup() + serverHas(sheetText(), 3) + mountDraft({ + probe, + entries: [{ pathname: location.pathname, state: { [ENTRY_KEY]: entry } }], + }) + await screen.findByRole('heading', { + level: 1, + name: 'Brouillon, version 4', + }) + await waitFor(() => expect(written()?.view.reference).toBeNull()) + expect(written()?.view.tab).toBe('references') + expect(refDialog()).toBeUndefined() + }) +}) + +describe('the finding filter', () => { + const chip = () => screen.getByTestId('editor-references-filter') + + /** Node A's dialog, its sheet, then « Tout afficher »: the tab filtered by Node A. */ + async function filtered(user: User) { + await user.click(screen.getByRole('tab', { name: 'Constats' })) + await openFinding(user, /Node A/) + await user.click(screen.getByRole('button', { name: '2 références' })) + await user.click( + await screen.findByRole('button', { + name: "Tout afficher dans l'onglet Références", + }), + ) + await waitFor(() => expect(written()?.view.tab).toBe('references')) + } + + it('« Tout afficher » lists the finding’s references, counts within the filter, no reorder', async () => { + const user = await mount() + await filtered(user) + expect(written()?.view.referenceFilter).toMatchObject({ kind: 'finding' }) + expect(chip()).toHaveTextContent('Références du constat : Node A') + expect(within(tab()).getAllByRole('listitem')).toHaveLength(2) + expect(within(tab()).getByText('2 références')).toBeVisible() + await user.click(header('Barone')) + expect( + within(tab()).queryByRole('button', { name: 'Descendre' }), + ).toBeNull() + await user.type( + within(tab()).getByRole('searchbox', { + name: 'Rechercher une référence', + }), + 'Code', + ) + expect(within(tab()).getByText('0 référence sur 2')).toBeVisible() + expect(screen.getByTestId('editor-references-no-result')).toBeVisible() + }) + + it('the × removes the filter by replace; the search text is never in the entry', async () => { + const user = await mount() + await filtered(user) + const id = written()!.id + await user.type( + within(tab()).getByRole('searchbox', { + name: 'Rechercher une référence', + }), + 'Code', + ) + await user.click( + within(chip()).getByRole('button', { + name: 'Retirer le filtre du constat Node A', + }), + ) + await waitFor(() => expect(written()?.view.referenceFilter).toBeNull()) + expect(written()?.id).toBe(id) + expect(JSON.stringify(location.state)).not.toContain('Code') + expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(0) + }) + + it('« Revenir au constat » pops to the finding with its sheet open when the entry below shows it', async () => { + const user = await mount() + await filtered(user) + await user.click(screen.getByRole('button', { name: 'Revenir au constat' })) + await waitFor(() => expect(dialogs()).toHaveLength(2)) + expect(written()?.view.finding).toMatchObject({ citations: true }) + expect(written()?.view.referenceFilter).toBeNull() + }) + + it('a finding that vanishes clears the filter and says so', async () => { + const user = await mount() + await filtered(user) + act(() => { + store.getState().commit({ + op: 'remove', + key: { + kind: 'finding', + zone_id: 'zone-a', + path: ['fcat-a', 'fnode-a'], + }, + }) + }) + await waitFor(() => expect(written()?.view.referenceFilter).toBeNull()) + expect(screen.queryByTestId('editor-references-filter')).toBeNull() + await waitFor(() => + expect(live()).toHaveTextContent( + "Le constat n'existe plus : le filtre est retiré", + ), + ) + }) + + it('the finding dialog and the sheet come back by Back, the filtered tab by Forward', async () => { + const user = await mount() + await filtered(user) + await back() + await waitFor(() => expect(dialogs()).toHaveLength(2)) + expect(findingDialog()).not.toBeNull() + await act(async () => navigate(1)) + await waitFor(() => expect(dialogs()).toHaveLength(0)) + expect(chip()).toBeVisible() + }) +}) diff --git a/apps/app/tests/unit/editor-references-panel.test.tsx b/apps/app/tests/unit/editor-references-panel.test.tsx index 333db6be..ca8d796c 100644 --- a/apps/app/tests/unit/editor-references-panel.test.tsx +++ b/apps/app/tests/unit/editor-references-panel.test.tsx @@ -222,7 +222,7 @@ describe('opening', () => { } }) - it('has no search, no add control; field ids carry the panel prefix', async () => { + it('has no search, no add control; « Modifier » opens the reference dialog over the sheet', async () => { const user = await mount() await openFromFinding(user) expect(within(panel()).queryByRole('searchbox')).toBeNull() @@ -231,24 +231,23 @@ describe('opening', () => { ).toBeNull() await user.click(within(panel()).getByRole('button', { name: /^Barone/ })) await user.click(within(panel()).getByRole('button', { name: 'Modifier' })) + expect(document.querySelectorAll('dialog[open]')).toHaveLength(3) expect( - panel().querySelector('#panel-reference-0-ref-a-citation'), - ).not.toBeNull() - expect(document.querySelector('[id^="tab-reference-"]')).toBeNull() + screen.getByRole('dialog', { name: 'Modifier la référence' }), + ).toBeVisible() + expect(panel().querySelector('[id$="-citation"]')).toBeNull() }) it('ids stay unique with the Références tab mounted and the panel open (P14)', async () => { const user = await mount() await user.click(screen.getByRole('tab', { name: 'Références' })) await user.click(screen.getByRole('button', { name: /^Barone/ })) - await user.click(screen.getByRole('button', { name: 'Modifier' })) await openFromFinding(user) await user.click(within(panel()).getByRole('button', { name: /^Barone/ })) - await user.click(within(panel()).getByRole('button', { name: 'Modifier' })) const ids = [...document.querySelectorAll('[id]')].map((e) => e.id) expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([]) - expect(ids).toContain('tab-reference-0-ref-a-citation') - expect(ids).toContain('panel-reference-0-ref-a-citation') + expect(ids).toContain('tab-reference-0-ref-a-header') + expect(ids).toContain('panel-reference-0-ref-a-header') }) it('read-only: the tiles show, no Modifier, no Retirer, no field', async () => { @@ -348,7 +347,11 @@ describe.each(MODES)('closing, %s', (_label, reduced) => { await focusIs(() => within(tabPanel).getByRole('heading', { name: 'Références' }), ) - expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(3) + // Filtered by the finding the sheet belonged to: its two citations (R2F-6). + expect(within(tabPanel).getAllByRole('listitem')).toHaveLength(2) + expect( + within(tabPanel).getByText('Références du constat : Node A'), + ).toBeVisible() }) it('« Aller à » a citer from a panel tile closes the sheet and opens that finding in its dialog', async () => { @@ -581,90 +584,7 @@ describe('« Retirer de ce constat »', () => { }) }) -describe("a tile in edit when the panel closes (P22'')", () => { - async function edit(user: User) { - await openFromFinding(user) - await user.click(within(panel()).getByRole('button', { name: /^Barone/ })) - await user.click(within(panel()).getByRole('button', { name: 'Modifier' })) - return panel().querySelector( - '#panel-reference-0-ref-a-citation', - ) as HTMLTextAreaElement - } - - it('a valid draft is committed before the close, then the panel closes', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - await user.type(field, 'Neuf') - await user.click(closeButton()) - expect(doc().references[0].citation).toBe('Neuf') - await closed() - await focusIs(() => trigger()) - }) - - it('a refused draft cancels a user close: panel open, field focused, message shown', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - await user.click(closeButton()) - expect(hasPanel()).toBe(true) - expect(layer()).not.toHaveAttribute('inert') - expect(document.activeElement).toBe(field) - expect(within(panel()).getByRole('alert')).toBeVisible() - expect(doc().references[0].citation).toBe('Barone, Ostéologie') - }) - - it('a refused draft cancels « Tout afficher »', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - await user.click( - within(panel()).getByRole('button', { - name: "Tout afficher dans l'onglet Références", - }), - ) - expect(hasPanel()).toBe(true) - }) - - it('a forced close (finding vanished) drops a refused draft and says so', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - removeNodeA() - await closed() - await waitFor(() => expect(findingDialog()).toBeNull()) - await waitFor(() => - expect(live()).toHaveTextContent(/Saisie non appliquée : Citation/), - ) - expect(doc().references[0].citation).toBe('Barone, Ostéologie') - }) - - it('Escape in a field of the tile neither closes nor commits', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - await user.type(field, 'Neuf') - await user.keyboard('{Escape}') - expect(hasPanel()).toBe(true) - expect(doc().references[0].citation).toBe('Barone, Ostéologie') - }) - - it('a committed tile edit is one entry, reverted by Défaire once the sheet is closed', async () => { - const user = await mount() - const field = await edit(user) - await user.clear(field) - await user.type(field, 'Neuf') - fireEvent.blur(field) - expect(doc().references[0].citation).toBe('Neuf') - await user.click(closeButton()) - await closed() - act(() => void store.getState().undoStep()) - expect(doc().references[0].citation).toBe('Barone, Ostéologie') - }) -}) - const live = () => document.querySelector('p.sr-only[aria-live="polite"]') -const entries = () => store.getState().undo.length const undo = () => act(() => store.getState().undoStep()) const nodeKey: ElementKey = { kind: 'finding', @@ -689,44 +609,6 @@ function cite(ids: string[]) { }) } -describe('one user edit, one history entry in the panel (C1)', () => { - /** Opens Barone, enters edit and types a URL; the field keeps the focus. */ - async function typeUrl(user: User) { - await openFromFinding(user) - await user.click(within(panel()).getByRole('button', { name: /^Barone/ })) - await user.click(within(panel()).getByRole('button', { name: 'Modifier' })) - const url = panel().querySelector( - '#panel-reference-0-ref-a-url', - )! - await user.type(url, 'https://a.org/') - expect(document.activeElement).toBe(url) - return entries() - } - - it('✕ pressed with the field still focused (iPadOS) adds one entry', async () => { - const user = await mount() - const before = await typeUrl(user) - fireEvent.click(closeButton()) - await closed() - expect(entries() - before).toBe(1) - expect(doc().references[0].url).toBe('https://a.org/') - undo() - expect(doc().references[0].url).toBeNull() - }) - - it('a forced close (finding vanished) adds the edit once, besides the removal', async () => { - const user = await mount() - const before = await typeUrl(user) - act(() => { - store.getState().commit({ op: 'remove', key: nodeKey }) - }) - await closed() - expect(entries() - before).toBe(2) - await waitFor(() => expect(findingDialog()).toBeNull()) - expect(doc().references[0].url).toBe('https://a.org/') - }) -}) - describe('the panel review fixes', () => { it('the sheet is a modal dialog named by its title (M4: no announcement needed)', async () => { const user = await mount() diff --git a/apps/app/tests/unit/editor-references-tab.test.tsx b/apps/app/tests/unit/editor-references-tab.test.tsx index 6b0581a5..824f3654 100644 --- a/apps/app/tests/unit/editor-references-tab.test.tsx +++ b/apps/app/tests/unit/editor-references-tab.test.tsx @@ -1,16 +1,15 @@ /** R2.1 and R2.2: the Références tab, the library (search, order, counts, add, « Aller à »). */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - act, cleanup, fireEvent, render, screen, + waitFor, within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import ReferenceFacts from '@/components/editor/references/ReferenceFacts' -import ReferencesTab from '@/components/editor/tabs/ReferencesTab' import { useLocaleStore } from '@/state/localeStore' import { targetOfKey } from '@/editor/navigation' import { edit, insert } from '../helpers/editorFixtures' @@ -22,6 +21,7 @@ import { store, } from '../helpers/editorHarness' import { mountDraft, setWidth } from '../helpers/editorRoute' +import ReferencesHost from '../helpers/referencesHost' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@faunosteo/supabase', async (orig) => ({ @@ -188,19 +188,19 @@ describe('the Références tab', () => { ).toBeNull() }) - it('Ctrl+Z reverts a reference edit', async () => { + it('Ctrl+Z reverts a reference edit made in the dialog, once it is closed', async () => { const user = await mount() - await user.click(header('Barone')) - await user.click( - within(tabPanel()).getByRole('button', { name: 'Modifier' }), - ) - const field = within(tabPanel()).getByLabelText('Citation', { - selector: '#tab-reference-0-ref-a-citation', - }) + await startEdit(user, 'Barone') + const dialog = screen.getByRole('dialog', { name: 'Modifier la référence' }) + const field = within(dialog).getByLabelText('Citation') await user.clear(field) await user.type(field, 'Neuf') - fireEvent.blur(field) - const doc = () => JSON.parse(store.getState().documentText) + await user.click( + within(dialog).getByRole('button', { name: 'Enregistrer' }), + ) + await waitFor(() => + expect(document.querySelector('dialog[open]')).toBeNull(), + ) expect(doc().references[0].citation).toBe('Neuf') fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) expect(doc().references[0].citation).toBe('Barone, Ostéologie') @@ -228,13 +228,7 @@ describe('« Aller à » a reference', () => { serverHas(sheetText(), 3) await openReady({ text: sheetText() }) const user = userEvent.setup() - const view = render( - , - ) + const view = render() const box = screen.getByRole('searchbox', { name: 'Rechercher une référence', }) @@ -244,14 +238,7 @@ describe('« Aller à » a reference', () => { target: targetOfKey({ kind: 'reference', id: 'ref-a' }), serial: 1, } - view.rerender( - , - ) + view.rerender() expect(box).toHaveValue('') expect(document.querySelectorAll('button[aria-controls]')).toHaveLength(3) expect(document.activeElement?.getAttribute('data-focus-key')).toContain( @@ -265,45 +252,17 @@ describe('the reset signal', () => { it('empties the search once per bump and leaves other state alone', async () => { await openReady({ text: sheetText() }) const user = userEvent.setup() - const view = render( - , - ) + const view = render() const box = screen.getByRole('searchbox', { name: 'Rechercher une référence', }) await user.type(box, 'Code') - view.rerender( - , - ) + view.rerender() expect(box).toHaveValue('Code') - view.rerender( - , - ) + view.rerender() expect(box).toHaveValue('') await user.type(box, 'a') - view.rerender( - , - ) + view.rerender() expect(box).toHaveValue('a') }) }) @@ -311,182 +270,50 @@ describe('the reset signal', () => { describe('adding a reference', () => { const addButton = () => within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' }) - async function add(user: User) { - await user.click(addButton()) - const byId = (id: string) => tabPanel().querySelector(id)! - await user.selectOptions(byId('#tab-reference-new-type'), 'book') - await user.type(byId('#tab-reference-new-citation'), 'Nouvelle source') - await user.click( - within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }), - ) - } - it('resets the search, shows the new tile open and focuses its button', async () => { - const user = await mount() - await user.type(search(), 'Barone') - expect(cards()).toHaveLength(1) - await add(user) - expect(search()).toHaveValue('') - expect(cards()).toHaveLength(4) - expect(header('Nouvelle source')).toHaveAttribute('aria-expanded', 'true') - expect(document.activeElement).toBe(header('Nouvelle source')) - expect(within(tabPanel()).queryByLabelText('Citation')).toBeNull() - }) - - it('opens a draft tile with the citation focused, and a refused add keeps it', async () => { + it('opens the creation dialog with the type to choose, the search untouched', async () => { const user = await mount() await user.type(search(), 'Barone') await user.click(addButton()) - expect(search()).toHaveValue('') - expect(document.activeElement).toBe( - tabPanel().querySelector('#tab-reference-new-citation'), - ) - await user.click( - within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }), - ) - expect(within(tabPanel()).getByRole('alert')).toHaveTextContent( - 'Choisissez un type', - ) + const dialog = screen.getByRole('dialog', { name: 'Nouvelle référence' }) + expect(within(dialog).getByLabelText('Type')).toHaveValue('') + expect(search()).toHaveValue('Barone') expect(doc().references).toHaveLength(3) }) -}) -describe("« Annuler l'ajout » (C2)", () => { - const addButton = () => - within(tabPanel()).getByRole('button', { name: 'Ajouter une référence' }) - const field = (id: string) => - tabPanel().querySelector(`#tab-reference-new-${id}`)! - const draftTile = () => - within(tabPanel()).queryByLabelText('Nouvelle référence') - const cancelButton = () => - within(tabPanel()).getByRole('button', { name: "Annuler l'ajout" }) - const history = () => ({ - undo: store.getState().undo.length, - redo: store.getState().redo.length, - }) - const refs = () => JSON.parse(store.getState().documentText).references - - /** One real change undone, so a redo is pending; then the draft is opened. */ - async function openWithPendingRedo() { + it('creates the reference in one modification and leaves the list where it was', async () => { const user = await mount() - await startEditAndType(user) - act(() => store.getState().undoStep()) + await user.type(search(), 'Barone') await user.click(addButton()) - return user - } - async function startEditAndType(user: User) { - await user.click(header('Barone, Ostéologie')) - const item = header('Barone, Ostéologie').closest('li')! - await user.click(within(item).getByRole('button', { name: 'Modifier' })) - await user.type(within(item).getByLabelText('DOI'), '10.1/x') - await user.click(within(item).getByRole('button', { name: 'Terminer' })) - } - function expectCancelled(before: { refs: unknown; history: object }) { - expect(draftTile()).toBeNull() - expect(refs()).toEqual(before.refs) - expect(history()).toEqual(before.history) - expect(document.activeElement).toBe(addButton()) - } - const snapshot = () => ({ refs: refs(), history: history() }) - - it('the button removes the tile, writes nothing, keeps a pending redo', async () => { - const user = await openWithPendingRedo() - expect(history().redo).toBe(1) - const before = snapshot() - await user.click(cancelButton()) - expectCancelled(before) - }) - - it('Escape on the type select and on a button does the same', async () => { - const user = await openWithPendingRedo() - const before = snapshot() - await user.type(field('citation'), 'Brouillon') - fireEvent.keyDown(field('type'), { key: 'Escape' }) - expectCancelled(before) - await user.click(addButton()) - await user.type(field('citation'), 'Brouillon') - fireEvent.keyDown(cancelButton(), { key: 'Escape' }) - expectCancelled(before) - }) - - it('Escape in a field cancels while the form is pristine, not once typed', async () => { - const user = await openWithPendingRedo() - const before = snapshot() - fireEvent.keyDown(field('citation'), { key: 'Escape' }) - expectCancelled(before) - await user.click(addButton()) - await user.type(field('citation'), 'Brouillon') - fireEvent.keyDown(field('citation'), { key: 'Escape' }) - expect(draftTile()).not.toBeNull() - expect(field('citation')).toHaveValue('Brouillon') - }) - - it('Escape while composing, or already handled, does nothing', async () => { - const user = await mount() - await user.click(addButton()) - fireEvent.keyDown(field('type'), { key: 'Escape', isComposing: true }) - fireEvent.keyDown(field('type'), { key: 'Escape', keyCode: 229 }) - expect(draftTile()).not.toBeNull() - const handled = new KeyboardEvent('keydown', { - key: 'Escape', - bubbles: true, - cancelable: true, - }) - handled.preventDefault() - act(() => void field('type').dispatchEvent(handled)) - expect(draftTile()).not.toBeNull() - }) - - it('Escape that cancels is marked handled', async () => { - const user = await mount() - await user.click(addButton()) - const event = new KeyboardEvent('keydown', { - key: 'Escape', - bubbles: true, - cancelable: true, - }) - act(() => void field('type').dispatchEvent(event)) - expect(event.defaultPrevented).toBe(true) - }) - - it('goes with its refusal message, and a new add starts from an empty form', async () => { - const user = await mount() - await user.click(addButton()) - await user.type(field('citation'), 'Brouillon') - await user.click( - within(tabPanel()).getByRole('button', { name: 'Ajouter la référence' }), + const dialog = screen.getByRole('dialog', { name: 'Nouvelle référence' }) + await user.selectOptions(within(dialog).getByLabelText('Type'), 'book') + await user.type( + within(dialog).getByLabelText('Citation'), + 'Nouvelle source', ) - expect(within(tabPanel()).getByRole('alert')).toBeInTheDocument() - await user.click(cancelButton()) - expect(within(tabPanel()).queryByRole('alert')).toBeNull() - await user.click(addButton()) - expect(field('citation')).toHaveValue('') - expect(field('type')).toHaveValue('') - expect(within(tabPanel()).queryByRole('alert')).toBeNull() - }) - - it('« Défaire » after a cancel undoes the previous real change', async () => { - const user = await mount() - await startEditAndType(user) - expect(history().undo).toBe(1) - await user.click(addButton()) - await user.click(cancelButton()) - expect(history().undo).toBe(1) - act(() => store.getState().undoStep()) - expect(history()).toEqual({ undo: 0, redo: 1 }) - expect(refs()[0].doi).toBeNull() + await user.click( + within(dialog).getByRole('button', { name: 'Ajouter la référence' }), + ) + await waitFor(() => + expect(document.querySelector('dialog[open]')).toBeNull(), + ) + expect(store.getState().undo.length).toBe(1) + expect(doc().references).toHaveLength(4) + expect(search()).toHaveValue('Barone') + expect(cards()).toHaveLength(1) + expect(document.activeElement).toBe(addButton()) }) }) const tile = (citation: string) => header(citation).closest('li')! const doc = () => JSON.parse(store.getState().documentText) -/** Opens the tile and enters edit; answers the tile, whose header then names the edit. */ +/** Opens the tile and its « Modifier » dialog. */ async function startEdit(user: User, citation: string) { - const item = tile(citation) await user.click(header(citation)) - await user.click(within(item).getByRole('button', { name: 'Modifier' })) - return item + await user.click( + within(tile(citation)).getByRole('button', { name: 'Modifier' }), + ) } describe('the tile disclosure', () => { @@ -593,198 +420,6 @@ describe('an open tile', () => { }) }) -describe('a tile in edit', () => { - it('shows the fields, the citers and « Terminer », and hides the other actions', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - expect(view.getByText('Modifier la référence')).toBeInTheDocument() - expect(document.activeElement).toBe(view.getByLabelText('Citation')) - expect(view.getByText('Citée 2 fois, par :')).toBeInTheDocument() - expect(view.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2) - for (const name of ['Modifier', 'Supprimer', 'Monter', 'Descendre']) { - expect(view.queryByRole('button', { name })).toBeNull() - } - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(view.queryByLabelText('Citation')).toBeNull() - expect(document.activeElement).toBe( - item.querySelector('button[aria-expanded]'), - ) - expect(view.getByRole('button', { name: 'Modifier' })).toBeInTheDocument() - }) - - it('keeps edit and focuses the field when the URL is refused', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - const url = view.getByLabelText('Adresse web (URL)') - await user.type(url, 'exemple.org') - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument() - expect(document.activeElement).toBe(url) - expect(view.getByRole('alert')).toBeInTheDocument() - expect(doc().references[0].url).toBeNull() - }) - - it('keeps edit and focuses the citation when it is left blank', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - const citation = view.getByLabelText('Citation') - await user.clear(citation) - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument() - expect(document.activeElement).toBe(citation) - expect(view.getByText('Ce champ est obligatoire.')).toBeInTheDocument() - expect(doc().references[0].citation).toBe('Barone, Ostéologie') - }) - - it('a refused field A, then B applied, then « Terminer » keeps edit', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - const url = view.getByLabelText('Adresse web (URL)') - await user.type(url, 'exemple.org') - await user.tab() - await user.type(view.getByLabelText('DOI'), '10.1000/xyz') - await user.tab() - expect(doc().references[0].doi).toBe('10.1000/xyz') - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument() - expect(document.activeElement).toBe(url) - }) - - it('a press on « Terminer » keeps the focus in the field (no refusal shifts it), the click keeps edit', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - const url = view.getByLabelText('Adresse web (URL)') - await user.type(url, 'exemple.org') - const done = view.getByRole('button', { name: 'Terminer' }) - await user.pointer({ keys: '[MouseLeft>]', target: done }) - expect(view.queryByRole('alert')).toBeNull() - expect(document.activeElement).toBe(url) - await user.pointer({ keys: '[/MouseLeft]', target: done }) - expect(view.getByRole('alert')).toBeInTheDocument() - expect(document.activeElement).toBe(url) - expect(view.getByRole('button', { name: 'Terminer' })).toBeInTheDocument() - }) - - it('applies every pending field on « Terminer », as one history entry each', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const view = within(item) - const before = store.getState().undo.length - await user.type(view.getByLabelText('DOI'), '10.1000/xyz') - await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/') - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(store.getState().undo.length - before).toBe(2) - expect(doc().references[0]).toMatchObject({ - doi: '10.1000/xyz', - url: 'https://a.org/', - }) - expect(view.queryByLabelText('Citation')).toBeNull() - }) - - it('switching to another tile leaves edit only when the fields apply', async () => { - const user = await mount() - const barone = await startEdit(user, 'Barone') - const denoix = tile('Denoix') - const url = within(barone).getByLabelText('Adresse web (URL)') - await user.type(url, 'exemple.org') - await user.click(header('Denoix')) - const modify = () => - within(denoix).getByRole('button', { name: 'Modifier' }) - await user.click(modify()) - expect(within(barone).getByLabelText('Citation')).toBeInTheDocument() - expect(within(denoix).queryByLabelText('Citation')).toBeNull() - await user.clear(url) - await user.click(modify()) - expect(within(barone).queryByLabelText('Citation')).toBeNull() - expect(within(denoix).getByLabelText('Citation')).toBeInTheDocument() - }) - - it('survives a tab change with the typed text', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - await user.type(within(item).getByLabelText('DOI'), '10.1000/kept') - await user.click(screen.getByRole('tab', { name: 'Constats' })) - await user.click(screen.getByRole('tab', { name: 'Références' })) - const view = within(item) - expect(view.getByLabelText('DOI')).toHaveValue('10.1000/kept') - expect(doc().references[0].doi).toBe('10.1000/kept') - }) -}) - -describe('the disclosure button in edit (M7)', () => { - it('is named for what it does, and pressing it ends the edit', async () => { - const user = await mount() - const item = await startEdit(user, 'Barone') - const button = within(item).getByRole('button', { - name: /^Terminer\. Modifier la référence/, - }) - expect(button).toHaveAttribute('aria-expanded', 'true') - await user.click(button) - expect(within(item).queryByLabelText('Citation')).toBeNull() - }) -}) - -describe('one user edit, one history entry (C1)', () => { - const entries = () => store.getState().undo.length - const undo = () => act(() => store.getState().undoStep()) - - it('« Terminer » after one typed field adds one entry, the first « Défaire » undoes it', async () => { - const user = await mount() - const view = within(await startEdit(user, 'Barone')) - const before = entries() - await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/') - await user.click(view.getByRole('button', { name: 'Terminer' })) - expect(entries() - before).toBe(1) - expect(doc().references[0].url).toBe('https://a.org/') - undo() - expect(doc().references[0].url).toBeNull() - }) - - it('« Terminer » pressed with the field still focused (no pointer) adds one entry', async () => { - const user = await mount() - const view = within(await startEdit(user, 'Barone')) - const before = entries() - const url = view.getByLabelText('Adresse web (URL)') - await user.type(url, 'https://a.org/') - expect(document.activeElement).toBe(url) - fireEvent.click(view.getByRole('button', { name: 'Terminer' })) - expect(entries() - before).toBe(1) - undo() - expect(doc().references[0].url).toBeNull() - }) - - it('a tab switch with the field still focused adds one entry', async () => { - const user = await mount() - const view = within(await startEdit(user, 'Barone')) - const before = entries() - await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/') - fireEvent.click(screen.getByRole('tab', { name: 'Constats' })) - expect(entries() - before).toBe(1) - undo() - expect(doc().references[0].url).toBeNull() - }) - - it('a blur after the field was applied adds nothing; a changed text adds one more', async () => { - const user = await mount() - const view = within(await startEdit(user, 'Barone')) - const before = entries() - const url = view.getByLabelText('Adresse web (URL)') - await user.type(url, 'https://a.org/') - await user.tab() - await user.click(url) - await user.tab() - expect(entries() - before).toBe(1) - await user.type(url, 'x') - await user.tab() - expect(entries() - before).toBe(2) - }) -}) - describe('read-only tiles', () => { it('keep DOI, URL and « Aller à », and offer no edit control', async () => { const user = await mount(800) @@ -805,9 +440,8 @@ describe('read-only tiles', () => { }) describe('reopening the editor', () => { - it('starts with every tile closed and none in edit', async () => { + it('starts with every tile closed', async () => { const user = await mount() - await startEdit(user, 'Barone') await user.click(header('Denoix')) cleanup() await mount() @@ -815,10 +449,5 @@ describe('reopening the editor', () => { expanded: true, }) expect(opened).toHaveLength(0) - expect( - within(tabPanel()).queryByLabelText('Citation', { - selector: '#tab-reference-0-ref-a-citation', - }), - ).toBeNull() }) }) diff --git a/apps/app/tests/unit/editor-references-view.test.tsx b/apps/app/tests/unit/editor-references-view.test.tsx index 8238c9f1..fb1a5591 100644 --- a/apps/app/tests/unit/editor-references-view.test.tsx +++ b/apps/app/tests/unit/editor-references-view.test.tsx @@ -1,10 +1,15 @@ -/** R2.3: search, sort, count, no-result notice, A1, the add flow, the pin and the reset. */ +/** R2.3: search, sort, count, no-result notice, A1, the pin (the dialog's tile) and the reset. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, render, screen, within } from '@testing-library/react' +import { + act, + cleanup, + render, + screen, + waitFor, + within, +} from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { ReferenceType } from '@faunosteo/core-wasm/types' -import ReferencesTab from '@/components/editor/tabs/ReferencesTab' -import { AnnounceContext } from '@/editor/focusRequest' import { targetOfKey } from '@/editor/navigation' import { useLocaleStore } from '@/state/localeStore' import { edit, insert } from '../helpers/editorFixtures' @@ -14,6 +19,7 @@ import { resetStore, store, } from '../helpers/editorHarness' +import ReferencesHost from '../helpers/referencesHost' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@faunosteo/supabase', async (orig) => ({ @@ -87,12 +93,7 @@ function sortText(): string { type User = ReturnType const doc = () => JSON.parse(store.getState().documentText) const lib = (readOnly = false, extra = {}) => ( - + ) async function mount(readOnly = false) { await openReady({ text: sortText() }) @@ -183,16 +184,6 @@ describe('the count line', () => { }) }) -describe('the count with a pinned tile', () => { - it('counts the matches only, the pinned tile stays shown', async () => { - const { user } = await mount() - await startEdit(user, 'r1') - await user.type(search(), 'alpha') - expect(order()).toEqual(['r1', 'r5']) - expect(screen.getByText('1 référence sur 5')).toBeInTheDocument() - }) -}) - describe('clearing the search', () => { it('the button appears with a query, empties it and refocuses the field', async () => { const { user } = await mount() @@ -303,96 +294,72 @@ describe('the move buttons (A1)', () => { }) }) -/** Opens the tile of `id` and enters edit. */ +/** Opens the tile of `id` and its « Modifier » dialog. */ async function startEdit(user: User, id: string) { await user.click(header(id)) const item = header(id).closest('li')! await user.click(within(item).getByRole('button', { name: 'Modifier' })) - return item + return screen.getByRole('dialog', { name: 'Modifier la référence' }) } -describe('the tile in edit is pinned (P23)', () => { - it('keeps its index when the sort changes', async () => { +/** Types a new citation in the open dialog and saves it. */ +async function saveCitation(user: User, text: string) { + const dialog = screen.getByRole('dialog', { name: 'Modifier la référence' }) + const citation = within(dialog).getByLabelText('Citation') + await user.clear(citation) + await user.type(citation, text) + await user.click(within(dialog).getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull()) +} + +const cancelDialog = async (user: User) => { + await user.click(screen.getByRole('button', { name: 'Annuler' })) + await waitFor(() => expect(document.querySelector('dialog[open]')).toBeNull()) +} + +describe('the tile the dialog edits is pinned (P23)', () => { + it('keeps its index when the sort changes after the dialog closes', async () => { const { user } = await mount() await user.selectOptions(sortBox(), 'citation') await startEdit(user, 'r1') + await cancelDialog(user) expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) await user.selectOptions(sortBox(), 'count') - expect(order()).toEqual(['r2', 'r5', 'r3', 'r4', 'r1']) - await user.selectOptions(sortBox(), 'sheet') - expect(order()).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']) + expect(order()).toEqual(['r2', 'r1', 'r5', 'r3', 'r4']) }) - it('starts in sheet order and holds its place under a later sort', async () => { + it('stays shown under a search it stops matching, until the next search change (I1)', async () => { const { user } = await mount() - await startEdit(user, 'r3') - await user.selectOptions(sortBox(), 'citation') - expect(order()).toEqual(['r5', 'r4', 'r3', 'r2', 'r1']) - }) - - it('stays shown under a search that does not match it, also after « Terminer », until the next search change (I1)', async () => { - const { user } = await mount() - const item = await startEdit(user, 'r1') await user.type(search(), 'alpha') - expect(order()).toEqual(['r1', 'r5']) - expect(within(item).getByLabelText('Citation')).toBeInTheDocument() - await user.click(within(item).getByRole('button', { name: 'Terminer' })) - expect(order()).toEqual(['r1', 'r5']) - expect(document.activeElement).toBe(header('r1')) + await startEdit(user, 'r5') + await saveCitation(user, 'Autre titre') + expect(order()).toEqual(['r5']) await user.clear(search()) await user.type(search(), 'alpha') - expect(order()).toEqual(['r5']) + expect(order()).toEqual([]) }) - it('keeps the tile shown and focused when its edit stops matching the search (I1)', async () => { + it('keeps the tile shown and the opener focused when its edit stops matching (I1)', async () => { const { user } = await mount() await user.type(search(), 'zèbre') - const item = await startEdit(user, 'r1') - const citation = within(item).getByLabelText('Citation') - await user.clear(citation) - await user.type(citation, 'Autre titre') - await user.click(within(item).getByRole('button', { name: 'Terminer' })) + await startEdit(user, 'r1') + await saveCitation(user, 'Autre titre') expect(order()).toEqual(['r1', 'r2']) - expect(document.activeElement).toBe(header('r1')) + expect(search()).toHaveValue('zèbre') + expect(document.activeElement).toBe( + within(header('r1').closest('li')!).getByRole('button', { + name: 'Modifier', + }), + ) }) - it('keeps the tile in edit at its index across a sort change made while read-only (M3)', async () => { + it('keeps its index across a sort made in read-only after the dialog', async () => { const { user, view } = await mount() await user.selectOptions(sortBox(), 'citation') await startEdit(user, 'r3') + await cancelDialog(user) + view.rerender(lib(true)) expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1']) - view.rerender(lib(true)) - await user.selectOptions(sortBox(), 'count') - view.rerender(lib(false)) - expect(order()).toEqual(['r2', 'r3', 'r1', 'r5', 'r4']) - }) - - it('stays pinned in read-only: the read view of the tile, still shown after a search', async () => { - const { user, view } = await mount() - await startEdit(user, 'r1') - await user.selectOptions(sortBox(), 'citation') - view.rerender(lib(true)) - expect(screen.queryByLabelText('Citation')).toBeNull() - expect(order()).toEqual(['r1', 'r5', 'r3', 'r4', 'r2']) - await user.type(search(), 'alpha') - expect(order()).toEqual(['r1', 'r5']) - view.rerender(lib(false)) - expect(order()).toEqual(['r1', 'r5']) - expect( - within(header('r1').closest('li')!).getByLabelText('Citation'), - ).toBeVisible() - }) - - it('a read-only toggle ends the edit state and collapses the tile', async () => { - const { user, view } = await mount() - await startEdit(user, 'r1') - view.rerender(lib(true)) - expect(header('r1')).toHaveAttribute('aria-expanded', 'true') - await user.click(header('r1')) - expect(header('r1')).toHaveAttribute('aria-expanded', 'false') - view.rerender(lib(false)) - expect(header('r1')).toHaveAttribute('aria-expanded', 'false') - expect(screen.queryByLabelText('Citation')).toBeNull() }) }) @@ -402,194 +369,74 @@ describe('the tile outside the search (C3)', () => { const lineOf = (id: string) => within(header(id).closest('li')!).queryByText(line) - async function editedOut(user: User) { - await user.type(search(), 'zèbre') - const item = await startEdit(user, 'r1') - const citation = within(item).getByLabelText('Citation') - await user.clear(citation) - await user.type(citation, 'Autre titre') - return item - } - - it('after « Terminer » shows the tile with its line, no notice, focus on its header', async () => { + it('after the save shows the tile with its line and no notice', async () => { const { user } = await mount() - await user.clear(search()) await user.type(search(), 'alpha') - const item = await startEdit(user, 'r5') - await user.clear(within(item).getByLabelText('Citation')) - await user.type(within(item).getByLabelText('Citation'), 'Autre titre') - await user.click(within(item).getByRole('button', { name: 'Terminer' })) + await startEdit(user, 'r5') + await saveCitation(user, 'Autre titre') expect(order()).toEqual(['r5']) expect(lineOf('r5')).toBeVisible() expect(notice()).toBeNull() expect(screen.getByText('0 référence sur 5')).toBeInTheDocument() - expect(document.activeElement).toBe(header('r5')) - expect(header('r5').getAttribute('aria-describedby')).toBe(lineOf('r5')!.id) expect(header('r5')).toHaveAccessibleDescription(line) - expect( - screen.getByRole('button', { name: 'Effacer la recherche' }), - ).toBeVisible() }) it('the next search change drops the tile and shows the notice', async () => { const { user } = await mount() await user.type(search(), 'alpha') - const item = await startEdit(user, 'r5') - await user.clear(within(item).getByLabelText('Citation')) - await user.type(within(item).getByLabelText('Citation'), 'Autre titre') - await user.click(within(item).getByRole('button', { name: 'Terminer' })) + await startEdit(user, 'r5') + await saveCitation(user, 'Autre titre') await user.type(search(), 'x') expect(order()).toEqual([]) expect(notice()).not.toBeNull() }) - it('a tile in edit that does not match carries the line', async () => { - const { user } = await mount() - const item = await editedOut(user) - expect(lineOf('r1')).toBeNull() - await user.type(search(), 'x') - expect(within(item).getByLabelText('Citation')).toBeVisible() - expect(lineOf('r1')).toBeVisible() - }) - it('a matching pinned tile has no line', async () => { const { user } = await mount() + await user.type(search(), 'zebre') await startEdit(user, 'r1') - await user.type(search(), 'alpha') - expect(lineOf('r1')).toBeVisible() - expect(lineOf('r5')).toBeNull() - await user.clear(search()) + await cancelDialog(user) expect(lineOf('r1')).toBeNull() }) it('a read-only flip keeps the tile and its line', async () => { const { user, view } = await mount() - await startEdit(user, 'r1') await user.type(search(), 'alpha') + await startEdit(user, 'r5') + await saveCitation(user, 'Autre titre') view.rerender(lib(true)) - expect(order()).toEqual(['r1', 'r5']) - expect(lineOf('r1')).toBeVisible() + expect(order()).toEqual(['r5']) + expect(lineOf('r5')).toBeVisible() expect(notice()).toBeNull() }) - - it('an open draft tile does not hide the notice for a search matching nothing', async () => { - const { user } = await mount() - await user.click( - screen.getByRole('button', { name: 'Ajouter une référence' }), - ) - await user.type(search(), 'radiographie') - expect(order()).toEqual([]) - expect(notice()).not.toBeNull() - }) }) -describe('adding (P24)', () => { - const add = () => - screen.getByRole('button', { name: 'Ajouter une référence' }) - const draftCitation = () => - document.querySelector('#tab-reference-new-citation') - - it('resets search and sort, appends a draft tile in edit, citation focused', async () => { +describe('after a dialog closes, the view is unchanged (R2F-5)', () => { + it('keeps scroll position inputs: search, sort, open tiles', async () => { const { user } = await mount() - await user.selectOptions(sortBox(), 'count') + await user.click(header('r2')) + await user.selectOptions(sortBox(), 'citation') await user.type(search(), 'e') - await user.click(add()) - expect(search()).toHaveValue('') - expect(sortBox()).toHaveValue('sheet') - expect(order()).toHaveLength(5) - expect(document.activeElement).toBe(draftCitation()) - expect(screen.getByLabelText('Type')).toHaveValue('') - expect( - within(screen.getByLabelText('Type')).getByText('Choisir…'), - ).toBeInTheDocument() - expect( - screen.getByText('Type et citation obligatoires.'), - ).toBeInTheDocument() - expect(snapshot().history).toBe(0) - }) - - it('creates the reference in one modification; the tile stays open, out of edit, focused', async () => { - const { user } = await mount() - await user.click(add()) - await user.selectOptions(screen.getByLabelText('Type'), 'book') - await user.type(draftCitation()!, 'Nouvelle source') - await user.click( - screen.getByRole('button', { name: 'Ajouter la référence' }), - ) - expect(store.getState().undo.length).toBe(1) - expect(doc().references).toHaveLength(6) - const id = doc().references[5].id - expect(order()).toHaveLength(6) - expect(header(id)).toHaveAttribute('aria-expanded', 'true') - expect(document.activeElement).toBe(header(id)) - expect(draftCitation()).toBeNull() - expect( - within(header(id).closest('li')!).getByRole('button', { + await startEdit(user, 'r3') + await cancelDialog(user) + expect(search()).toHaveValue('e') + expect(sortBox()).toHaveValue('citation') + expect(header('r2')).toHaveAttribute('aria-expanded', 'true') + expect(header('r3')).toHaveAttribute('aria-expanded', 'true') + expect(document.activeElement).toBe( + within(header('r3').closest('li')!).getByRole('button', { name: 'Modifier', }), - ).toBeInTheDocument() - }) - - it('a search typed after « Ajouter une référence » is cleared by the add, the new tile takes the focus (I1)', async () => { - const { user } = await mount() - await user.click(add()) - await user.selectOptions(screen.getByLabelText('Type'), 'book') - await user.type(draftCitation()!, 'Nouvelle source') - await user.type(search(), 'alpha') - expect(order()).toEqual(['r5']) - await user.click( - screen.getByRole('button', { name: 'Ajouter la référence' }), ) - const id = doc().references[5].id - expect(search()).toHaveValue('') - expect(order()).toHaveLength(6) - expect(document.activeElement).toBe(header(id)) - }) - - it('a second click on the button takes the focus back to the citation', async () => { - const { user } = await mount() - await user.click(add()) - await user.click(search()) - await user.click(add()) - expect(document.activeElement).toBe(draftCitation()) - expect( - document.querySelectorAll('#tab-reference-new-citation'), - ).toHaveLength(1) - }) - - it('leaves the tile in edit first: a refused field cancels the add (P22)', async () => { - const { user } = await mount() - const item = await startEdit(user, 'r1') - const url = within(item).getByLabelText('Adresse web (URL)') - await user.type(url, 'exemple.org') - await user.click(add()) - expect(draftCitation()).toBeNull() - expect(document.activeElement).toBe(url) - await user.clear(url) - await user.click(add()) - expect(draftCitation()).not.toBeNull() - expect(within(item).queryByLabelText('Citation')).toBeNull() - }) - - it('keeps the draft hidden in read-only and resumes it when editable again', async () => { - const { user, view } = await mount() - await user.click(add()) - await user.type(draftCitation()!, 'En cours') - view.rerender(lib(true)) - expect(draftCitation()).not.toBeVisible() - view.rerender(lib(false)) - expect(draftCitation()).toBeVisible() - expect(draftCitation()).toHaveValue('En cours') }) }) describe('the reset path (« Tout afficher »)', () => { - it('empties the search and keeps the sort, keeping open tiles and the tile in edit (R2F-4)', async () => { + it('empties the search and keeps the sort, keeping open tiles (R2F-4)', async () => { await openReady({ text: sortText() }) const user = userEvent.setup() const view = render(lib(false, { libraryReset: 0 })) await user.click(header('r2')) - const item = await startEdit(user, 'r1') await user.selectOptions(sortBox(), 'citation') await user.type(search(), 'e') view.rerender(lib(false, { libraryReset: 1 })) @@ -597,10 +444,6 @@ describe('the reset path (« Tout afficher »)', () => { expect(sortBox()).toHaveValue('citation') expect(order()).toHaveLength(5) expect(header('r2')).toHaveAttribute('aria-expanded', 'true') - expect(within(item).getByLabelText('Citation')).toBeInTheDocument() - // The tile in edit stays pinned through the reset: a new search does not hide it. - await user.type(search(), 'alpha') - expect(order()).toEqual(['r1', 'r5']) }) }) @@ -638,9 +481,9 @@ describe('« Aller à » a reference hidden by the search (P3, P8)', () => { }) describe('state of a reference that left the document (P23-prime)', () => { - it('is dropped: undoing the removal brings the tile back closed and out of edit', async () => { + it('is dropped: undoing the removal brings the tile back closed', async () => { const { user } = await mount() - await startEdit(user, 'r4') + await user.click(header('r4')) act(() => { store .getState() @@ -652,58 +495,5 @@ describe('state of a reference that left the document (P23-prime)', () => { }) expect(order()).toContain('r4') expect(header('r4')).toHaveAttribute('aria-expanded', 'false') - expect( - within(header('r4').closest('li')!).queryByLabelText('Citation'), - ).toBeNull() - }) -}) - -describe('a read-only flip with a tile in edit (M1)', () => { - const ui = (announce: (text: string) => void, readOnly: boolean) => ( - {lib(readOnly)} - ) - - async function refusedUrl() { - await openReady({ text: sortText() }) - const user = userEvent.setup() - const announce = vi.fn() - const view = render(ui(announce, false)) - const item = await startEdit(user, 'r1') - await user.type( - within(item).getByLabelText('Adresse web (URL)'), - 'exemple.org', - ) - await user.tab() - return { view, announce, item, user } - } - - it('says which refused draft is dropped, once', async () => { - const { view, announce } = await refusedUrl() - view.rerender(ui(announce, true)) - expect(announce).toHaveBeenCalledTimes(1) - expect(announce).toHaveBeenCalledWith( - 'Saisie non appliquée : Adresse web (URL)', - ) - view.rerender(ui(announce, false)) - expect(announce).toHaveBeenCalledTimes(1) - }) - - it('does not move the focus to Citation when editing is possible again', async () => { - const { view, announce } = await refusedUrl() - view.rerender(ui(announce, true)) - view.rerender(ui(announce, false)) - const citation = screen.getByLabelText('Citation') - expect(document.activeElement).not.toBe(citation) - expect(screen.getByLabelText('Adresse web (URL)')).toHaveValue('') - }) - - it('says nothing when no draft is lost', async () => { - await openReady({ text: sortText() }) - const user = userEvent.setup() - const announce = vi.fn() - const view = render(ui(announce, false)) - await startEdit(user, 'r1') - view.rerender(ui(announce, true)) - expect(announce).not.toHaveBeenCalled() }) }) diff --git a/apps/app/tests/unit/editor-tabs-lists.test.tsx b/apps/app/tests/unit/editor-tabs-lists.test.tsx index a7be5998..a418d0e3 100644 --- a/apps/app/tests/unit/editor-tabs-lists.test.tsx +++ b/apps/app/tests/unit/editor-tabs-lists.test.tsx @@ -1,9 +1,14 @@ /** Lot F: the Références tab and Vertèbres. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { cleanup, render, screen, within } from '@testing-library/react' +import { + cleanup, + render, + screen, + waitFor, + within, +} from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' -import ReferencesTab from '@/components/editor/tabs/ReferencesTab' import RegionsSection from '@/components/editor/annotations/sections/RegionsSection' import { useLocaleStore } from '@/state/localeStore' import { edit, insert, point } from '../helpers/editorFixtures' @@ -13,6 +18,7 @@ import { resetStore, store, } from '../helpers/editorHarness' +import ReferencesHost from '../helpers/referencesHost' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@faunosteo/supabase', async (orig) => ({ @@ -44,16 +50,24 @@ describe('Références', () => { it('adds a reference only with a type and a citation', async () => { await openReady() const user = userEvent.setup() - render() + render() await user.click( screen.getByRole('button', { name: 'Ajouter une référence' }), ) await user.click( screen.getByRole('button', { name: 'Ajouter la référence' }), ) - expect(screen.getByRole('alert')).toHaveTextContent('Choisissez un type') + expect(screen.getByLabelText('Type')).toHaveAccessibleDescription( + 'Ce champ est obligatoire.', + ) expect(doc().references).toEqual([]) await user.selectOptions(screen.getByLabelText('Type'), 'web') + await user.click( + screen.getByRole('button', { name: 'Ajouter la référence' }), + ) + expect(screen.getByLabelText('Citation')).toHaveAccessibleDescription( + 'Ce champ est obligatoire.', + ) await user.type(screen.getByLabelText('Citation'), 'Anatomie du cheval') await user.click( screen.getByRole('button', { name: 'Ajouter la référence' }), @@ -68,23 +82,24 @@ describe('Références', () => { expect(doc().references[0].id).toMatch(/^ref-[a-z2-7]{10}$/) }) - it('edits a field in a tile, applies it on blur, and reorders with the arrows', async () => { + it('edits a reference in its dialog, one command on « Enregistrer », and reorders with the arrows', async () => { const text = insert( insert(baseText(), reference('ref-a', 'Alpha')), reference('ref-b', 'Beta'), ) await openReady({ text }) const user = userEvent.setup() - render() + render() await user.click(screen.getByRole('button', { name: /^Alpha/ })) await user.click(screen.getByRole('button', { name: 'Modifier' })) - const url = screen.getByLabelText('Adresse web (URL)', { - selector: '#tab-reference-0-ref-a-url', - }) + const url = screen.getByLabelText('Adresse web (URL)') await user.type(url, 'https://example.org') - await user.tab() + expect(doc().references[0].url).toBeNull() + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => + expect(document.querySelector('dialog[open]')).toBeNull(), + ) expect(doc().references[0].url).toBe('https://example.org') - await user.click(screen.getByRole('button', { name: 'Terminer' })) await user.click(screen.getByRole('button', { name: /^Beta/ })) await user.click(screen.getAllByRole('button', { name: 'Monter' })[1]) expect(doc().references.map((r) => r.id)).toEqual(['ref-b', 'ref-a']) @@ -118,7 +133,7 @@ describe('Références', () => { }) await openReady({ text }) const user = userEvent.setup() - render() + render() await user.click(screen.getByRole('button', { name: /^Alpha/ })) expect(screen.queryByRole('button', { name: 'Supprimer' })).toBeNull() expect(screen.getByText(/Pour supprimer cette référence/)).toBeTruthy() @@ -133,7 +148,7 @@ describe('Références', () => { it('read-only shows the facts and no control that changes the draft', async () => { await openReady({ text: insert(baseText(), reference('ref-a', 'Alpha')) }) const user = userEvent.setup() - render() + render() await user.click(screen.getByRole('button', { name: /^Alpha/ })) expect(screen.getByText('Aucun')).toBeTruthy() expect(screen.queryByRole('textbox', { name: 'Citation' })).toBeNull()