feat(editor): collapsible reference tiles in the Références tab

Board 23 / 24 / 27 tiles: closed (citation on two lines, type, « Citée
{n} fois » / « Non citée »), open (Type, DOI, URL as safe links, the
citers with « famille » badge and « Aller à »), edit (« Terminer » with a
leave guard re-committing every changed field; a refusal keeps edit
and focuses the field). A cited reference shows the deletion hint, an
uncited one keeps « Supprimer ». Read-only keeps DOI, URL, « Aller à ».
« Terminer » keeps focus in the field on press, so a refusal message
can no longer move the button under the pointer.

Gates: typecheck, lint, test:run (app 1419), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (editor-equine never listed): 111
passed / 99 skipped / 3 failed in the new editor-references.spec (two
test bugs, one app bug), fixed and rerun: 5 passed / 4 skipped; full-row
guard: no pre-existing row changed in any table.

## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-citations.test.ts | `citationCounts` counts 2/1/0, memoised, empty | `citersOf`: ordered citers (Cat, Node), family flag, trail from zone, key, memoised, empty |
| editor-references-tab.test.tsx | cards say « citée N fois » (ref-a 1, ref-c 0) | « Citée 2 fois » (fixture gains a node citing ref-a), « Citée 1 fois », « Non citée » |
| same | ids `#tab-reference-ref-a-citation` exist when closed | header id `#tab-reference-0-ref-a-header`; field ids only inside an open edit tile |
| same | ↑/↓ on every card | in open tiles only, absent under a search |
| same | Ctrl+Z on an always-visible field | open tile, Modifier, then same assertion on `#tab-reference-0-ref-a-citation` |
| same | « Aller à » focuses the card (`listitem` count 3, focus key) | tile opened (aria-expanded true), header focused, 3 tiles |
| same | add: `getByText('Nouvelle source')` | tile header named « Nouvelle source » |
| same | read-only: no Supprimer / add | same after opening every tile |
| editor-tabs-lists.test.tsx | edit on blur and arrows on always-open cards | open tile, Modifier, blur applies, Terminer, Monter on opened tile |
| same | cited reference deletion refused in a dialog listing citers | REMOVED: no Supprimer on a cited tile (hint asserted, citer listed); uncited delete kept. The dialog's blocked path stays covered by `DeleteDialog`'s own tests |
| same | read-only: no button at all | read-only: facts shown, no Modifier / Supprimer / Citation textbox (header buttons exist now) |
| editor-keep-alive.test.tsx:~330 | tab-click commit of `#tab-reference-ref-1-citation` | opens tile + Modifier first, id `#tab-reference-0-ref-1-citation` |
| editor-keep-alive.test.tsx:~350,367 | `#panel-reference-ref-1-citation` | `#panel-reference-0-ref-1-citation` |
| editor-references-panel.test.tsx | « citée 2 fois / 1 fois » | « Citée 2 fois / 1 fois » |
| same | `#panel-reference-ref-a-citation`; no `#tab-reference-ref-a-citation` | `#panel-reference-0-ref-a-citation`; no `[id^="tab-reference-"]` while the tab tiles are closed |
| same | ids unique, tab and panel field ids present | tab tile opened in edit first; `tab-reference-0-ref-a-citation` and `panel-reference-0-ref-a-citation` unique |
| e2e editor-structures.spec.ts:~88-110 | citation inputs count 3/1/2, « citée 0 fois » x2, « citée 1 fois », move via row buttons | tile headers count, « Non citée » x2, « Citée 1 fois », tile opened before Monter/Supprimer, `tiles.nth(1)` contains the moved text (saved-list assertion unchanged) |

## i18n (fr / en)
Changed (in place, P18): `editor.references.cited_one|other`: « citée {count} fois » -> « Citée {count} fois »; « cited {count} time(s) » -> « Cited {count} time(s) ».
Added: `editor.references.uncited` Non citée / Not cited; `citers_one|other` « Citée {count} fois, par : » / « Cited {count} time(s), by: »; `no_citers` « Aucun constat ni aucune famille ne cite cette référence. » / « No finding or family cites this reference. »; `family` famille / family; `go_to` Aller à / Go to; `edit` Modifier / Edit; `done` Terminer / Done; `edit_title` Modifier la référence / Edit the reference; `url_label` URL / URL; `none_doi` Aucun / None; `none_url` Aucune / None; `new_tab` (nouvel onglet) / (new tab) (sr-only); `delete_hint` (REVUE wording, fr and en).
Removed: none. R10 grep (src, tests, e2e incl. editor-equine) found no reader of the old lowercase wording left.
This commit is contained in:
bchanot committed 2026-11-12 20:50:25 +01:00
1 parent 4499bc740c
commit c21995b3fb
26 files changed
+1532 -155

No files matched your search

@@ -0,0 +1,269 @@
import { fr } from '@/i18n/fr'
import type { Locator, Page, TestInfo } from '@playwright/test'
import {
expect,
expectAccessible,
expectNoHorizontalOverflow,
test,
} from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
editorActor,
libraryRoot,
openEditor,
openTab,
place,
seedDraft,
standardShape,
} 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.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const DOI = '10.3389/fvets.2022.898096'
/** « Référence A » (cited by « Constat A ») plus one cited by a family and one uncited. */
function shape(document: Record<string, unknown>) {
standardShape(document)
document.references = [
{
id: 'ref-a',
type: 'book',
citation: 'Référence A',
url: null,
doi: null,
},
{
id: 'ref-doi',
type: 'journal',
citation:
'Long-term outcome of horses undergoing surgery, Front Vet Sci 2022',
url: `https://doi.org/${DOI}`,
doi: DOI,
},
{
id: 'ref-free',
type: 'web',
citation: 'Source libre',
url: null,
doi: null,
},
]
const zone = (document.finding_zones as { categories: unknown[] }[])[0]
const family = zone.categories[0] as { reference_ids: string[] }
family.reference_ids = ['ref-doi']
}
async function open(page: Page) {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, { shape: shape })
await openEditor(page, dict, actor, seed.sheetId)
return { actor, seed }
}
const headers = (page: Page) =>
libraryRoot(page).locator('button[aria-controls][id$="-header"]')
/** The tile at a position of the seeded list (header ids stay put while it is in edit). */
const tileAt = (page: Page, position: number): Locator =>
headers(page).nth(position).locator('xpath=ancestor::li[1]')
const REF_DOI = 1
const REF_A = 0
const REF_FREE = 2
test.describe('reference tiles, edit mode', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(
isPhone(info),
'editing needs >= 1 024 px; the phone twin is below',
) // floor-guard: allow C16 editing needs >= 1024 px; read-only twin in this file
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('closed, open and edit tiles, accessible in each state', async ({
page,
requests,
}) => {
test.setTimeout(120_000)
const { actor } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await openTab(page, dict, 'references')
await expect(headers(page)).toHaveCount(3)
await expect(headers(page).first()).toHaveAttribute(
'aria-expanded',
'false',
)
await expect(
libraryRoot(page).getByText(dict['editor.references.uncited']),
).toHaveCount(1)
await expectNoHorizontalOverflow(page, 'the closed tiles')
await expectAccessible(page, 'the closed reference tiles')
// Open: facts as safe links, the citers, the hint on a cited reference.
await headers(page).nth(1).click()
const cited = tileAt(page, REF_DOI)
await expect(headers(page).nth(1)).toHaveAttribute('aria-expanded', 'true')
const doi = cited
.getByRole('link', { name: new RegExp(DOI.replace('.', '\\.')) })
.first()
await expect(doi).toHaveAttribute('href', `https://doi.org/${DOI}`)
await expect(doi).toHaveAttribute('target', '_blank')
await expect(doi).toHaveAttribute('rel', 'noopener noreferrer')
await expect(cited.getByText('Dysfonction A')).toBeVisible()
await expect(
cited.getByText(dict['editor.references.family'], { exact: true }),
).toBeVisible()
await expect(
cited.getByRole('button', { name: dict['editor.action.delete'] }),
).toHaveCount(0)
await expect(
cited.getByText(dict['editor.references.delete_hint']),
).toBeVisible()
await headers(page).nth(2).click()
await expect(
tileAt(page, REF_FREE).getByRole('button', {
name: dict['editor.action.delete'],
}),
).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()
await expect(
cited.getByText(dict['editor.references.edit_title']),
).toBeVisible()
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')
})
test('« Terminer » keeps the edit view while a field is refused', async ({
page,
}) => {
test.setTimeout(120_000)
await open(page)
await openTab(page, dict, 'references')
await headers(page).nth(2).click()
const tile = tileAt(page, REF_FREE)
await tile
.getByRole('button', { name: dict['editor.references.edit'] })
.click()
const url = tile.getByLabel(dict['editor.reference.url'])
await url.fill('exemple.org')
await tile
.getByRole('button', { name: dict['editor.references.done'] })
.click()
await expect(url).toBeFocused()
await expect(
tile.getByRole('button', { name: dict['editor.references.done'] }),
).toBeVisible()
await url.fill('https://exemple.org/page')
await tile
.getByRole('button', { name: dict['editor.references.done'] })
.click()
await expect(tile.getByLabel(dict['editor.reference.url'])).toHaveCount(0)
await expect(
tile.getByRole('link', { name: /exemple\.org/ }),
).toHaveAttribute('href', 'https://exemple.org/page')
})
test('the tile headers are a keyboard walk: Tab between them, Enter and Space open', async ({
page,
}) => {
test.setTimeout(120_000)
await open(page)
await openTab(page, dict, 'references')
await page
.getByRole('searchbox', { name: dict['editor.references.search'] })
.focus()
for (let at = 0; at < 3; at++) {
await page.keyboard.press('Tab')
await expect(headers(page).nth(at)).toBeFocused()
}
// Focus is on the third header: one Shift+Tab back reaches the second.
await page.keyboard.press('Shift+Tab')
await expect(headers(page).nth(1)).toBeFocused()
await page.keyboard.press('Enter')
await expect(headers(page).nth(1)).toHaveAttribute('aria-expanded', 'true')
// Open, the tile's own content is the next tab stop: its DOI link, then back.
await page.keyboard.press('Tab')
await expect(tileAt(page, REF_DOI).getByRole('link').first()).toBeFocused()
await page.keyboard.press('Shift+Tab')
await expect(headers(page).nth(1)).toBeFocused()
await page.keyboard.press('Space')
await expect(headers(page).nth(1)).toHaveAttribute('aria-expanded', 'false')
})
test('« Aller à » on a citer opens the Constats tab on it', async ({
page,
}) => {
test.setTimeout(120_000)
await open(page)
await openTab(page, dict, 'references')
await headers(page).nth(0).click()
await tileAt(page, REF_A)
.getByRole('button', { name: dict['editor.references.go_to'] })
.click()
await expect(place(page, 'findings')).toBeVisible()
await expect(place(page, 'findings').locator(':focus')).toHaveCount(1)
})
})
test.describe('reference tiles, read-only at 375 px', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(!isPhone(info), 'the read-only twin runs at 375 px only')
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('« Plus » lists Références; tiles keep DOI, URL and « Aller à », no edit control @phone', async ({
page,
}) => {
test.setTimeout(120_000)
await open(page)
await openTab(page, dict, 'references')
await expect(headers(page)).toHaveCount(3)
const box = await headers(page).first().boundingBox()
expect(box?.height ?? 0).toBeGreaterThanOrEqual(44)
await expectNoHorizontalOverflow(page, 'the closed tiles at 375 px')
await expectAccessible(page, 'the closed tiles at 375 px')
await headers(page).nth(1).click()
const cited = tileAt(page, REF_DOI)
await expect(cited.getByRole('link').first()).toHaveAttribute(
'target',
'_blank',
)
const goTo = cited.getByRole('button', {
name: dict['editor.references.go_to'],
})
expect((await goTo.boundingBox())?.height ?? 0).toBeGreaterThanOrEqual(44)
for (const name of [
dict['editor.references.edit'],
dict['editor.action.delete'],
dict['editor.action.move_up'],
]) {
await expect(libraryRoot(page).getByRole('button', { name })).toHaveCount(
0,
)
}
await expectNoHorizontalOverflow(page, 'an open tile at 375 px')
await expectAccessible(page, 'an open tile at 375 px')
})
})
+21 -22
View File
@@ -87,35 +87,34 @@ test.describe('editor structures (A4)', () => {
.click()
await expect(page.getByText(citation)).toBeVisible()
}
const citations = page.locator(
'[id^="tab-reference-"][id$="-citation"]:not(#tab-reference-new-citation)',
)
await expect(citations).toHaveCount(3)
await expect(libraryRoot(page).getByText('citée 0 fois')).toHaveCount(2)
await expect(libraryRoot(page).getByText('citée 1 fois')).toHaveCount(1)
await page
.getByRole('searchbox', { name: dict['editor.references.search'] })
.fill('seconde')
await expect(citations).toHaveCount(1)
await page
.getByRole('searchbox', { name: dict['editor.references.search'] })
.fill('')
await expect(citations).toHaveCount(3)
await page
.getByRole('listitem')
.filter({ hasText: 'Seconde référence' })
const tiles = page.locator('[id^="tab-reference-"][id$="-header"]')
const tileOf = (citation: string) =>
page.getByRole('listitem').filter({ hasText: citation }).first()
await expect(tiles).toHaveCount(3)
await expect(
libraryRoot(page).getByText(dict['editor.references.uncited']),
).toHaveCount(2)
await expect(libraryRoot(page).getByText('Citée 1 fois')).toHaveCount(1)
const search = page.getByRole('searchbox', {
name: dict['editor.references.search'],
})
await search.fill('seconde')
await expect(tiles).toHaveCount(1)
await search.fill('')
await expect(tiles).toHaveCount(3)
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(citations.nth(1)).toHaveValue('Seconde référence')
await page
.getByRole('listitem')
.filter({ hasText: 'Première référence' })
await expect(tiles.nth(1)).toContainText('Seconde référence')
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()
await dialog(page)
.getByRole('button', { name: dict['editor.delete.confirm'] })
.click()
await expect(citations).toHaveCount(2)
await expect(tiles).toHaveCount(2)
// A region with its count.
await openSection(page, dict, 'regions')
@@ -11,6 +11,7 @@ export default function DraftField({
label,
value,
onChange,
onBlur,
multiline,
hint,
error,
@@ -19,6 +20,8 @@ export default function DraftField({
label: string
value: string
onChange: (value: string) => void
/** Optional: a form field that applies its text when it loses the focus. */
onBlur?: () => void
multiline?: boolean
hint?: string
error?: string
@@ -27,6 +30,7 @@ export default function DraftField({
id,
value,
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
onBlur,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
}
@@ -0,0 +1,57 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { CiterItem } from '@/editor/references/citations'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** « Citée {n} fois, par : » and who cites, each with « Aller à »; the empty line when none. */
export default function CitersList({
citers,
onGoTo,
}: {
citers: readonly CiterItem[]
onGoTo: (key: ElementKey) => void
}) {
const t = useT()
const plural = usePlural()
const locale = useLocaleStore((s) => s.locale)
if (citers.length === 0) {
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.no_citers')}
</p>
)
}
return (
<div className="space-y-1">
<p className="text-sm font-semibold">
{plural('editor.references.citers', citers.length)}
</p>
<ul>
{citers.map((citer, index) => (
<li key={index} className="flex items-start gap-2 py-1 text-sm">
<span className="min-w-0 flex-1">
<span className="text-[var(--color-ink-muted)]">
{citer.trail.map((name) => name[locale]).join(' › ')}
{' › '}
</span>
{citer.name[locale]}
{citer.isFamily && (
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
{t('editor.references.family')}
</span>
)}
</span>
<button
type="button"
onClick={() => onGoTo(citer.key)}
className="inline-flex min-h-11 items-center whitespace-nowrap text-[var(--color-accent-strong)] underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
{t('editor.references.go_to')}
</button>
</li>
))}
</ul>
</div>
)
}
@@ -0,0 +1,63 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
import {
useReferenceEdit,
type Field,
type LeaveGuard,
} from './useReferenceEdit'
interface Props {
reference: Reference
/** DOM id prefix of the tile (host, position and id): the fields' ids derive from it. */
base: string
/** The tile's leave guard, registered while the view is mounted and null after. */
registerLeave: (guard: LeaveGuard | null) => void
}
/** The edit view of one reference (board 24 D): type, DOI, citation and URL. */
export default function ReferenceEditor(props: Props) {
const { reference, base } = props
const t = useT()
const { edit, drafts, setDraft, commitField, setType } = useReferenceEdit(
reference,
base,
props.registerLeave,
)
const text = (field: Field, label: string, multiline = false) => (
<DraftField
id={`${base}-${field}`}
label={label}
value={drafts[field]}
onChange={(value) => setDraft(field, value)}
onBlur={() => commitField(field)}
multiline={multiline}
error={edit.fieldError(field)}
/>
)
const options = REFERENCE_TYPES.map((type) => ({
value: type,
label: t(`editor.reference.type.${type}`),
}))
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<SelectField
id={`${base}-type`}
label={t('editor.reference.type')}
value={reference.type}
options={options}
onCommit={(type) =>
setType({ ...reference, type: type as ReferenceType })
}
error={edit.fieldError('type')}
/>
{text('doi', t('editor.reference.doi'))}
</div>
{text('citation', t('editor.reference.citation'), true)}
{text('url', t('editor.reference.url'))}
</div>
)
}
@@ -0,0 +1,62 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import Icon from '@/components/ui/Icon'
import { doiHref, webHref } from '@/editor/references/safeLink'
import { useT } from '@/i18n/useT'
const LINK =
'inline-flex max-w-full items-center gap-1 text-[var(--color-accent-strong)] underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** An external link (new tab); plain text when the address is not a safe link. */
function Address({ text, href }: { text: string; href: string | null }) {
const t = useT()
if (href === null) return <span className="break-all">{text}</span>
return (
<a href={href} target="_blank" rel="noopener noreferrer" className={LINK}>
<span className="break-all">{text}</span>
<Icon name="external" size={14} />
<span className="sr-only">{t('editor.references.new_tab')}</span>
</a>
)
}
function Absent({ label }: { label: string }) {
return <span className="text-[var(--color-ink-muted)]">{label}</span>
}
/** Type, DOI and URL of a reference; the links only for http(s) and a well-formed DOI. */
export default function ReferenceFacts({
reference,
}: {
reference: Reference
}) {
const t = useT()
const { doi, url } = reference
return (
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
<dt className="text-[var(--color-ink-muted)]">
{t('editor.reference.type')}
</dt>
<dd>{t(`editor.reference.type.${reference.type}`)}</dd>
<dt className="text-[var(--color-ink-muted)]">
{t('editor.reference.doi')}
</dt>
<dd className="min-w-0">
{doi ? (
<Address text={doi} href={doiHref(doi)} />
) : (
<Absent label={t('editor.references.none_doi')} />
)}
</dd>
<dt className="text-[var(--color-ink-muted)]">
{t('editor.references.url_label')}
</dt>
<dd className="min-w-0">
{url ? (
<Address text={url} href={webHref(url)} />
) : (
<Absent label={t('editor.references.none_url')} />
)}
</dd>
</dl>
)
}
@@ -10,28 +10,33 @@ import {
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
import { citationCounts } from '@/editor/references/citations'
import type { EditorTarget } from '@/editor/navigation'
import { citersOf } from '@/editor/references/citations'
import { visibleReferences } from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
import ReferenceForm from './ReferenceForm'
import { EmptyLine, ReferenceList } from './ReferenceList'
import { EmptyLine } from './ReferenceList'
import ReferenceTiles from './ReferenceTiles'
import { tileKeys, useTileState } from './useTileState'
interface Props {
readOnly: boolean
/** « Aller à » a citing finding or family. */
navigate: (target: EditorTarget) => void
focus?: FocusRequest
/** Bumped by « Tout afficher »: the search is emptied once per bump. */
resetSignal?: number
}
/**
* « Aller à » a reference: the search is cleared first when it may hide the card, and the
* card is focused after the commit that shows it (it does not exist while hidden).
* « Aller à » a reference: its tile is opened, the search is cleared first when it may
* hide the tile, and the tile's button is focused after the commit that shows it.
*/
function useReferenceFocus(
focus: FocusRequest | undefined,
query: string,
clearQuery: () => void,
actions: { clearQuery: () => void; reveal: (key: ElementKey) => void },
) {
const [late, setLate] = useState<ElementKey | null>(null)
useEffect(() => {
@@ -41,8 +46,9 @@ function useReferenceFocus(
}, [late])
useFocusRequest(focus, (target) => {
if (target.key === null) return 'none'
actions.reveal(target.key)
if (query === '') return focusRow(target.key) ? 'found' : 'none'
clearQuery()
actions.clearQuery()
setLate(target.key)
return 'found'
})
@@ -60,21 +66,27 @@ function useSearchQuery(resetSignal: number) {
}
/**
* The sheet's bibliography: a search, one card per reference with how often it is cited,
* the add form and the delete dialog. Lives in the Références tab (ids prefixed `tab-`).
* The sheet's bibliography: a search, one collapsible tile per reference, the add form
* and the delete dialog. Lives in the Références tab (ids prefixed `tab-`).
*/
export default function ReferenceLibrary({
readOnly,
focus,
resetSignal = 0,
}: Props) {
export default function ReferenceLibrary(props: Props) {
const { readOnly, navigate, focus, resetSignal = 0 } = props
const t = useT()
const doc = useSheetDocument()
const tiles = useTileState()
const [query, setQuery] = useSearchQuery(resetSignal)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
useReferenceFocus(focus, query, () => setQuery(''))
const all: readonly Reference[] = doc?.references ?? []
const keys = tileKeys(all)
const reveal = (key: ElementKey) => {
const at = all.findIndex(
(reference) => key.kind === 'reference' && reference.id === key.id,
)
if (at >= 0) tiles.reveal(keys[at])
}
useReferenceFocus(focus, query, { clearQuery: () => setQuery(''), reveal })
const shown = visibleReferences(all, null, query)
const citers = doc ? citersOf(doc) : new Map()
return (
<div className="space-y-3">
<Input
@@ -87,13 +99,15 @@ export default function ReferenceLibrary({
{doc && (
<>
<EmptyLine total={all.length} shown={shown.length} />
<ReferenceList
host="tab"
<ReferenceTiles
shown={shown}
all={all}
counts={citationCounts(doc)}
movable={query.trim() === ''}
keys={keys}
citers={citers}
tiles={tiles}
readOnly={readOnly}
movable={query.trim() === ''}
navigate={navigate}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
@@ -1,4 +1,5 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import type { CiterItem } from '@/editor/references/citations'
import { useT } from '@/i18n/useT'
import ReferenceRow from './ReferenceRow'
import type { ReferenceHost } from './referenceTypes'
@@ -7,29 +8,29 @@ interface ListProps {
host: ReferenceHost
shown: readonly Reference[]
all: readonly Reference[]
counts: ReadonlyMap<string, number>
movable: boolean
citers: ReadonlyMap<string, readonly CiterItem[]>
readOnly: boolean
onDelete: (reference: Reference) => void
}
/** The cards of `shown`, each knowing its place in the whole bibliography `all`. */
export function ReferenceList({ shown, all, counts, ...rest }: ListProps) {
/** The panel's cards of `shown`, each knowing its place in the whole bibliography `all`. */
export function ReferenceList({ shown, all, citers, ...rest }: ListProps) {
return (
<ul className="space-y-3">
{shown.map((reference) => (
<ReferenceRow
key={reference.id}
host={rest.host}
reference={reference}
index={all.indexOf(reference)}
count={all.length}
cited={counts.get(reference.id) ?? 0}
movable={rest.movable}
readOnly={rest.readOnly}
onDelete={() => rest.onDelete(reference)}
/>
))}
{shown.map((reference) => {
const index = all.indexOf(reference)
return (
<ReferenceRow
key={`${index}-${reference.id}`}
host={rest.host}
reference={reference}
index={index}
cited={citers.get(reference.id)?.length ?? 0}
readOnly={rest.readOnly}
onDelete={() => rest.onDelete(reference)}
/>
)
})}
</ul>
)
}
@@ -1,6 +1,5 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
@@ -12,14 +11,12 @@ import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes'
const CARD = 'space-y-3 rounded-lg border border-[var(--color-border)] p-3'
/** One reference: fields commit one by one, ↑ / ↓ reorder, delete asks the core. */
/** One reference as the citations panel shows it (interim until R2.4): fields commit one by one. */
export default function ReferenceRow({
host,
reference,
index,
count,
cited,
movable,
readOnly,
onDelete,
}: {
@@ -28,11 +25,8 @@ export default function ReferenceRow({
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
index: number
count: number
/** How many findings cite it. */
cited: number
/** ↑ / ↓ only while neither the finding filter nor the search narrows the list. */
movable: boolean
readOnly: boolean
onDelete: () => void
}) {
@@ -50,11 +44,13 @@ export default function ReferenceRow({
value: type,
label: t(`editor.reference.type.${type}`),
}))
const prefix = `${host}-reference-${reference.id}`
const prefix = `${host}-reference-${index}-${reference.id}`
return (
<li {...focusAttrs(key)} className={`${CARD} ${FOCUS_CLASS}`}>
<p className="text-right text-sm text-[var(--color-ink-muted)]">
{plural('editor.references.cited', cited)}
{cited === 0
? t('editor.references.uncited')
: plural('editor.references.cited', cited)}
</p>
<div className="grid gap-3">
<SelectField
@@ -97,16 +93,6 @@ export default function ReferenceRow({
/>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
{movable && (
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) =>
edit.run('move', { op: 'move', key, position })
}
/>
)}
<ActionButton
readOnly={readOnly}
variant="danger"
@@ -116,11 +102,6 @@ export default function ReferenceRow({
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('move') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('move')}
</p>
)}
</li>
)
}
@@ -0,0 +1,211 @@
import { useRef, type RefObject } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { usePlural } from '@/editor/plural'
import type { CiterItem } from '@/editor/references/citations'
import { useT } from '@/i18n/useT'
import CitersList from './CitersList'
import ReferenceEditor from './ReferenceEditor'
import ReferenceFacts from './ReferenceFacts'
import type { ReferenceHost } from './referenceTypes'
import type { LeaveGuard } from './useReferenceEdit'
/** What a tile asks of the library that owns its state. */
export interface TileHandlers {
toggle: () => void
edit: () => void
/** Leaves the edit view; false (the view stays) when a field refuses. */
done: () => boolean
remove: () => void
move: (position: number) => void
goTo: (key: ElementKey) => void
registerLeave: (guard: LeaveGuard | null) => void
}
export interface TileProps {
host: ReferenceHost
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
position: number
count: number
citers: readonly CiterItem[]
open: boolean
editing: boolean
readOnly: boolean
/** ↑ / ↓ only while neither the search nor a sort narrows or reorders the list. */
movable: boolean
on: TileHandlers
}
/** DOM id prefix of a tile: host, position and id keep duplicates distinct (P31). */
export const tileBase = (
host: ReferenceHost,
position: number,
reference: Reference,
) => `${host}-reference-${position}-${reference.id}`
const BUTTON_RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** The disclosure button: citation (two lines when closed), type and how often it is cited. */
function TileHeader({
base,
props,
headerRef,
}: {
base: string
props: TileProps
headerRef: RefObject<HTMLButtonElement | null>
}) {
const t = useT()
const plural = usePlural()
const { reference, open, editing, citers } = props
const cited = citers.length
const key = JSON.stringify({ kind: 'reference', id: reference.id })
return (
<button
ref={headerRef}
type="button"
id={`${base}-header`}
data-focus-key={key}
aria-expanded={open || editing}
aria-controls={`${base}-body`}
onClick={props.on.toggle}
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left sm:grid-cols-[1.25rem_1fr_auto] ${BUTTON_RING}`}
>
<Icon
name={open || editing ? 'chevron-down' : 'chevron-right'}
size={18}
/>
<span
className={`min-w-0 break-words text-sm ${open || editing ? '' : 'line-clamp-2'} ${editing ? 'font-semibold' : ''}`}
>
{editing ? t('editor.references.edit_title') : reference.citation}
</span>
<span className="col-start-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-ink-muted)] sm:col-start-3 sm:row-start-1 sm:flex-col sm:items-end">
{!editing && (
<span className="rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 font-medium text-[var(--color-ink)]">
{t(`editor.reference.type.${reference.type}`)}
</span>
)}
<span>
{cited === 0
? t('editor.references.uncited')
: plural('editor.references.cited', cited)}
</span>
</span>
</button>
)
}
/** « Modifier », « Supprimer » (uncited only, else the hint), « Monter » / « Descendre ». */
function TileActions({ props }: { props: TileProps }) {
const t = useT()
const { position, count, citers, readOnly, movable, on } = props
if (readOnly) return null
return (
<>
<div className="flex flex-wrap items-center gap-2">
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={on.edit}
>
{t('editor.references.edit')}
</ActionButton>
{citers.length === 0 && (
<ActionButton
readOnly={false}
variant="ghost"
size="sm"
className="text-[var(--color-danger-strong)]"
onClick={on.remove}
>
{t('editor.action.delete')}
</ActionButton>
)}
{movable && (
<>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={position === 0}
onClick={() => on.move(position - 1)}
>
{t('editor.action.move_up')}
</ActionButton>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={position >= count - 1}
onClick={() => on.move(position + 1)}
>
{t('editor.action.move_down')}
</ActionButton>
</>
)}
</div>
{citers.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.delete_hint')}
</p>
)}
</>
)
}
/**
* One reference as a collapsible tile (boards 23, 24): closed, open (facts, citers,
* actions), or in edit (fields, citers, « Terminer »). Read-only: the facts and the
* citers' « Aller à » only, no control that changes the draft.
*/
export default function ReferenceTile(props: TileProps) {
const { host, reference, position, open, editing, on } = props
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef<HTMLButtonElement>(null)
const done = () => {
if (on.done()) headerRef.current?.focus()
}
return (
<li className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]">
<TileHeader base={base} props={props} headerRef={headerRef} />
{(open || editing) && (
<div
id={`${base}-body`}
className="space-y-3 border-t border-[var(--color-border)] p-3"
>
{editing ? (
<ReferenceEditor
reference={reference}
base={base}
registerLeave={on.registerLeave}
/>
) : (
<ReferenceFacts reference={reference} />
)}
<CitersList citers={props.citers} onGoTo={on.goTo} />
{editing ? (
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
// A press keeps the focus in its field: a refusal shown on blur would move
// the button before the click lands. The click applies every field itself.
onMouseDown={(event) => event.preventDefault()}
onClick={done}
>
{t('editor.references.done')}
</ActionButton>
) : (
<TileActions props={props} />
)}
</div>
)}
</li>
)
}
@@ -0,0 +1,71 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import type { CiterItem } from '@/editor/references/citations'
import { useEditCommand } from '@/editor/useEditCommand'
import ReferenceTile from './ReferenceTile'
import type { useTileState } from './useTileState'
interface Props {
/** The tiles to list, each placed by its index in the whole bibliography `all`. */
shown: readonly Reference[]
all: readonly Reference[]
/** One key per position of `all` (`tileKeys`). */
keys: readonly string[]
citers: ReadonlyMap<string, readonly CiterItem[]>
tiles: ReturnType<typeof useTileState>
readOnly: boolean
movable: boolean
navigate: (target: EditorTarget) => void
onDelete: (reference: Reference) => void
}
/** The tiles of the Références tab, wired to the library's open / edit state. */
export default function ReferenceTiles(props: Props) {
const { shown, all, keys, citers, tiles, navigate } = props
const edit = useEditCommand()
const move = (reference: Reference, position: number) =>
edit.run('move', {
op: 'move',
key: { kind: 'reference', id: reference.id },
position,
})
const moveError = edit.fieldError('move')
return (
<>
<ul className="space-y-3">
{shown.map((reference) => {
const position = all.indexOf(reference)
const key = keys[position]
return (
<ReferenceTile
key={key}
host="tab"
reference={reference}
position={position}
count={all.length}
citers={citers.get(reference.id) ?? []}
open={tiles.openKeys.has(key)}
editing={!props.readOnly && tiles.editingKey === key}
readOnly={props.readOnly}
movable={props.movable}
on={{
toggle: () => tiles.toggle(key),
edit: () => tiles.startEdit(key),
done: tiles.finish,
remove: () => props.onDelete(reference),
move: (to) => move(reference, to),
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
}}
/>
)
})}
</ul>
{moveError && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{moveError}
</p>
)}
</>
)
}
@@ -4,7 +4,7 @@ import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import Icon from '@/components/ui/Icon'
import { citationCounts } from '@/editor/references/citations'
import { citersOf } from '@/editor/references/citations'
import {
citedIds,
citingFinding,
@@ -138,8 +138,7 @@ export default function ReferencesPanel(props: Props) {
host="panel"
shown={visibleReferences(all, cited, '')}
all={all}
counts={citationCounts(doc)}
movable={false}
citers={citersOf(doc)}
readOnly={readOnly}
onDelete={(reference) =>
setDeleting({
@@ -0,0 +1,103 @@
import { useEffect, useState } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
/** The text fields of the edit view, in the order the leave guard tries them. */
export const FIELDS = ['citation', 'doi', 'url'] as const
export type Field = (typeof FIELDS)[number]
type Drafts = Record<Field, string>
/** What the guard calls on a leave: true when every pending field was applied. */
export type LeaveGuard = () => boolean
const committedOf = (reference: Reference): Drafts => ({
citation: reference.citation,
doi: reference.doi ?? '',
url: reference.url ?? '',
})
/** The document value a draft gives (a blank optional field is null, so ''). */
const normalized = (field: Field, draft: string) =>
field === 'citation' ? draft : (nullable(draft) ?? '')
const patched = (reference: Reference, field: Field, draft: string) =>
field === 'citation'
? { ...reference, citation: draft }
: { ...reference, [field]: nullable(draft) }
/** One draft per text field; a new committed value (undo, reload) replaces its draft. */
function useDrafts(reference: Reference) {
const committed = committedOf(reference)
const [drafts, setDrafts] = useState(committed)
const [seen, setSeen] = useState(committed)
const changed = FIELDS.filter((field) => seen[field] !== committed[field])
if (changed.length > 0) {
setSeen(committed)
const fresh = changed.map((field) => [field, committed[field]])
setDrafts({ ...drafts, ...Object.fromEntries(fresh) })
}
const setDraft = (field: Field, value: string) =>
setDrafts({ ...drafts, [field]: value })
return [drafts, setDraft] as const
}
/**
* The write path of one reference's edit view. A field applies to the draft when it
* loses the focus (`commitField`); `leave` re-applies every field whose text differs from
* the document, stops at the first refusal, shows it and focuses that field (P22, P22').
* `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
*/
export function useReferenceEdit(
reference: Reference,
base: string,
registerLeave: (guard: LeaveGuard | null) => void,
) {
const edit = useEditCommand()
const [drafts, setDraft] = useDrafts(reference)
const key = { kind: 'reference', id: reference.id } as const
const update = (field: string, value: Reference) =>
edit.run(field, {
op: 'update',
key,
element: { kind: 'reference', value },
})
const apply = (current: Reference, field: Field): Reference | null => {
const draft = drafts[field]
if (field === 'citation' && isBlank(draft)) {
edit.reject(field, 'editor.field.required')
return null
}
const next = patched(current, field, draft)
return update(field, next) ? next : null
}
const pending = (current: Reference, field: Field) =>
normalized(field, drafts[field]) !== committedOf(current)[field]
const leave: LeaveGuard = () => {
let current = reference
for (const field of FIELDS.filter((name) => pending(current, name))) {
const next = apply(current, field)
if (!next) {
document.getElementById(`${base}-${field}`)?.focus()
return false
}
current = next
}
return true
}
useEffect(() => {
registerLeave(leave)
return () => registerLeave(null)
})
useEffect(() => {
document.getElementById(`${base}-citation`)?.focus()
}, [base])
return {
edit,
drafts,
setDraft,
commitField: (field: Field) =>
pending(reference, field) && apply(reference, field),
setType: (value: Reference) => update('type', value),
}
}
@@ -0,0 +1,58 @@
import { useRef, useState } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import type { LeaveGuard } from './useReferenceEdit'
/**
* One key per tile: the id and its occurrence among equal ids, so a duplicated id stays
* two distinct tiles (P31) and a tile keeps its state when ↑ / ↓ changes its position.
*/
export function tileKeys(all: readonly Reference[]): string[] {
const seen = new Map<string, number>()
return all.map((reference) => {
const occurrence = seen.get(reference.id) ?? 0
seen.set(reference.id, occurrence + 1)
return `${reference.id}#${occurrence}`
})
}
/**
* Which tiles are open and which one is in edit. Lives in the library, which the tab keeps
* mounted (A2), so both survive a tab change and reset when the editor is reopened.
* Leaving the edit view asks the tile's guard first: a refusal keeps it (P22).
*/
export function useTileState() {
const [openKeys, setOpenKeys] = useState<ReadonlySet<string>>(() => new Set())
const [editingKey, setEditingKey] = useState<string | null>(null)
const guard = useRef<LeaveGuard | null>(null)
const leave = () => guard.current?.() ?? true
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
const finish = () => {
if (!leave()) return false
setEditingKey(null)
return true
}
const toggle = (key: string) => {
if (editingKey === key) return void finish()
setOpenKeys((prev) => {
const next = new Set(prev)
if (!next.delete(key)) next.add(key)
return next
})
}
const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && !leave()) return
setEditingKey(key)
open(key)
}
return {
openKeys,
editingKey,
toggle,
startEdit,
finish,
reveal: open,
registerLeave: (next: LeaveGuard | null) => {
guard.current = next
},
}
}
@@ -5,6 +5,7 @@ import { useT } from '@/i18n/useT'
/** The fifth tab: the sheet's reference library under its own heading. */
export default function ReferencesTab({
readOnly,
navigate,
focus,
libraryReset,
}: EditorPlaceProps) {
@@ -25,6 +26,7 @@ export default function ReferencesTab({
</h2>
<ReferenceLibrary
readOnly={readOnly}
navigate={navigate}
focus={focus}
resetSignal={libraryReset}
/>
+6
View File
@@ -18,6 +18,9 @@ export type IconName =
| 'lock'
| 'google'
| 'apple'
| 'chevron-right'
| 'chevron-down'
| 'external'
/** Stroke paths on a 24-unit grid; decorative by default (aria-hidden). */
const PATHS: Record<IconName, string> = {
@@ -35,6 +38,9 @@ const PATHS: Record<IconName, string> = {
'eye-off':
'M3 3l18 18M10.6 10.6A3 3 0 0 0 13.4 13.4M9.9 5.2A10.5 10.5 0 0 1 12 5c6 0 10 7 10 7a17 17 0 0 1-3.2 3.9M6.1 6.1A17 17 0 0 0 2 12s4 7 10 7a10 10 0 0 0 4-.8',
check: 'M5 12l5 5L20 7',
'chevron-right': 'M9 6l6 6-6 6',
'chevron-down': 'M6 9l6 6 6-6',
external: 'M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5',
lock: 'M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3',
alert: 'M12 9v4M12 17h.01M10.3 3.9L2.8 17a2 2 0 0 0 1.7 3h15a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z',
google:
+42 -13
View File
@@ -1,25 +1,54 @@
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import type {
AnatomicalSheetDocument,
ElementKey,
LocalizedText,
} from '@faunosteo/core-wasm/types'
import { buildItems } from '@/editor/findings/tree'
const memo = new WeakMap<AnatomicalSheetDocument, ReadonlyMap<string, number>>()
/** A family or a finding that cites a reference. */
export interface CiterItem {
key: ElementKey
name: LocalizedText
/** The zone, then the families above, outermost first; the citer itself excluded. */
trail: readonly LocalizedText[]
isFamily: boolean
}
const memo = new WeakMap<
AnatomicalSheetDocument,
ReadonlyMap<string, readonly CiterItem[]>
>()
/**
* How many findings (categories and nodes, at any depth) cite each reference. A display
* count read from the document, no rule: the core's `sheet.dependents` stays the authority
* for a refused deletion. Memoised on the parsed document.
* Who cites each reference: families and findings at any depth, in document order, one
* entry per citer however often it lists the id. A display list read from the document,
* no rule: the core's `sheet.dependents` stays the authority for a refused deletion.
* Memoised on the parsed document.
*/
export function citationCounts(
export function citersOf(
doc: AnatomicalSheetDocument,
): ReadonlyMap<string, number> {
): ReadonlyMap<string, readonly CiterItem[]> {
const known = memo.get(doc)
if (known) return known
const counts = new Map<string, number>()
for (const { element } of buildItems(doc)) {
const items = buildItems(doc)
const byId = new Map(items.map((item) => [item.id, item]))
const trailOf = (parentId: string | null): LocalizedText[] => {
const parent = parentId === null ? undefined : byId.get(parentId)
return parent ? [...trailOf(parent.parentId), parent.name] : []
}
const citers = new Map<string, CiterItem[]>()
for (const { element, key, name, parentId, kind } of items) {
if (element.kind === 'zone') continue
for (const id of element.value.reference_ids) {
counts.set(id, (counts.get(id) ?? 0) + 1)
const citer = {
key,
name,
trail: trailOf(parentId),
isFamily: kind === 'category',
}
for (const id of new Set(element.value.reference_ids)) {
citers.set(id, [...(citers.get(id) ?? []), citer])
}
}
memo.set(doc, counts)
return counts
memo.set(doc, citers)
return citers
}
@@ -0,0 +1,24 @@
const DOI_PREFIX = /^(?:doi:|https?:\/\/(?:dx\.)?doi\.org\/)/i
const DOI_SHAPE = /^10\.\d{4,9}\/\S+$/
/** The address as a link target, only for http and https; anything else is plain text. */
export function webHref(raw: string): string | null {
try {
const url = new URL(raw.trim())
return url.protocol === 'http:' || url.protocol === 'https:'
? url.href
: null
} catch {
return null
}
}
/**
* `https://doi.org/<doi>` for a well-formed DOI (an optional `doi:` or resolver prefix is
* stripped); null when the text is not a DOI. Encoded per segment, the `/` kept.
*/
export function doiHref(raw: string): string | null {
const doi = raw.trim().replace(DOI_PREFIX, '')
if (!DOI_SHAPE.test(doi)) return null
return `https://doi.org/${doi.split('/').map(encodeURIComponent).join('/')}`
}
+16 -2
View File
@@ -1233,8 +1233,22 @@ export const en: Dict = {
'editor.references.cited_by': 'Cited by « {name} » ({count})',
'editor.references.show_all': 'Show all ({count})',
'editor.references.no_match': 'No reference matches.',
'editor.references.cited_one': 'cited {count} time',
'editor.references.cited_other': 'cited {count} times',
'editor.references.cited_one': 'Cited {count} time',
'editor.references.cited_other': 'Cited {count} times',
'editor.references.uncited': 'Not cited',
'editor.references.citers_one': 'Cited {count} time, by:',
'editor.references.citers_other': 'Cited {count} times, by:',
'editor.references.no_citers': 'No finding or family cites this reference.',
'editor.references.family': 'family',
'editor.references.go_to': 'Go to',
'editor.references.edit': 'Edit',
'editor.references.done': 'Done',
'editor.references.edit_title': 'Edit the reference',
'editor.references.url_label': 'URL',
'editor.references.none_doi': 'None',
'editor.references.none_url': 'None',
'editor.references.new_tab': '(new tab)',
'editor.references.delete_hint': "To delete this reference, first remove each of its citations: “Go to”, then “Remove” in the finding's or family's detail.",
'editor.findings.references_open_one': '{count} reference',
'editor.findings.references_open_other': '{count} references',
'editor.draft.loading': 'Loading the draft…',
+16 -2
View File
@@ -1264,8 +1264,22 @@ export const fr: Dict = {
'editor.references.cited_by': 'Citées par « {name} » ({count})',
'editor.references.show_all': 'Tout afficher ({count})',
'editor.references.no_match': 'Aucune référence ne correspond.',
'editor.references.cited_one': 'citée {count} fois',
'editor.references.cited_other': 'citée {count} fois',
'editor.references.cited_one': 'Citée {count} fois',
'editor.references.cited_other': 'Citée {count} fois',
'editor.references.uncited': 'Non citée',
'editor.references.citers_one': 'Citée {count} fois, par :',
'editor.references.citers_other': 'Citée {count} fois, par :',
'editor.references.no_citers': 'Aucun constat ni aucune famille ne cite cette référence.',
'editor.references.family': 'famille',
'editor.references.go_to': 'Aller à',
'editor.references.edit': 'Modifier',
'editor.references.done': 'Terminer',
'editor.references.edit_title': 'Modifier la référence',
'editor.references.url_label': 'URL',
'editor.references.none_doi': 'Aucun',
'editor.references.none_url': 'Aucune',
'editor.references.new_tab': '(nouvel onglet)',
'editor.references.delete_hint': 'Pour supprimer cette référence, retirez d\'abord chacune de ses citations : « Aller à », puis « Retirer » dans le détail du constat ou de la famille.',
'editor.findings.references_open_one': '{count} référence',
'editor.findings.references_open_other': '{count} références',
'editor.draft.loading': 'Chargement du brouillon…',
+23 -9
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { citationCounts } from '@/editor/references/citations'
import { citersOf } from '@/editor/references/citations'
import { edit, insert } from '../helpers/editorFixtures'
import { baseText } from '../helpers/editorHarness'
@@ -54,20 +54,34 @@ function citing(): AnatomicalSheetDocument {
return JSON.parse(text)
}
describe('citationCounts', () => {
it('counts the citers of a category and of nested nodes, zero when uncited', () => {
const counts = citationCounts(citing())
expect(counts.get('ref-a')).toBe(2)
expect(counts.get('ref-b')).toBe(1)
expect(counts.get('ref-none') ?? 0).toBe(0)
describe('citersOf', () => {
it('lists the citers of a category and of nested nodes, in document order', () => {
const citers = citersOf(citing())
const names = (id: string) => (citers.get(id) ?? []).map((c) => c.name.fr)
expect(names('ref-a')).toEqual(['Cat', 'Node'])
expect(names('ref-b')).toEqual(['Cat'])
expect(citers.get('ref-none')).toBeUndefined()
})
it('marks families and gives the trail from the zone', () => {
const [family, node] = citersOf(citing()).get('ref-a')!
expect(family.isFamily).toBe(true)
expect(family.trail.map((t) => t.fr)).toEqual(['Zone'])
expect(node.isFamily).toBe(false)
expect(node.trail.map((t) => t.fr)).toEqual(['Zone', 'Cat'])
expect(node.key).toEqual({
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
})
})
it('is memoised on the parsed document', () => {
const doc = citing()
expect(citationCounts(doc)).toBe(citationCounts(doc))
expect(citersOf(doc)).toBe(citersOf(doc))
})
it('is empty without findings', () => {
expect(citationCounts(JSON.parse(baseText())).size).toBe(0)
expect(citersOf(JSON.parse(baseText())).size).toBe(0)
})
})
@@ -328,8 +328,12 @@ describe('a field still focused while a place is left', () => {
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-ref-1-citation',
selector: '#tab-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2023' } })
@@ -347,7 +351,7 @@ describe('a field still focused while a place is left', () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
await openCitations(user)
const field = inPlace('citations').getByLabelText('Citation', {
selector: '#panel-reference-ref-1-citation',
selector: '#panel-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2021' } })
@@ -364,7 +368,7 @@ describe('a field still focused while a place is left', () => {
const user = await mount(findingsText(referenceText(), ['ref-1']))
await openCitations(user)
const field = inPlace('citations').getByLabelText('Citation', {
selector: '#panel-reference-ref-1-citation',
selector: '#panel-reference-0-ref-1-citation',
})
await user.click(field)
fireEvent.change(field, { target: { value: 'Doe 2022' } })
@@ -158,8 +158,8 @@ describe('citations panel opening', () => {
const chip = within(panel()).getByTestId('references-filter-chip')
expect(chip).toHaveTextContent('Citées par « Node A » (2)')
expect(cards()).toHaveLength(2)
expect(cards()[0].textContent).toContain('citée 2 fois')
expect(cards()[1].textContent).toContain('citée 1 fois')
expect(cards()[0].textContent).toContain('Citée 2 fois')
expect(cards()[1].textContent).toContain('Citée 1 fois')
})
it('has no search, no add form and no order buttons', async () => {
@@ -178,9 +178,9 @@ describe('citations panel opening', () => {
const user = await mount()
await openFromFinding(user)
expect(
panel().querySelector('#panel-reference-ref-a-citation'),
panel().querySelector('#panel-reference-0-ref-a-citation'),
).not.toBeNull()
expect(document.querySelector('#tab-reference-ref-a-citation')).toBeNull()
expect(document.querySelector('[id^="tab-reference-"]')).toBeNull()
})
it('« Tout afficher » closes the panel and shows the tab on its heading', async () => {
@@ -266,7 +266,7 @@ describe('closing and layout', () => {
const user = await mount()
await openFromFinding(user)
const field = within(panel()).getByLabelText('Citation', {
selector: '#panel-reference-ref-a-citation',
selector: '#panel-reference-0-ref-a-citation',
})
await user.clear(field)
await user.type(field, 'Neuf')
@@ -293,11 +293,13 @@ describe('ids', () => {
it('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)
const ids = [...document.querySelectorAll('[id]')].map((e) => e.id)
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([])
expect(ids).toContain('tab-reference-ref-a-citation')
expect(ids).toContain('panel-reference-ref-a-citation')
expect(ids).toContain('tab-reference-0-ref-a-citation')
expect(ids).toContain('panel-reference-0-ref-a-citation')
})
})
@@ -1,4 +1,4 @@
/** R2.1: the Références tab, the library (search, order, counts, add, « Aller à »). */
/** 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 {
cleanup,
@@ -8,6 +8,7 @@ import {
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReferenceFacts from '@/components/editor/references/ReferenceFacts'
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
import { useLocaleStore } from '@/state/localeStore'
import { targetOfKey } from '@/editor/navigation'
@@ -78,19 +79,48 @@ function sheetText(): string {
})
}
/** The sheet with a finding under « Cat A » that cites ref-a too (ref-a: two citers). */
function citedTwiceText(): string {
return edit(sheetText(), {
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'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
const ready = () =>
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
const tabPanel = () => screen.getByRole('tabpanel', { name: 'Références' })
const cards = () => within(tabPanel()).getAllByRole('listitem')
const header = (citation: string) =>
within(tabPanel()).getByRole('button', { name: new RegExp(`^${citation}`) })
const openAll = async (user: User) => {
for (const button of within(tabPanel()).getAllByRole('button', {
expanded: false,
})) {
if (button.hasAttribute('aria-controls')) await user.click(button)
}
}
const search = () =>
within(tabPanel()).getByRole('searchbox', {
name: 'Rechercher une référence',
})
type User = ReturnType<typeof userEvent.setup>
async function mount(width = 1280) {
serverHas(sheetText(), 3)
async function mount(width = 1280, text = citedTwiceText()) {
serverHas(text, 3)
const user = userEvent.setup()
mountDraft({ width })
await ready()
@@ -119,10 +149,11 @@ describe('the Références tab', () => {
it('each card says how often it is cited, the ids carry the tab prefix', async () => {
await mount()
const texts = cards().map((card) => card.textContent)
expect(texts[0]).toContain('citée 1 fois')
expect(texts[2]).toContain('citée 0 fois')
expect(texts[0]).toContain('Citée 2 fois')
expect(texts[1]).toContain('Citée 1 fois')
expect(texts[2]).toContain('Non citée')
expect(
tabPanel().querySelector('#tab-reference-ref-a-citation'),
tabPanel().querySelector('#tab-reference-0-ref-a-header'),
).not.toBeNull()
expect(
tabPanel().querySelector('#tab-reference-new-citation'),
@@ -146,8 +177,9 @@ describe('the Références tab', () => {
).toBeInTheDocument()
})
it('shows ↑ / ↓ only without a search', async () => {
it('shows ↑ / ↓ in open tiles, and only without a search', async () => {
const user = await mount()
await openAll(user)
expect(
within(tabPanel()).getAllByRole('button', { name: 'Descendre' }).length,
).toBe(3)
@@ -159,8 +191,12 @@ describe('the Références tab', () => {
it('Ctrl+Z reverts a reference edit', 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-ref-a-citation',
selector: '#tab-reference-0-ref-a-citation',
})
await user.clear(field)
await user.type(field, 'Neuf')
@@ -174,7 +210,8 @@ describe('the Références tab', () => {
describe('read-only modes', () => {
it('show no edit control, only the search', async () => {
await mount(800)
const user = await mount(800)
await openAll(user)
expect(
within(tabPanel()).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
@@ -188,11 +225,13 @@ describe('read-only modes', () => {
})
describe('« Aller à » a reference', () => {
it('clears the search that hides it and focuses its card', async () => {
it('clears the search that hides it, opens its tile and focuses its button', async () => {
serverHas(sheetText(), 3)
await openReady({ text: sheetText() })
const user = userEvent.setup()
const view = render(<ReferenceLibrary readOnly={false} />)
const view = render(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} />,
)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
@@ -202,12 +241,15 @@ describe('« Aller à » a reference', () => {
target: targetOfKey({ kind: 'reference', id: 'ref-a' }),
serial: 1,
}
view.rerender(<ReferenceLibrary readOnly={false} focus={focus} />)
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} focus={focus} />,
)
expect(box).toHaveValue('')
expect(screen.getAllByRole('listitem')).toHaveLength(3)
expect(document.querySelectorAll('button[aria-controls]')).toHaveLength(3)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
)
expect(document.activeElement).toHaveAttribute('aria-expanded', 'true')
})
})
@@ -215,17 +257,25 @@ 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(<ReferenceLibrary readOnly={false} resetSignal={0} />)
const view = render(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={0} />,
)
const box = screen.getByRole('searchbox', {
name: 'Rechercher une référence',
})
await user.type(box, 'Code')
view.rerender(<ReferenceLibrary readOnly={false} resetSignal={0} />)
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={0} />,
)
expect(box).toHaveValue('Code')
view.rerender(<ReferenceLibrary readOnly={false} resetSignal={1} />)
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={1} />,
)
expect(box).toHaveValue('')
await user.type(box, 'a')
view.rerender(<ReferenceLibrary readOnly={false} resetSignal={1} />)
view.rerender(
<ReferenceLibrary readOnly={false} navigate={vi.fn()} resetSignal={1} />,
)
expect(box).toHaveValue('a')
})
})
@@ -247,7 +297,7 @@ describe('adding a reference', () => {
await add(user)
expect(search()).toHaveValue('')
expect(cards()).toHaveLength(4)
expect(within(tabPanel()).getByText('Nouvelle source')).toBeInTheDocument()
expect(header('Nouvelle source')).toBeInTheDocument()
})
it('a refused add keeps the search', async () => {
@@ -259,3 +309,277 @@ describe('adding a reference', () => {
expect(search()).toHaveValue('Barone')
})
})
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. */
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
}
describe('the tile disclosure', () => {
it('opens and closes from the keyboard, and several stay open', async () => {
const user = await mount()
const first = header('Barone')
expect(first).toHaveAttribute('aria-expanded', 'false')
expect(first).toHaveAttribute('aria-controls', 'tab-reference-0-ref-a-body')
first.focus()
await user.keyboard('{Enter}')
expect(first).toHaveAttribute('aria-expanded', 'true')
header('Denoix').focus()
await user.keyboard(' ')
expect(first).toHaveAttribute('aria-expanded', 'true')
expect(header('Denoix')).toHaveAttribute('aria-expanded', 'true')
first.focus()
await user.keyboard('{Enter}')
expect(first).toHaveAttribute('aria-expanded', 'false')
expect(tabPanel().querySelector('#tab-reference-0-ref-a-body')).toBeNull()
})
it('is a natural tab stop that carries only the focus key', async () => {
await mount()
const button = header('Barone')
expect(button).not.toHaveAttribute('tabindex')
expect(button.closest('[data-focus-key]')).toBe(button)
})
})
describe('an open tile', () => {
it('shows type, DOI and URL as safe links, « Aucun » / « Aucune » when absent', async () => {
const user = await mount()
await user.click(header('Code rural'))
await user.click(header('Denoix'))
const doi = within(tile('Code rural')).getByRole('link', {
name: /10\.1000\/ABC/,
})
expect(doi).toHaveAttribute('href', 'https://doi.org/10.1000/ABC')
expect(doi).toHaveAttribute('target', '_blank')
expect(doi).toHaveAttribute('rel', 'noopener noreferrer')
expect(within(tile('Code rural')).getByText('Aucune')).toBeInTheDocument()
const url = within(tile('Denoix')).getByRole('link', {
name: /exemple\.org/,
})
expect(url).toHaveAttribute('href', 'https://exemple.org/%C3%89paule')
expect(within(tile('Denoix')).getByText('Aucun')).toBeInTheDocument()
})
it('lists the citers, a family marked, and the count is the list length', async () => {
const user = await mount()
await user.click(header('Barone'))
const open = within(tile('Barone'))
expect(open.getByText('Citée 2 fois, par :')).toBeInTheDocument()
expect(open.getAllByRole('button', { name: 'Aller à' })).toHaveLength(2)
expect(open.getAllByText('famille')).toHaveLength(1)
expect(open.getByText(/Zone A › Cat A ›/)).toBeInTheDocument()
})
it('says so when nothing cites it, and offers « Supprimer » only then', async () => {
const user = await mount()
await user.click(header('Barone'))
await user.click(header('Code rural'))
const cited = within(tile('Barone'))
expect(cited.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(
cited.getByText(/Pour supprimer cette référence/),
).toBeInTheDocument()
const uncited = within(tile('Code rural'))
expect(
uncited.getByText(
'Aucun constat ni aucune famille ne cite cette référence.',
),
).toBeInTheDocument()
expect(
uncited.getByRole('button', { name: 'Supprimer' }),
).toBeInTheDocument()
expect(uncited.queryByText(/Pour supprimer cette référence/)).toBeNull()
})
it('« Aller à » on a citer opens the Constats tab on it', async () => {
const user = await mount()
await user.click(header('Barone'))
const [family] = within(tile('Barone')).getAllByRole('button', {
name: 'Aller à',
})
await user.click(family)
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
'aria-selected',
'true',
)
})
it('never links a javascript: address', () => {
const risky = {
id: 'ref-x',
type: 'web',
citation: 'X',
url: 'javascript:alert(1)',
doi: 'javascript:alert(2)',
} as const
render(<ReferenceFacts reference={risky} />)
expect(screen.queryByRole('link')).toBeNull()
expect(screen.getByText('javascript:alert(1)')).toBeInTheDocument()
})
})
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)
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(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('read-only tiles', () => {
it('keep DOI, URL and « Aller à », and offer no edit control', async () => {
const user = await mount(800)
await user.click(header('Barone'))
await user.click(header('Denoix'))
const cited = within(tile('Barone'))
expect(cited.getAllByRole('button', { name: 'Aller à' })).toHaveLength(2)
expect(
within(tile('Denoix')).getByRole('link', { name: /exemple\.org/ }),
).toBeInTheDocument()
expect(
within(tabPanel()).queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(
within(tabPanel()).queryByRole('textbox', { name: 'Citation' }),
).toBeNull()
})
})
describe('reopening the editor', () => {
it('starts with every tile closed and none in edit', async () => {
const user = await mount()
await startEdit(user, 'Barone')
await user.click(header('Denoix'))
cleanup()
await mount()
const opened = within(tabPanel()).queryAllByRole('button', {
expanded: true,
})
expect(opened).toHaveLength(0)
expect(
within(tabPanel()).queryByLabelText('Citation', {
selector: '#tab-reference-0-ref-a-citation',
}),
).toBeNull()
})
})
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { doiHref, webHref } from '@/editor/references/safeLink'
const SEED_DOI = '10.1892/0891-6640(2002)016<0697:toih>2.3.co;2'
describe('doiHref', () => {
it('links a DOI to the resolver, encoded per segment with the slash kept', () => {
expect(doiHref('10.3389/fvets.2022.898096')).toBe(
'https://doi.org/10.3389/fvets.2022.898096',
)
expect(doiHref(SEED_DOI)).toBe(
'https://doi.org/10.1892/0891-6640(2002)016%3C0697%3Atoih%3E2.3.co%3B2',
)
})
it('strips a doi: or resolver prefix', () => {
const plain = 'https://doi.org/10.3389/fvets.2022.898096'
expect(doiHref('doi:10.3389/fvets.2022.898096')).toBe(plain)
expect(doiHref('DOI:10.3389/fvets.2022.898096')).toBe(plain)
expect(doiHref('https://doi.org/10.3389/fvets.2022.898096')).toBe(plain)
expect(doiHref('http://dx.doi.org/10.3389/fvets.2022.898096')).toBe(plain)
})
it('refuses what is not a DOI', () => {
expect(doiHref('')).toBeNull()
expect(doiHref('not a doi')).toBeNull()
expect(doiHref('10.12/short')).toBeNull()
expect(doiHref('10.3389/has space')).toBeNull()
expect(doiHref('javascript:alert(1)')).toBeNull()
})
})
describe('webHref', () => {
it('accepts http and https only', () => {
expect(webHref('https://exemple.org/a')).toBe('https://exemple.org/a')
expect(webHref(' http://exemple.org/a ')).toBe('http://exemple.org/a')
expect(webHref('javascript:alert(1)')).toBeNull()
expect(webHref('JAVASCRIPT:alert(1)')).toBeNull()
expect(webHref('data:text/html,x')).toBeNull()
expect(webHref('ftp://exemple.org/a')).toBeNull()
})
it('refuses a schemeless address and an empty one', () => {
expect(webHref('exemple.org/a')).toBeNull()
expect(webHref('')).toBeNull()
})
})
+20 -15
View File
@@ -65,7 +65,7 @@ describe('Références', () => {
expect(doc().references[0].id).toMatch(/^ref-[a-z2-7]{10}$/)
})
it('edits a field on blur and reorders with the arrows', async () => {
it('edits a field in a tile, applies it on blur, and reorders with the arrows', async () => {
const text = insert(
insert(baseText(), reference('ref-a', 'Alpha')),
reference('ref-b', 'Beta'),
@@ -73,18 +73,22 @@ describe('Références', () => {
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
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-ref-a-url',
selector: '#tab-reference-0-ref-a-url',
})
await user.type(url, 'https://example.org')
await user.tab()
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'])
expect(screen.getAllByRole('button', { name: 'Monter' })[0]).toBeDisabled()
})
it('a cited reference is refused with the citing findings listed; an uncited one is deleted', async () => {
it('a cited reference offers no deletion, only the hint; an uncited one is deleted', async () => {
let text = insert(
insert(baseText(), reference('ref-a', 'Alpha')),
reference('ref-b', 'Beta'),
@@ -112,25 +116,26 @@ describe('Références', () => {
await openReady({ text })
const user = userEvent.setup()
render(<ReferencesTab {...props} />)
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[0])
const refused = await screen.findByRole('dialog')
expect(within(refused).getByText(/cite cette référence/)).toBeTruthy()
expect(within(refused).getByText(/Boiterie/)).toBeTruthy()
await user.click(
within(refused).getAllByRole('button', { name: 'Fermer' }).at(-1)!,
)
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[1])
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()
expect(screen.getByText('Boiterie')).toBeTruthy()
await user.click(screen.getByRole('button', { name: /^Beta/ }))
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const asked = await screen.findByRole('dialog')
await user.click(within(asked).getByRole('button', { name: 'Supprimer' }))
expect(doc().references.map((r) => r.id)).toEqual(['ref-a'])
})
it('read-only shows the citations as text', async () => {
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(<ReferencesTab {...props} readOnly />)
expect(screen.getByText('Alpha')).toBeTruthy()
expect(screen.queryByRole('textbox')).toBeNull()
expect(screen.queryAllByRole('button')).toEqual([])
await user.click(screen.getByRole('button', { name: /^Alpha/ }))
expect(screen.getByText('Aucun')).toBeTruthy()
expect(screen.queryByRole('textbox', { name: 'Citation' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Modifier' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Supprimer' })).toBeNull()
})
})