diff --git a/apps/api/src/assignments/__tests__/assignments.controller.test.ts b/apps/api/src/assignments/__tests__/assignments.controller.test.ts index fb8d392e0..23767ebe6 100644 --- a/apps/api/src/assignments/__tests__/assignments.controller.test.ts +++ b/apps/api/src/assignments/__tests__/assignments.controller.test.ts @@ -138,7 +138,7 @@ describe('AssignmentsController', () => { await sendEmail({ language: 'en', recipient: 'p@x.org' }); expect(groupsService.findById).not.toHaveBeenCalled(); expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({ - links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }], + links: [{ expiresAt: assignment.expiresAt, url: assignment.url }], recipient: 'p@x.org', template: DEFAULT_ASSIGNMENT_EMAIL_TEMPLATE }); @@ -150,7 +150,7 @@ describe('AssignmentsController', () => { assignmentsService.findById.mockResolvedValueOnce({ ...assignment, groupId: null }); await sendEmail({ language: 'en', recipient: 'p@x.org' }); expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({ - links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }] + links: [{ expiresAt: assignment.expiresAt, url: assignment.url }] }); }); @@ -237,7 +237,17 @@ describe('AssignmentsController', () => { await sendEmail({ language: 'fr', recipient: 'p@x.org' }); expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({ language: 'fr', - links: [{ url: `${assignment.url}?lang=fr` }] + links: [{ url: assignment.url }] + }); + }); + + it('never re-points the link, so an email in another language cannot override what the link says', async () => { + assignmentsService.findById.mockResolvedValueOnce({ ...assignment, url: `${assignment.url}?lang=en` }); + groupsService.findById.mockResolvedValueOnce({ emailTemplates: [] }); + await sendEmail({ language: 'fr', recipient: 'p@x.org' }); + expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({ + language: 'fr', + links: [{ url: `${assignment.url}?lang=en` }] }); }); @@ -329,8 +339,8 @@ describe('AssignmentsController', () => { expect(mailService.sendAssignmentEmail).toHaveBeenCalledOnce(); expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({ links: [ - { expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }, - { expiresAt: second.expiresAt, url: `${second.url}?lang=en` } + { expiresAt: assignment.expiresAt, url: assignment.url }, + { expiresAt: second.expiresAt, url: second.url } ], recipient: 'p@x.org' }); diff --git a/apps/api/src/assignments/__tests__/assignments.service.test.ts b/apps/api/src/assignments/__tests__/assignments.service.test.ts index fdbe45413..7a9c828c4 100644 --- a/apps/api/src/assignments/__tests__/assignments.service.test.ts +++ b/apps/api/src/assignments/__tests__/assignments.service.test.ts @@ -388,6 +388,12 @@ describe('AssignmentsService', () => { expect(url).toBe(`http://localhost:3500/assignments/${id}`); }); + it('should open the participant link in the language chosen for the assignment', async () => { + await assignmentsService.create({ ...data(), language: 'fr' }, permissiveUser()); + const { id, url } = assignmentModel.create.mock.lastCall?.[0].data ?? {}; + expect(url).toBe(`http://localhost:3500/assignments/${id}?lang=fr`); + }); + it('should point the participant link at the gateway site address in production', async () => { await compile({ get: (key) => (key === 'NODE_ENV' ? 'production' : undefined), diff --git a/apps/api/src/assignments/assignments.controller.ts b/apps/api/src/assignments/assignments.controller.ts index eb218ccde..270600874 100644 --- a/apps/api/src/assignments/assignments.controller.ts +++ b/apps/api/src/assignments/assignments.controller.ts @@ -132,7 +132,7 @@ export class AssignmentsController { language, links: assignments.map((assignment) => ({ expiresAt: assignment.expiresAt, - url: `${assignment.url}?lang=${language}` + url: assignment.url })), recipient, template: await this.resolveTemplate(groupId ?? null, templateId, ability) @@ -156,7 +156,7 @@ export class AssignmentsController { const assignment = await this.assignmentsService.findById(id, { ability }); const result = await this.mailService.sendAssignmentEmail({ language, - links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=${language}` }], + links: [{ expiresAt: assignment.expiresAt, url: assignment.url }], recipient, template: await this.resolveTemplate(assignment.groupId ?? null, templateId, ability) }); diff --git a/apps/api/src/assignments/assignments.service.ts b/apps/api/src/assignments/assignments.service.ts index 5f29c30ce..554aebf11 100644 --- a/apps/api/src/assignments/assignments.service.ts +++ b/apps/api/src/assignments/assignments.service.ts @@ -15,6 +15,7 @@ import type { BulkAssignmentIssue, BulkAssignmentPreflightResult } from '@opendatacapture/schemas/assignment'; +import type { Language } from '@opendatacapture/schemas/core'; import { AuditLogger } from '@/audit/audit.logger'; import { accessibleQuery, forcedAppSubject } from '@/auth/ability.utils'; @@ -76,7 +77,7 @@ export class AssignmentsService { } async create( - { expiresAt, groupId, instrumentId, redirectUrl, subjectId }: $CreateAssignmentData, + { expiresAt, groupId, instrumentId, language, redirectUrl, subjectId }: $CreateAssignmentData, currentUser: RequestUser ): Promise { if (groupId) { @@ -96,6 +97,7 @@ export class AssignmentsService { expiresAt, groupId, instrumentId, + language, redirectUrl, subjectId }); @@ -350,17 +352,20 @@ export class AssignmentsService { expiresAt, groupId, instrumentId, + language, redirectUrl, subjectId }: { expiresAt: Date; groupId?: null | string; instrumentId: string; + language?: Language; redirectUrl?: string; subjectId: string; }): Promise<{ assignment: Assignment; publicKey: webcrypto.CryptoKey }> { const { privateKey, publicKey } = await HybridCrypto.generateKeyPair(); const id = crypto.randomUUID(); + const link = `${this.assignmentBaseUrl}/assignments/${id}`; const assignment = await this.assignmentModel.create({ data: { encryptionKeyPair: { @@ -374,7 +379,10 @@ export class AssignmentsService { redirectUrl, status: 'OUTSTANDING', subject: { connect: { id: subjectId } }, - url: `${this.assignmentBaseUrl}/assignments/${id}` + // The language is named on the link only when the assignment is created: a link left + // without one is one the subject's own browser decides, and nothing later — an email + // written in another language included — overrides that. + url: language ? `${link}?lang=${language}` : link } }); return { assignment, publicKey }; diff --git a/apps/gateway/src/lib/__tests__/setup-state.test.ts b/apps/gateway/src/lib/__tests__/setup-state.test.ts index cbf0179b8..ac2da2bb7 100644 --- a/apps/gateway/src/lib/__tests__/setup-state.test.ts +++ b/apps/gateway/src/lib/__tests__/setup-state.test.ts @@ -36,4 +36,59 @@ describe('resolveLanguage', () => { updateSetupState({ activeLanguages: ['en', 'fr'] }); expect(resolveLanguage(['fr', 'en'])).toBe('en'); }); + + it('should open a link with no language in the language the browser asks for', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'fr-CA,fr;q=0.9,en;q=0.8')).toBe('fr'); + }); + + it('should fall back to the browser for a link pinned to a language the instance has since turned off', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage('es', 'fr-CA,fr;q=0.9')).toBe('fr'); + }); + + it('should prefer the language the link names over the one the browser asks for', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage('en', 'fr-CA,fr;q=0.9')).toBe('en'); + }); + + it('should take the most wanted language the instance has active, not merely the first listed', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'de;q=0.9,fr;q=0.8,en;q=0.7')).toBe('fr'); + }); + + it('should order by quality rather than by the order the header lists them', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'en;q=0.3,fr;q=0.9')).toBe('fr'); + }); + + it('should ignore a language the browser explicitly refuses with q=0', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'fr;q=0,en;q=0.5')).toBe('en'); + }); + + it('should fall back to the first active language when the browser asks for none it has', () => { + updateSetupState({ activeLanguages: ['fr', 'en'] }); + expect(resolveLanguage(undefined, 'de,it')).toBe('fr'); + }); + + it('should fall back to the first active language for a header it cannot read', () => { + updateSetupState({ activeLanguages: ['fr', 'en'] }); + expect(resolveLanguage(undefined, ';;;')).toBe('fr'); + }); + + it('should treat an unreadable quality as the strongest preference, since the language was still named', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'fr;q=high,en;q=0.9')).toBe('fr'); + }); + + it('should treat a quality of punctuation alone as the strongest preference rather than dropping the language', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'fr;q=.,en;q=0.9')).toBe('fr'); + }); + + it('should read a quality the client spells with a capital Q, which HTTP allows', () => { + updateSetupState({ activeLanguages: ['en', 'fr'] }); + expect(resolveLanguage(undefined, 'fr;Q=0.1,en;Q=0.9')).toBe('en'); + }); }); diff --git a/apps/gateway/src/lib/setup-state.ts b/apps/gateway/src/lib/setup-state.ts index cdf6cb818..65198fa70 100644 --- a/apps/gateway/src/lib/setup-state.ts +++ b/apps/gateway/src/lib/setup-state.ts @@ -1,7 +1,31 @@ -import { $Language, DEFAULT_ACTIVE_LANGUAGES, resolveActiveLanguage } from '@opendatacapture/schemas/core'; +import { $Language, DEFAULT_ACTIVE_LANGUAGES } from '@opendatacapture/schemas/core'; import type { ActiveLanguages, Language } from '@opendatacapture/schemas/core'; import type { RemoteSetupState } from '@opendatacapture/schemas/gateway'; +/** + * The languages an `Accept-Language` header asks for, most wanted first. + * + * Only the base language is kept, so `fr-CA` counts as a request for French, and a tag with `q=0` + * is dropped because that is how a client says it does not want one. An unreadable quality is + * treated as the default of 1 rather than discarded, since a client that sends one still wants the + * language it named. A parameter name is matched either case, as HTTP does not distinguish them. + */ +const parseAcceptLanguage = (header: string): string[] => { + return header + .split(',') + .map((part) => { + const [tag = '', ...parameters] = part.trim().split(';'); + const quality = parameters + .map((parameter) => /^\s*q=(?[\d.]+)\s*$/iu.exec(parameter)?.groups?.value) + .find((value) => value !== undefined); + const parsedQuality = quality === undefined ? 1 : Number.parseFloat(quality); + return { quality: Number.isNaN(parsedQuality) ? 1 : parsedQuality, tag: tag.trim() }; + }) + .filter(({ quality, tag }) => tag.length > 0 && quality > 0) + .sort((a, b) => b.quality - a.quality) + .map(({ tag }) => tag.split('-')[0]!.toLowerCase()); +}; + /** * The setup state of the instance this gateway serves, as last pushed by `apps/api`. * @@ -18,16 +42,24 @@ export function getActiveLanguages(): ActiveLanguages { /** * The language to render a page in: the one a `?lang=` query asks for when the instance offers it, - * otherwise the first active language. Resolved server-side rather than from `window.location` so - * the SSR pass and the hydration pass agree; anything else renders the page in English and then - * swaps it. + * otherwise the first language the reader's browser asks for that the instance offers, and failing + * both the first active language. Resolved server-side rather than from `window.location` or + * `navigator` so the SSR pass and the hydration pass agree; anything else renders the page in one + * language and then swaps it. + * + * A link created without a language is the common case — an assignment is assigned before anyone + * knows what the subject reads — so the header is what makes that link open in their own language. */ -export function resolveLanguage(requested: unknown): Language { +export function resolveLanguage(requested: unknown, acceptLanguage?: string): Language { const activeLanguages = getActiveLanguages(); const requestedLanguage = $Language.safeParse(requested); - return requestedLanguage.success - ? resolveActiveLanguage(requestedLanguage.data, activeLanguages) - : activeLanguages[0]; + if (requestedLanguage.success && activeLanguages.includes(requestedLanguage.data)) { + return requestedLanguage.data; + } + const accepted = parseAcceptLanguage(acceptLanguage ?? '') + .map((tag) => $Language.safeParse(tag)) + .find((parsed) => parsed.success && activeLanguages.includes(parsed.data)); + return accepted?.success ? accepted.data : activeLanguages[0]; } export function updateSetupState(state: RemoteSetupState): void { diff --git a/apps/gateway/src/routers/__tests__/root.router.test.ts b/apps/gateway/src/routers/__tests__/root.router.test.ts index 84af7aa16..557c3e0d9 100644 --- a/apps/gateway/src/routers/__tests__/root.router.test.ts +++ b/apps/gateway/src/routers/__tests__/root.router.test.ts @@ -40,8 +40,8 @@ function storeAssignment(stored: { }); } -async function getRootProps(path: string): Promise { - const response = await fetch(`${baseUrl}${path}`); +async function getRootProps(path: string, headers?: { [key: string]: string }): Promise { + const response = await fetch(`${baseUrl}${path}`, { headers }); return response.json(); } @@ -111,6 +111,19 @@ describe('rootRouter', () => { }); }); + it('should open a link with no language in the language the browser asks for, which is how most links are created', async () => { + storeAssignment({}); + expect( + await getRootProps('/assignments/assignment-1', { 'accept-language': 'fr-CA,fr;q=0.9,en;q=0.8' }) + ).toMatchObject({ language: 'fr' }); + }); + + it('should name Accept-Language as what the page varies on, so a shared cache cannot serve one subject the language of another', async () => { + storeAssignment({}); + const response = await fetch(`${baseUrl}/assignments/assignment-1`); + expect(response.headers.get('vary')).toBe('Accept-Language'); + }); + it('should hand the page the redirect URL the assignment was created with, so it can send the subject on', async () => { storeAssignment({ redirectUrl: 'https://example.com/done' }); expect(await getRootProps('/assignments/assignment-1')).toMatchObject({ diff --git a/apps/gateway/src/routers/root.router.ts b/apps/gateway/src/routers/root.router.ts index 10d38e56c..bb80a5830 100644 --- a/apps/gateway/src/routers/root.router.ts +++ b/apps/gateway/src/routers/root.router.ts @@ -50,12 +50,12 @@ router.get( id, initialSeriesIndex, kind: 'assignment', - language: resolveLanguage(req.query.lang), + language: resolveLanguage(req.query.lang, req.headers['accept-language']), redirectUrl: assignment.redirectUrl ?? undefined, target: targetParseResult.data, token } satisfies RootProps); - res.status(200).set({ 'Content-Type': 'text/html' }).end(html); + res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html); }) ); @@ -63,9 +63,9 @@ router.get('/', (req, res) => { const html = res.locals.loadRoot({ activeLanguages: getActiveLanguages(), kind: 'landing', - language: resolveLanguage(req.query.lang) + language: resolveLanguage(req.query.lang, req.headers['accept-language']) } satisfies RootProps); - res.status(200).set({ 'Content-Type': 'text/html' }).end(html); + res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html); }); export { router as rootRouter }; diff --git a/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx new file mode 100644 index 000000000..823e14603 --- /dev/null +++ b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx @@ -0,0 +1,55 @@ +import { Label, Select } from '@douglasneuroinformatics/libui/components'; +import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import { $Language } from '@opendatacapture/schemas/core'; +import type { Language } from '@opendatacapture/schemas/core'; + +import type { AdministrationChoice } from '@/utils/administration-choice'; +import { LANGUAGE_LABELS } from '@/utils/language'; + +/** Stands in for "no language", which a Select cannot hold as a value of its own. */ +const AUTOMATIC = '__automatic__'; + +type AdministrationOptionsProps = { + choice: AdministrationChoice; + onLanguageChange: (language: Language | undefined) => void; +}; + +/** + * The language a remote assignment opens in. The default leaves it unset, so the gateway opens the + * link in whatever language the subject's browser asks for; picking one pins the link to it. + */ +export const AdministrationOptions = ({ choice, onLanguageChange }: AdministrationOptionsProps) => { + const { t } = useTranslation(); + if (choice.languageOptions.length < 2) { + return null; + } + return ( +
+ + +
+ ); +}; diff --git a/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx new file mode 100644 index 000000000..bc6544ace --- /dev/null +++ b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx @@ -0,0 +1,63 @@ +import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { AdministrationOptions } from '../AdministrationOptions'; + +import '@/services/i18n'; + +const instrument = { details: { title: 'Scale' }, id: 'scale', kind: 'FORM' } as unknown as TranslatedInstrumentInfo; + +const renderOptions = ( + choice: Partial[0]['choice']>, + onLanguageChange = vi.fn() +) => { + render( + + ); + return onLanguageChange; +}; + +const chooseOption = (name: string) => { + fireEvent.click(screen.getByTestId('administration-language')); + fireEvent.click(screen.getByRole('option', { name })); +}; + +describe('AdministrationOptions', () => { + afterEach(cleanup); + + it('should offer the languages of an instrument that has more than one', () => { + renderOptions({ languageOptions: ['en', 'fr'] }); + expect(screen.getByTestId('administration-language')).toBeTruthy(); + }); + + it('should leave out the language dropdown when there is only one language to choose', () => { + renderOptions({ languageOptions: ['en'] }); + expect(screen.queryByTestId('administration-language')).toBeNull(); + }); + + it('should leave out the language dropdown when no allowed language is offered, rather than offer an empty one', () => { + renderOptions({ language: undefined, languageOptions: [] }); + expect(screen.queryByTestId('administration-language')).toBeNull(); + }); + + it('should leave the language to the browser by default, which is what no choice means', () => { + renderOptions({ languageOptions: ['en', 'fr'] }); + expect(screen.getByTestId('administration-language').textContent).toBe("The subject's browser language"); + }); + + it('should pin the link to a language the user picks', () => { + const onLanguageChange = renderOptions({ languageOptions: ['en', 'fr'] }); + chooseOption('French'); + expect(onLanguageChange).toHaveBeenCalledWith('fr'); + }); + + it('should hand back no language when the browser option is picked again', () => { + const onLanguageChange = renderOptions({ language: 'fr', languageOptions: ['en', 'fr'] }); + chooseOption("The subject's browser language"); + expect(onLanguageChange).toHaveBeenCalledWith(undefined); + }); +}); diff --git a/apps/web/src/components/AdministrationOptions/index.ts b/apps/web/src/components/AdministrationOptions/index.ts new file mode 100644 index 000000000..67687f6a5 --- /dev/null +++ b/apps/web/src/components/AdministrationOptions/index.ts @@ -0,0 +1 @@ +export * from './AdministrationOptions'; diff --git a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx index cd80fffd4..b6f709442 100644 --- a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx +++ b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx @@ -12,25 +12,31 @@ import { useGroupQuery } from '@/hooks/useGroupQuery'; import { useMailErrorMessage } from '@/hooks/useMailErrorMessage'; import { useSendAssignmentEmailMutation } from '@/hooks/useSendAssignmentEmailMutation'; import { useSetupStateQuery } from '@/hooks/useSetupStateQuery'; +import { getLinkLanguage } from '@/utils/assignment-link'; import { sendableLanguages } from '@/utils/language'; +import { ConfirmEmailLanguageDialog } from './ConfirmEmailLanguageDialog'; + const DEFAULT_TEMPLATE_OPTION = '__default__'; export type AssignmentEmailFormProps = { assignment: Assignment | null; + /** The email language to start from; defaults to the interface language. Read once, on mount. */ + initialLanguage?: Language; instrumentLanguages?: string[]; }; -export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: AssignmentEmailFormProps) => { +export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLanguages }: AssignmentEmailFormProps) => { const { resolvedLanguage, t } = useTranslation(); const setupStateQuery = useSetupStateQuery(); const sendEmailMutation = useSendAssignmentEmailMutation(); const addNotification = useNotificationsStore((store) => store.addNotification); const mailErrorMessage = useMailErrorMessage(); const [recipient, setRecipient] = useState(''); - const [languageChoice, setLanguageChoice] = useState(resolvedLanguage); + const [languageChoice, setLanguageChoice] = useState(initialLanguage ?? resolvedLanguage); const [templateChoice, setTemplateChoice] = useState(null); const [feedback, setFeedback] = useState(null); + const [isConfirmingLanguage, setIsConfirmingLanguage] = useState(false); // The server resolves the template from the assignment's own group, so this must query that // group rather than whichever one is currently selected in the app store - on the datahub they @@ -63,10 +69,19 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm // leave the trigger showing a value with no matching item while a different one is posted. const language = languageOptions.includes(languageChoice) ? languageChoice : (languageOptions[0] ?? 'en'); + // The link's own language, which the email's does not have to match — so it is worth confirming, + // but only where the sender could pick it: a template authored in neither of the link's languages + // leaves them nothing to resolve, and a warning they can only override is a warning they learn to + // ignore. + const pinnedLinkLanguage = assignment ? getLinkLanguage(assignment.url) : undefined; + const linkLanguage = + pinnedLinkLanguage && languageOptions.includes(pinnedLinkLanguage) ? pinnedLinkLanguage : undefined; + const handleSendEmail = () => { if (!assignment || !recipient) { return; } + setIsConfirmingLanguage(false); setFeedback(null); const fail = (message: string) => { setFeedback({ message, tone: 'error' }); @@ -154,11 +169,10 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm

- {/* Only the email is localized: the gateway does not read the link's `lang` param. */} {t({ - en: 'The email is sent in the selected language when the template has been written in it. Participants choose their own language when they open the assignment.', - es: 'El correo se envía en el idioma seleccionado cuando la plantilla se ha redactado en ese idioma. Los participantes eligen su propio idioma al abrir la tarea.', - fr: "Le courriel est envoyé dans la langue sélectionnée lorsque le modèle a été rédigé dans celle-ci. Les participants choisissent leur propre langue à l'ouverture de l'évaluation." + en: 'The email is sent in the selected language when the template has been written in it. The link opens in the language the assignment was created in, whatever language the email is sent in.', + es: 'El correo se envía en el idioma seleccionado cuando la plantilla se ha redactado en ese idioma. El enlace se abre en el idioma en que se creó la tarea, sea cual sea el idioma del correo.', + fr: "Le courriel est envoyé dans la langue sélectionnée lorsque le modèle a été rédigé dans celle-ci. Le lien s'ouvre dans la langue de création de la tâche, quelle que soit la langue du courriel." })}

@@ -203,7 +217,13 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm disabled={!recipient || sendEmailMutation.isPending || groupQuery.isLoading} type="button" variant="primary" - onClick={handleSendEmail} + onClick={() => { + if (linkLanguage && linkLanguage !== language) { + setIsConfirmingLanguage(true); + return; + } + handleSendEmail(); + }} > {sendEmailMutation.isPending ? t({ en: 'Sending…', es: 'Enviando…', fr: 'Envoi en cours…' }) @@ -222,6 +242,15 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm {feedback.message}

)} + {linkLanguage && isConfirmingLanguage && ( + + )} ); }; diff --git a/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx new file mode 100644 index 000000000..ba7ddf86e --- /dev/null +++ b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx @@ -0,0 +1,61 @@ +import { Button, Dialog } from '@douglasneuroinformatics/libui/components'; +import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import type { Language } from '@opendatacapture/schemas/core'; + +import { LANGUAGE_LABELS } from '@/utils/language'; + +export type ConfirmEmailLanguageDialogProps = { + /** The language the email will be written in. */ + emailLanguage: Language; + isPending: boolean; + /** The language the assignment link opens the instrument in. */ + linkLanguage: Language; + onConfirm: () => void; + onOpenChange: (open: boolean) => void; +}; + +/** + * Asks before sending an email written in one language for a link that opens in another. The two + * are set separately and nothing else in the app shows them side by side, so the mismatch is easy + * to create and invisible until the subject opens the link. + * + * Rendered only while confirming, so it needs no closed state of its own. + */ +export const ConfirmEmailLanguageDialog = ({ + emailLanguage, + isPending, + linkLanguage, + onConfirm, + onOpenChange +}: ConfirmEmailLanguageDialogProps) => { + const { t } = useTranslation(); + return ( + + + + + {t({ en: 'Languages do not match', es: 'Los idiomas no coinciden', fr: 'Langues différentes' })} + + + + {t( + { + en: 'This email will be written in {}, but the link opens the instrument in {}. Send it anyway?', + es: 'Este correo se escribirá en {}, pero el enlace abre el instrumento en {}. ¿Enviarlo de todos modos?', + fr: "Ce courriel sera rédigé en {}, mais le lien ouvre l'instrument en {}. L'envoyer quand même ?" + }, + { args: [t(LANGUAGE_LABELS[emailLanguage]), t(LANGUAGE_LABELS[linkLanguage])] } + )} + + + + + + + + ); +}; diff --git a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx index 0f857112c..2edaf5355 100644 --- a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx +++ b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx @@ -329,4 +329,71 @@ describe('AssignmentEmailForm', () => { submit('q@x.org'); expect(screen.queryByTestId('assignment-email-feedback')).toBeNull(); }); + + describe('a link pinned to a language', () => { + const pinnedAssignment: Assignment = { ...assignment, url: `${assignment.url}?lang=fr` }; + + const chooseEmailLanguage = (name: string) => { + fireEvent.click(screen.getByTestId('assignment-language')); + fireEvent.click(screen.getByRole('option', { name })); + }; + + it('sends without asking when the email is in the language the link opens in', () => { + render(); + submit('p@x.org'); + expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull(); + expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'fr' }), expect.anything()); + }); + + it('asks before sending an email in a language the link does not open in', () => { + render(); + chooseEmailLanguage('English'); + submit('p@x.org'); + expect(screen.getByTestId('confirm-email-language-dialog')).toBeTruthy(); + expect(mocks.sendEmail).not.toHaveBeenCalled(); + }); + + it('names both languages, so the sender can see which is which', () => { + render(); + chooseEmailLanguage('English'); + submit('p@x.org'); + expect(screen.getByTestId('confirm-email-language-dialog').textContent).toContain( + 'written in English, but the link opens the instrument in French' + ); + }); + + it('sends once the mismatch is confirmed', () => { + render(); + chooseEmailLanguage('English'); + submit('p@x.org'); + fireEvent.click(screen.getByTestId('confirm-email-language')); + expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'en' }), expect.anything()); + }); + + // Otherwise the warning fires on every send with nothing the sender can do but override it, + // which is how a warning stops being read. + it('asks nothing when no template is authored in the language the link opens in, since there is nothing to resolve', () => { + mockGroup('tpl-en', [englishTemplate]); + render(); + submit('p@x.org'); + expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull(); + expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'en' }), expect.anything()); + }); + + it('sends nothing when the mismatch is dismissed', () => { + render(); + chooseEmailLanguage('English'); + submit('p@x.org'); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull(); + expect(mocks.sendEmail).not.toHaveBeenCalled(); + }); + }); + + it('asks nothing of a link with no language, which the browser that opens it decides', () => { + render(); + submit('p@x.org'); + expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull(); + expect(mocks.sendEmail).toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/components/InstrumentCard/InstrumentCard.tsx b/apps/web/src/components/InstrumentCard/InstrumentCard.tsx index 8800daa34..d1b54e6e1 100644 --- a/apps/web/src/components/InstrumentCard/InstrumentCard.tsx +++ b/apps/web/src/components/InstrumentCard/InstrumentCard.tsx @@ -1,13 +1,16 @@ import React from 'react'; -import { Card, Heading, Tooltip } from '@douglasneuroinformatics/libui/components'; +import { Card, Heading, Label, Tooltip } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { cn } from '@douglasneuroinformatics/libui/utils'; import { licenses } from '@opendatacapture/licenses'; import { InstrumentIcon } from '@opendatacapture/react-core'; +import type { Language } from '@opendatacapture/schemas/core'; import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; import { BadgeAlertIcon, BadgeCheckIcon } from 'lucide-react'; +import { LanguageSelect } from '../LanguageSelect'; + type BaseCardItem = { label: string; tooltip?: React.ReactNode }; type LinkCardItem = BaseCardItem & { href?: null | string; kind: 'link' }; @@ -19,12 +22,30 @@ type CardItem = LinkCardItem | TextCardItem; type InstrumentCardProps = { highlighted?: boolean; instrument: TranslatedInstrumentInfo; + /** The language the card will be opened in, where the card offers a choice of them. */ + language?: Language; + /** The languages to offer; the dropdown replaces the static list only when there are two or more. */ + languageOptions?: Language[]; onClick: () => void; + onLanguageChange?: (language: Language) => void; }; -export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentCardProps) => { +export const InstrumentCard = ({ + highlighted, + instrument, + language, + languageOptions, + onClick, + onLanguageChange +}: InstrumentCardProps) => { const { t } = useTranslation(); + // Narrowed once, so the dropdown's own props need no assertions. + const languageSelect = + language && onLanguageChange && languageOptions && languageOptions.length > 1 + ? { onLanguageChange, options: languageOptions, value: language } + : null; + const license = licenses.get(instrument.details.license); const content: CardItem[] = [ @@ -62,16 +83,18 @@ export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentC es: 'Idiomas', fr: 'Langues' }), - text: instrument.supportedLanguages - .map((language) => { - switch (language) { - case 'en': - return 'English'; - case 'fr': - return 'Français'; - } - }) - .join(', ') + text: languageSelect + ? undefined + : instrument.supportedLanguages + .map((supported) => { + switch (supported) { + case 'en': + return 'English'; + case 'fr': + return 'Français'; + } + }) + .join(', ') }, { kind: 'text', @@ -178,6 +201,22 @@ export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentC ); })} + {languageSelect && ( +
+ + event.stopPropagation()} + onKeyDown={(event) => event.stopPropagation()} + /> +
+ )} diff --git a/apps/web/src/components/InstrumentShowcase/InstrumentShowcase.tsx b/apps/web/src/components/InstrumentShowcase/InstrumentShowcase.tsx index 2e6b0025a..c6596ad7e 100644 --- a/apps/web/src/components/InstrumentShowcase/InstrumentShowcase.tsx +++ b/apps/web/src/components/InstrumentShowcase/InstrumentShowcase.tsx @@ -3,9 +3,12 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ListboxDropdown, SearchBar } from '@douglasneuroinformatics/libui/components'; import type { ListboxDropdownOption } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import type { Language } from '@opendatacapture/schemas/core'; import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; import { AnimatePresence, motion } from 'motion/react'; +import { getAdministrationChoice } from '@/utils/administration-choice'; + import { InstrumentCard } from '../InstrumentCard'; import { InstrumentKindDropdown } from './InstrumentKindDropdown'; import { InstrumentLanguageDropdown } from './InstrumentLanguageDropdown'; @@ -13,11 +16,17 @@ import { InstrumentLanguageDropdown } from './InstrumentLanguageDropdown'; import type { InstrumentShowcaseKindOption } from './InstrumentKindDropdown'; import type { InstrumentShowcaseLanguageOption } from './InstrumentLanguageDropdown'; +/** + * The instruments a user may pick. Given `allowedLanguages`, each card offers the languages it may + * be opened in — narrowed to those — and hands the chosen one to `onSelect`, so a choice costs the + * user no extra step. Without them no card offers a language and `onSelect` receives none. + */ export const InstrumentShowcase: React.FC<{ + allowedLanguages?: readonly Language[]; data: TranslatedInstrumentInfo[]; - onSelect: (instrument: TranslatedInstrumentInfo) => void; -}> = ({ data: availableInstruments, onSelect }) => { - const { t } = useTranslation(); + onSelect: (instrument: TranslatedInstrumentInfo, language?: Language) => void; +}> = ({ allowedLanguages, data: availableInstruments, onSelect }) => { + const { resolvedLanguage, t } = useTranslation(); const [filteredInstruments, setFilteredInstruments] = useState( availableInstruments.toSorted((a, b) => a.details.title.localeCompare(b.details.title)) ); @@ -26,8 +35,23 @@ export const InstrumentShowcase: React.FC<{ const [selectedTags, setSelectedTags] = useState([]); const [searchTerm, setSearchTerm] = useState(''); const [highlightedIndex, setHighlightedIndex] = useState(0); + const [chosenLanguages, setChosenLanguages] = useState<{ [instrumentId: string]: Language }>({}); const listRef = useRef(null); + const languageChoice = useCallback( + (instrument: TranslatedInstrumentInfo) => { + if (!allowedLanguages) { + return null; + } + const { language, languageOptions } = getAdministrationChoice(instrument, { + allowedLanguages, + preferredLanguage: resolvedLanguage + }); + return { language: chosenLanguages[instrument.id] ?? language, languageOptions }; + }, + [allowedLanguages, chosenLanguages, resolvedLanguage] + ); + useEffect(() => { const updatedFilteredInstruments = availableInstruments.filter(({ details, kind, supportedLanguages, tags }) => { if (selectedKinds.length && !selectedKinds.some(({ key }) => key === kind)) { @@ -71,7 +95,7 @@ export const InstrumentShowcase: React.FC<{ event.preventDefault(); const instrument = filteredInstruments[highlightedIndex]; if (instrument) { - onSelect(instrument); + onSelect(instrument, languageChoice(instrument)?.language); } return; } @@ -86,7 +110,7 @@ export const InstrumentShowcase: React.FC<{ setHighlightedIndex((prev) => Math.max(prev - 1, 0)); } }, - [filteredInstruments, highlightedIndex, onSelect] + [filteredInstruments, highlightedIndex, languageChoice, onSelect] ); return ( @@ -125,6 +149,7 @@ export const InstrumentShowcase: React.FC<{
    {filteredInstruments.map((instrument, i) => { + const choice = languageChoice(instrument); return ( onSelect(instrument)} + language={choice?.language} + languageOptions={choice?.languageOptions} + onClick={() => onSelect(instrument, choice?.language)} + onLanguageChange={(language) => { + setChosenLanguages((previous) => ({ ...previous, [instrument.id]: language })); + }} /> ); diff --git a/apps/web/src/components/InstrumentShowcase/__tests__/InstrumentShowcase.test.tsx b/apps/web/src/components/InstrumentShowcase/__tests__/InstrumentShowcase.test.tsx index 8c3cc32b8..cb1395cf2 100644 --- a/apps/web/src/components/InstrumentShowcase/__tests__/InstrumentShowcase.test.tsx +++ b/apps/web/src/components/InstrumentShowcase/__tests__/InstrumentShowcase.test.tsx @@ -1,4 +1,5 @@ import { i18n } from '@douglasneuroinformatics/libui/i18n'; +import type { Language } from '@opendatacapture/schemas/core'; import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MotionGlobalConfig } from 'motion/react'; @@ -65,6 +66,13 @@ const renderShowcase = (data: TranslatedInstrumentInfo[] = instruments) => { return onSelect; }; +/** The showcase offers a language per card only when it is told which languages are allowed. */ +const renderWithLanguages = (allowedLanguages: Language[], data: TranslatedInstrumentInfo[] = instruments) => { + const onSelect = vi.fn(); + render(); + return onSelect; +}; + const cardIds = () => { return screen.getAllByTestId(/^instrument-card-/).map((card) => card.dataset.testid?.replace('instrument-card-', '')); }; @@ -144,7 +152,7 @@ describe('InstrumentShowcase', () => { it('should select an instrument when its card is clicked', () => { const onSelect = renderShowcase(); fireEvent.click(screen.getByTestId('instrument-card-gamma')); - expect(onSelect).toHaveBeenCalledWith(gamma); + expect(onSelect).toHaveBeenCalledWith(gamma, undefined); }); it('should keep only the instruments whose title matches the search, ignoring case', async () => { @@ -254,7 +262,7 @@ describe('InstrumentShowcase', () => { const onSelect = renderShowcase(); pressKey('ArrowDown'); pressKey('Enter'); - expect(onSelect).toHaveBeenCalledWith(beta); + expect(onSelect).toHaveBeenCalledWith(beta, undefined); }); it('should move the highlight back to the first match when the search changes', async () => { @@ -271,4 +279,56 @@ describe('InstrumentShowcase', () => { pressKey('ArrowDown'); expect(scrollIntoView.mock.contexts.at(-1)).toBe(screen.getByTestId('instrument-card-beta').closest('li')); }); + + it('should offer no language on a card when no allowed languages are given', () => { + const onSelect = renderShowcase(); + expect(screen.queryByTestId('instrument-language-beta')).toBeNull(); + fireEvent.click(screen.getByTestId('instrument-card-beta')); + expect(onSelect).toHaveBeenCalledWith(beta, undefined); + }); + + it('should offer the languages a card may be opened in, defaulting to the interface language', () => { + renderWithLanguages(['en', 'fr']); + expect(screen.getByTestId('instrument-language-beta').textContent).toBe('English'); + }); + + it('should leave the dropdown off a card with only one language to offer', () => { + renderWithLanguages(['en']); + expect(screen.queryByTestId('instrument-language-beta')).toBeNull(); + }); + + it('should open the card in the language it was left on, rather than asking again', () => { + const onSelect = renderWithLanguages(['en', 'fr']); + fireEvent.click(screen.getByTestId('instrument-language-beta')); + fireEvent.click(screen.getByRole('option', { name: 'French' })); + fireEvent.click(screen.getByTestId('instrument-card-beta')); + expect(onSelect).toHaveBeenCalledWith(beta, 'fr'); + }); + + it('should not open the instrument when the language dropdown itself is clicked', () => { + const onSelect = renderWithLanguages(['en', 'fr']); + fireEvent.click(screen.getByTestId('instrument-language-beta')); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it('should not open the highlighted instrument when Enter is pressed on a language dropdown', () => { + const onSelect = renderWithLanguages(['en', 'fr']); + fireEvent.keyDown(screen.getByTestId('instrument-language-beta'), { key: 'Enter' }); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it('should keep each card on its own language, so one choice does not change another', () => { + const delta = createInstrument({ + id: 'delta', + kind: 'FORM', + supportedLanguages: ['en', 'fr'], + tags: ['Mood'], + title: 'Delta Questionnaire' + }); + const onSelect = renderWithLanguages(['en', 'fr'], [beta, delta]); + fireEvent.click(screen.getByTestId('instrument-language-beta')); + fireEvent.click(screen.getByRole('option', { name: 'French' })); + fireEvent.click(screen.getByTestId('instrument-card-delta')); + expect(onSelect).toHaveBeenCalledWith(delta, 'en'); + }); }); diff --git a/apps/web/src/components/LanguageSelect/LanguageSelect.tsx b/apps/web/src/components/LanguageSelect/LanguageSelect.tsx index 94447fdbc..e4dbe0543 100644 --- a/apps/web/src/components/LanguageSelect/LanguageSelect.tsx +++ b/apps/web/src/components/LanguageSelect/LanguageSelect.tsx @@ -1,3 +1,5 @@ +import type React from 'react'; + import { Select } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { $Language } from '@opendatacapture/schemas/core'; @@ -9,6 +11,10 @@ export type LanguageSelectProps = { 'data-testid'?: string; id?: string; onChange: (language: Language) => void; + /** Forwarded to the trigger, for a select inside something that is itself clickable. */ + onClick?: (event: React.MouseEvent) => void; + /** Forwarded to the trigger, for a select inside something that handles keys of its own. */ + onKeyDown?: (event: React.KeyboardEvent) => void; /** The languages to offer; defaults to every language the application supports. */ options?: readonly Language[]; value: Language; @@ -19,13 +25,15 @@ export const LanguageSelect = ({ 'data-testid': testId, id, onChange, + onClick, + onKeyDown, options = LANGUAGES, value }: LanguageSelectProps) => { const { t } = useTranslation(); return ( - {data.map((instrument) => ( - - ))} - - ) + onSelect: (info: InstrumentInfoStub, language?: Language) => void; + }) => { + mocks.showcaseProps(props); + return ( +
    + + {props.data.map((instrument) => ( + + ))} +
    + ); + } })); vi.mock('@/hooks/useInstrumentInfoQuery', () => ({ useInstrumentInfoQuery: () => ({ data: mocks.instrumentInfo }) })); +vi.mock('@/hooks/useSetupStateQuery', () => ({ + useSetupStateQuery: () => ({ data: { activeLanguages: mocks.activeLanguages } }) +})); vi.mock('@/store', () => ({ useAppStore: (selector: (store: typeof mocks.store) => unknown) => selector(mocks.store) })); const AccessibleInstrumentsPage = Route.options.component!; -const allowed: InstrumentInfoStub = { details: { title: 'Allowed' }, id: 'instrument-1', kind: 'FORM' }; -const excluded: InstrumentInfoStub = { details: { title: 'Excluded' }, id: 'instrument-2', kind: 'FORM' }; +const allowed: InstrumentInfoStub = { + details: { title: 'Allowed' }, + id: 'instrument-1', + internal: { edition: 1, name: 'Allowed' }, + kind: 'FORM', + supportedLanguages: ['en', 'fr'] +}; +const excluded: InstrumentInfoStub = { + details: { title: 'Excluded' }, + id: 'instrument-2', + internal: { edition: 1, name: 'Excluded' }, + kind: 'FORM', + supportedLanguages: ['en'] +}; describe('Route', () => { beforeEach(() => { + mocks.activeLanguages = ['en', 'fr', 'es']; mocks.instrumentInfo = [allowed, excluded]; mocks.store.currentGroup = { accessibleInstrumentIds: ['instrument-1'] }; }); @@ -99,11 +128,18 @@ describe('Route', () => { expect(document.activeElement).toBe(screen.getByRole('textbox')); }); - it('should open the selected instrument, passing its info along to avoid refetching it', () => { + it('should offer the showcase only the languages the instance has active', () => { + mocks.activeLanguages = ['en', 'fr']; + render(); + expect(mocks.showcaseProps).toHaveBeenCalledWith(expect.objectContaining({ allowedLanguages: ['en', 'fr'] })); + }); + + it('should open the instrument in the language its card was left on, with no further step', () => { render(); fireEvent.click(screen.getByRole('button', { name: 'Allowed' })); expect(mocks.navigate).toHaveBeenCalledWith({ params: { id: 'instrument-1' }, + search: { language: 'fr' }, state: { info: allowed }, to: '/instruments/render/$id' }); diff --git a/apps/web/src/routes/_app/instruments/accessible-instruments.tsx b/apps/web/src/routes/_app/instruments/accessible-instruments.tsx index b486bb7ba..8c2a664dd 100644 --- a/apps/web/src/routes/_app/instruments/accessible-instruments.tsx +++ b/apps/web/src/routes/_app/instruments/accessible-instruments.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from 'react'; +import { useEffect } from 'react'; import { Heading } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; @@ -8,6 +8,7 @@ import { InstrumentShowcase } from '@/components/InstrumentShowcase'; import { PageHeader } from '@/components/PageHeader'; import { WithFallback } from '@/components/WithFallback'; import { useInstrumentInfoQuery } from '@/hooks/useInstrumentInfoQuery'; +import { useSetupStateQuery } from '@/hooks/useSetupStateQuery'; import { useAppStore } from '@/store'; import { selectAdministrableInstruments } from '@/utils/administrable-instruments'; @@ -16,6 +17,7 @@ const RouteComponent = () => { const navigate = useNavigate(); const { t } = useTranslation(); const instrumentInfoQuery = useInstrumentInfoQuery(); + const setupStateQuery = useSetupStateQuery(); useEffect(() => { const input = document.querySelector('[data-testid="instrument-search-bar"] input'); @@ -32,10 +34,12 @@ const RouteComponent = () => { { + onSelect: (instrument, language) => { void navigate({ params: { id: instrument.id }, + search: { language }, state: { info: instrument }, to: `/instruments/render/$id` }); diff --git a/apps/web/src/routes/_app/instruments/render/$id.tsx b/apps/web/src/routes/_app/instruments/render/$id.tsx index cf738f990..84e1a14cd 100644 --- a/apps/web/src/routes/_app/instruments/render/$id.tsx +++ b/apps/web/src/routes/_app/instruments/render/$id.tsx @@ -4,11 +4,13 @@ import { Heading, Spinner } from '@douglasneuroinformatics/libui/components'; import { useNotificationsStore, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { InstrumentRenderer } from '@opendatacapture/react-core'; import type { InstrumentSubmitHandler } from '@opendatacapture/react-core'; +import { $Language } from '@opendatacapture/schemas/core'; import type { UnilingualInstrumentInfo } from '@opendatacapture/schemas/instrument'; import type { CreateInstrumentRecordData, InstrumentRecord } from '@opendatacapture/schemas/instrument-records'; import { $FileMetadata, $PresignedUrls, $UploadCompleteData } from '@opendatacapture/schemas/storage'; import { createFileRoute, useLocation, useNavigate } from '@tanstack/react-router'; import axios from 'axios'; +import { z } from 'zod/v4'; import { NavigationBlocker } from '@/components/NavigationBlocker'; import { PageHeader } from '@/components/PageHeader'; @@ -20,6 +22,7 @@ const RouteComponent = () => { const currentSession = useAppStore((store) => store.currentSession); const params = Route.useParams(); + const { language } = Route.useSearch(); const navigate = useNavigate(); const notifications = useNotificationsStore(); const location = useLocation(); @@ -114,6 +117,7 @@ const RouteComponent = () => {
    { }; export const Route = createFileRoute('/_app/instruments/render/$id')({ - component: RouteComponent + component: RouteComponent, + validateSearch: z.object({ language: $Language.optional() }) }); diff --git a/apps/web/src/routes/_app/instruments/render/__tests__/$id.test.tsx b/apps/web/src/routes/_app/instruments/render/__tests__/$id.test.tsx index cc74586dd..d4915fd22 100644 --- a/apps/web/src/routes/_app/instruments/render/__tests__/$id.test.tsx +++ b/apps/web/src/routes/_app/instruments/render/__tests__/$id.test.tsx @@ -13,6 +13,7 @@ import { Route } from '@/routes/_app/instruments/render/$id'; import '@/services/i18n'; type InstrumentRendererProps = { + language?: string; NavigationBlocker?: unknown; onSubmit: InstrumentSubmitHandler; subject?: Subject; @@ -24,6 +25,7 @@ type AxiosRequestConfigStub = { onUploadProgress: (event: { loaded: number }) => type MockState = { bundle: unknown; locationState: { info?: { clientDetails?: { title?: string }; details: { title: string } } }; + search: { language?: string }; store: { currentGroup: null | { id: string }; currentSession: null | Session }; }; @@ -31,6 +33,7 @@ const mocks = vi.hoisted(() => { const state: MockState = { bundle: undefined, locationState: {}, + search: {}, store: { currentGroup: null, currentSession: null } }; return { @@ -44,7 +47,13 @@ const mocks = vi.hoisted(() => { vi.mock('axios', () => ({ default: mocks.axios })); vi.mock('@tanstack/react-router', async (importOriginal) => ({ ...(await importOriginal()), - createFileRoute: () => (options: { component: FC }) => ({ options, useParams: () => ({ id: 'instrument-1' }) }), + createFileRoute: () => { + return (options: { component: FC }) => ({ + options, + useParams: () => ({ id: 'instrument-1' }), + useSearch: () => mocks.search + }); + }, useLocation: () => ({ state: mocks.locationState }), useNavigate: () => mocks.navigate })); @@ -99,6 +108,7 @@ describe('Route', () => { beforeEach(() => { mocks.bundle = { bundle: '__BUNDLE__', id: 'instrument-1', kind: 'FORM' }; mocks.locationState = { info: { details: { title: 'Details Title' } } }; + mocks.search = {}; mocks.store.currentGroup = { id: 'group-1' }; mocks.store.currentSession = createSession(); mocks.axios.post.mockResolvedValue({ data: { id: 'record-1' } }); @@ -129,6 +139,17 @@ describe('Route', () => { expect(rendererProps().NavigationBlocker).toBe(NavigationBlocker); }); + it('should run the instrument in the language the clinician chose', () => { + mocks.search = { language: 'fr' }; + render(); + expect(rendererProps().language).toBe('fr'); + }); + + it('should leave the instrument in the interface language when none was chosen', () => { + render(); + expect(rendererProps().language).toBeUndefined(); + }); + it('should render without a subject when the session has none', () => { mocks.store.currentSession = createSession(null); render(); diff --git a/apps/web/src/routes/_app/session/__tests__/remote-assignment.test.tsx b/apps/web/src/routes/_app/session/__tests__/remote-assignment.test.tsx index 89f0ca3ba..f76321c3f 100644 --- a/apps/web/src/routes/_app/session/__tests__/remote-assignment.test.tsx +++ b/apps/web/src/routes/_app/session/__tests__/remote-assignment.test.tsx @@ -2,7 +2,7 @@ import type { FC } from 'react'; import type { Assignment } from '@opendatacapture/schemas/assignment'; import type { Session } from '@opendatacapture/schemas/session'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { Route } from '@/routes/_app/session/remote-assignment'; @@ -12,11 +12,13 @@ import '@/services/i18n'; type InstrumentInfoStub = { details: { title: string }; id: string; + internal: { edition: number; name: string }; kind: 'FILE' | 'FORM'; supportedLanguages: string[]; }; type MockState = { + activeLanguages: string[]; config: { setup: { isGatewayEnabled: boolean } }; instrumentInfo: InstrumentInfoStub[] | undefined; store: { currentGroup: null | { accessibleInstrumentIds: string[]; id: string }; currentSession: null | Session }; @@ -24,13 +26,16 @@ type MockState = { const mocks = vi.hoisted(() => { const state: MockState = { + activeLanguages: ['en', 'fr'], config: { setup: { isGatewayEnabled: true } }, instrumentInfo: undefined, store: { currentGroup: null, currentSession: null } }; return { ...state, - AssignmentEmailForm: vi.fn((_props: { assignment: Assignment | null; instrumentLanguages?: string[] }) => null), + AssignmentEmailForm: vi.fn( + (_props: { assignment: Assignment | null; initialLanguage?: string; instrumentLanguages?: string[] }) => null + ), mutateAsync: vi.fn(), navigate: vi.fn(), QRCode: vi.fn((_props: { url: string }) => null) @@ -68,7 +73,9 @@ vi.mock('@/hooks/useInstrumentInfoQuery', () => ({ useInstrumentInfoQuery: () => ({ data: mocks.instrumentInfo }) })); vi.mock('@/hooks/useSetupStateQuery', () => ({ - useSetupStateQuery: () => ({ data: { defaultAssignmentDurationDays: 7 } }) + useSetupStateQuery: () => ({ + data: { activeLanguages: mocks.activeLanguages, defaultAssignmentDurationDays: 7 } + }) })); vi.mock('@/store', () => ({ useAppStore: (selector: (store: typeof mocks.store) => unknown) => selector(mocks.store) @@ -103,6 +110,7 @@ const assignment: Assignment = { const allowed: InstrumentInfoStub = { details: { title: 'Allowed' }, id: 'instrument-1', + internal: { edition: 1, name: 'Allowed' }, kind: 'FORM', supportedLanguages: ['en', 'fr'] }; @@ -118,17 +126,38 @@ const selectInstrument = () => { const submitForm = () => fireEvent.click(screen.getByRole('button', { name: 'Submit' })); +/** + * Waits out the whole submit cycle, so no state update lands after the test has finished. + * + * The link renders as soon as `mutateAsync` resolves, but the form is `suspendWhileSubmitting`, so + * libui holds `isSubmitting` for 500ms more and clears it once this dialog is already gone. Ending + * on the link alone leaves that update to fire after the environment is torn down, which surfaces + * as an unhandled `window is not defined` charged to whichever file runs next. + */ +const waitForLink = async () => { + await waitFor(() => expect(screen.getByRole('link', { name: 'Assignment Link' })).toBeTruthy()); + await act(async () => { + await new Promise((resolve) => { + setTimeout(resolve, 600); + }); + }); +}; + const createAssignment = async () => { selectInstrument(); submitForm(); - await waitFor(() => expect(screen.getByRole('link', { name: 'Assignment Link' })).toBeTruthy()); + await waitForLink(); }; describe('Route', () => { beforeEach(() => { vi.useFakeTimers({ now: NOW, toFake: ['Date'] }); mocks.config.setup.isGatewayEnabled = true; - mocks.instrumentInfo = [allowed, { ...allowed, details: { title: 'Excluded' }, id: 'instrument-2' }]; + mocks.activeLanguages = ['en', 'fr']; + mocks.instrumentInfo = [ + allowed, + { ...allowed, details: { title: 'Excluded' }, id: 'instrument-2', internal: { edition: 1, name: 'Excluded' } } + ]; mocks.store.currentGroup = { accessibleInstrumentIds: ['instrument-1'], id: 'group-1' }; mocks.store.currentSession = session; mocks.mutateAsync.mockResolvedValue(assignment); @@ -216,11 +245,35 @@ describe('Route', () => { expiresAt: new Date('2026-01-08'), groupId: 'group-1', instrumentId: 'instrument-1', + language: undefined, subjectId: 'subject-1' } }); }); + it('should leave the language unset by default, so the browser that opens the link decides', async () => { + await createAssignment(); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: undefined }) }); + }); + + it('should assign the language chosen in the dialog, so the link opens the gateway in it', async () => { + selectInstrument(); + fireEvent.click(screen.getByTestId('administration-language')); + fireEvent.click(screen.getByRole('option', { name: 'French' })); + submitForm(); + await waitForLink(); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: 'fr' }) }); + }); + + it('should offer no language dropdown when the gateway serves only one, since there is nothing to pin', async () => { + mocks.activeLanguages = ['fr']; + selectInstrument(); + expect(screen.queryByTestId('administration-language')).toBeNull(); + submitForm(); + await waitForLink(); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: undefined }) }); + }); + it('should refuse a redirect URL that is not https, without creating the assignment', async () => { selectInstrument(); fireEvent.change(screen.getByLabelText('Redirect URL (Optional)'), { target: { value: 'http://example.com' } }); @@ -235,7 +288,7 @@ describe('Route', () => { target: { value: 'https://example.com/done' } }); submitForm(); - await waitFor(() => expect(mocks.mutateAsync).toHaveBeenCalled()); + await waitForLink(); expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ redirectUrl: 'https://example.com/done' }) }); @@ -247,7 +300,7 @@ describe('Route', () => { fireEvent.change(input, { target: { value: 'https://example.com/done' } }); fireEvent.change(input, { target: { value: '' } }); submitForm(); - await waitFor(() => expect(mocks.mutateAsync).toHaveBeenCalled()); + await waitForLink(); expect(mocks.mutateAsync.mock.lastCall?.[0].data.redirectUrl).toBeUndefined(); }); @@ -267,7 +320,11 @@ describe('Route', () => { it('should hand the assignment url to the QR code and the email form', async () => { await createAssignment(); expect(mocks.QRCode.mock.lastCall?.[0]).toEqual({ url: assignment.url }); - expect(mocks.AssignmentEmailForm.mock.lastCall?.[0]).toEqual({ assignment, instrumentLanguages: ['en', 'fr'] }); + expect(mocks.AssignmentEmailForm.mock.lastCall?.[0]).toEqual({ + assignment, + initialLanguage: undefined, + instrumentLanguages: ['en', 'fr'] + }); }); it('should close the link panel when the close button is clicked', async () => { diff --git a/apps/web/src/routes/_app/session/remote-assignment.tsx b/apps/web/src/routes/_app/session/remote-assignment.tsx index 938f841b1..fa9e98bf4 100644 --- a/apps/web/src/routes/_app/session/remote-assignment.tsx +++ b/apps/web/src/routes/_app/session/remote-assignment.tsx @@ -4,16 +4,18 @@ import { Button, Dialog, Form, Heading, Input, Label, Sheet } from '@douglasneur import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { CopyButton } from '@opendatacapture/react-core'; import type { $CreateAssignmentData, Assignment } from '@opendatacapture/schemas/assignment'; -import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; +import type { Language } from '@opendatacapture/schemas/core'; import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'; import { z } from 'zod/v4'; +import { AdministrationOptions } from '@/components/AdministrationOptions'; import { AssignmentEmailForm } from '@/components/AssignmentEmailForm'; import { InstrumentShowcase } from '@/components/InstrumentShowcase'; import { PageHeader } from '@/components/PageHeader'; import { QRCode } from '@/components/QRCode'; import { WithFallback } from '@/components/WithFallback'; import { config } from '@/config'; +import { useAdministrationChoice } from '@/hooks/useAdministrationChoice'; import { useCreateAssignment } from '@/hooks/useCreateAssignment'; import { useInstrumentInfoQuery } from '@/hooks/useInstrumentInfoQuery'; import { useSetupStateQuery } from '@/hooks/useSetupStateQuery'; @@ -27,9 +29,10 @@ const AssignmentResultSlider: React.FC<{ assignment: Assignment | null; instrumentLanguages?: string[]; isOpen: boolean; + language: Language | undefined; setIsOpen: (isOpen: boolean) => void; title: string | undefined; -}> = ({ assignment, instrumentLanguages, isOpen, setIsOpen, title }) => { +}> = ({ assignment, instrumentLanguages, isOpen, language, setIsOpen, title }) => { const { t } = useTranslation(); const url = assignment?.url; @@ -62,7 +65,12 @@ const AssignmentResultSlider: React.FC<{
    - + @@ -93,8 +101,7 @@ const RouteComponent = () => { const instrumentInfoQuery = useInstrumentInfoQuery(); const setupStateQuery = useSetupStateQuery(); const createAssignmentMutation = useCreateAssignment(); - - const [selectedInstrument, setSelectedInstrument] = useState(null); + const { choice, pick, setLanguage } = useAdministrationChoice(setupStateQuery.data.activeLanguages); const [isCreateModalOpen, setIsCreateModalOpen] = useState(false); const createDialogRef = useRef(null); const [isResultSliderOpen, setIsResultSliderOpen] = useState(false); @@ -131,7 +138,7 @@ const RouteComponent = () => { props={{ data: instrumentInfoQuery.data && selectRemotelyAssignableInstruments(instrumentInfoQuery.data, currentGroup), onSelect: (instrument) => { - setSelectedInstrument(instrument); + pick(instrument); setIsCreateModalOpen(true); } }} @@ -159,74 +166,81 @@ const RouteComponent = () => { es: 'Asignar "{}" al sujeto actual para que la complete de forma remota.', fr: 'Assigner « {} » au client actuel pour complétion à distance.' }, - { args: [selectedInstrument?.details.title ?? ''] } + { args: [choice?.instrument.details.title ?? ''] } )} -
    > - } - onSubmit={async ({ expiresAt, redirectUrl }) => { - const created = await createAssignmentMutation.mutateAsync({ - data: { - expiresAt, - groupId: currentGroup?.id, - instrumentId: selectedInstrument!.id, - redirectUrl: omittedIfBlank(redirectUrl), - subjectId: currentSession.subjectId + {choice && ( + + + > } - }); - setAssignment(created); - setIsCreateModalOpen(false); - setIsResultSliderOpen(true); - }} - /> + onSubmit={async ({ expiresAt, redirectUrl }) => { + const created = await createAssignmentMutation.mutateAsync({ + data: { + expiresAt, + groupId: currentGroup?.id, + instrumentId: choice.instrument.id, + language: choice.language, + redirectUrl: omittedIfBlank(redirectUrl), + subjectId: currentSession.subjectId + } + }); + setAssignment(created); + setIsCreateModalOpen(false); + setIsResultSliderOpen(true); + }} + /> + + )} ); diff --git a/apps/web/src/utils/__tests__/administration-choice.test.ts b/apps/web/src/utils/__tests__/administration-choice.test.ts new file mode 100644 index 000000000..4b19e2b77 --- /dev/null +++ b/apps/web/src/utils/__tests__/administration-choice.test.ts @@ -0,0 +1,48 @@ +import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; +import { describe, expect, it } from 'vitest'; + +import { getAdministrationChoice } from '../administration-choice'; + +function createInfo(supportedLanguages: string[]): TranslatedInstrumentInfo { + return { + details: { title: 'a' }, + id: 'a-1', + internal: { edition: 1, name: 'a' }, + kind: 'FORM', + supportedLanguages + } as unknown as TranslatedInstrumentInfo; +} + +describe('getAdministrationChoice', () => { + it('should return the preferred language when the instrument offers it', () => { + const result = getAdministrationChoice(createInfo(['en', 'fr']), { + allowedLanguages: ['en', 'fr'], + preferredLanguage: 'fr' + }); + expect(result.language).toBe('fr'); + }); + + it('should fall back to the first offered language when the preferred one is not offered', () => { + const result = getAdministrationChoice(createInfo(['fr']), { + allowedLanguages: ['en', 'fr'], + preferredLanguage: 'en' + }); + expect(result.language).toBe('fr'); + }); + + it('should offer only the allowed languages, so a language the instance turned off is not offered', () => { + const result = getAdministrationChoice(createInfo(['en', 'fr']), { + allowedLanguages: ['fr'], + preferredLanguage: 'en' + }); + expect(result.languageOptions).toStrictEqual(['fr']); + }); + + it('should leave the language undefined when the instrument offers no allowed language', () => { + const result = getAdministrationChoice(createInfo(['en']), { + allowedLanguages: ['fr'], + preferredLanguage: 'en' + }); + expect(result.language).toBeUndefined(); + }); +}); diff --git a/apps/web/src/utils/__tests__/assignment-link.test.ts b/apps/web/src/utils/__tests__/assignment-link.test.ts new file mode 100644 index 000000000..84fd29b51 --- /dev/null +++ b/apps/web/src/utils/__tests__/assignment-link.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; + +import { getLinkLanguage } from '../assignment-link'; + +describe('getLinkLanguage', () => { + it('should read the language the link opens the instrument in', () => { + expect(getLinkLanguage('https://gateway.example/assignments/a-1?lang=fr')).toBe('fr'); + }); + + it('should read nothing from a link created without a language, which the gateway chooses for', () => { + expect(getLinkLanguage('https://gateway.example/assignments/a-1')).toBeUndefined(); + }); + + it('should read nothing from a language the application does not have, rather than trust the URL', () => { + expect(getLinkLanguage('https://gateway.example/assignments/a-1?lang=klingon')).toBeUndefined(); + }); +}); diff --git a/apps/web/src/utils/administration-choice.ts b/apps/web/src/utils/administration-choice.ts new file mode 100644 index 000000000..7ef40fe45 --- /dev/null +++ b/apps/web/src/utils/administration-choice.ts @@ -0,0 +1,43 @@ +import type { Language } from '@opendatacapture/schemas/core'; +import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; + +type AdministrationChoice = { + instrument: TranslatedInstrumentInfo; + /** + * The language to open the instrument in. Absent means none was chosen, which a remote assignment + * leaves to the subject's browser and the instrument offers none of the allowed languages. + */ + language: Language | undefined; + languageOptions: Language[]; +}; + +type AdministrationChoiceOptions = { + /** Narrows the instrument's own languages to those the instance has active. */ + allowedLanguages: readonly Language[]; + /** Used when the instrument offers it; otherwise the first language it does offer. */ + preferredLanguage: Language; +}; + +/** The languages an instrument may be opened in here: its own, narrowed to the instance's active ones. */ +function getLanguageOptions(instrument: TranslatedInstrumentInfo, allowedLanguages: readonly Language[]): Language[] { + return instrument.supportedLanguages.filter((language) => allowedLanguages.includes(language)); +} + +/** + * The language a picked instrument opens in where one must be settled now, as on a showcase card + * that opens the instrument in a single click. + */ +function getAdministrationChoice( + instrument: TranslatedInstrumentInfo, + { allowedLanguages, preferredLanguage }: AdministrationChoiceOptions +): AdministrationChoice { + const languageOptions = getLanguageOptions(instrument, allowedLanguages); + return { + instrument, + language: languageOptions.includes(preferredLanguage) ? preferredLanguage : languageOptions[0], + languageOptions + }; +} + +export { getAdministrationChoice, getLanguageOptions }; +export type { AdministrationChoice }; diff --git a/apps/web/src/utils/assignment-link.ts b/apps/web/src/utils/assignment-link.ts new file mode 100644 index 000000000..5b53bcbe6 --- /dev/null +++ b/apps/web/src/utils/assignment-link.ts @@ -0,0 +1,13 @@ +import { $Language } from '@opendatacapture/schemas/core'; +import type { Language } from '@opendatacapture/schemas/core'; + +/** + * The language an assignment link opens the gateway in, which the API stores as its `lang` param. + * + * Absent for a link created without one — a bulk assignment, or one made before the language could + * be chosen — which the gateway opens in its own choice of language instead. + */ +export function getLinkLanguage(url: string): Language | undefined { + const lang = $Language.safeParse(new URL(url).searchParams.get('lang')); + return lang.success ? lang.data : undefined; +} diff --git a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx index 87eec2ebd..05de5ba5a 100644 --- a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx +++ b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx @@ -116,6 +116,8 @@ Use **Administer Instrument** after starting a session. Administer Instrument shows the instruments selected for the current group. Select an instrument and complete it. +If an instrument is available in more than one language, ODC asks which language to use before it starts, with your interface language selected by default. The language you choose changes only the instrument, not the rest of ODC. Remote assignments offer the same choice, and the assignment link opens in the language you chose, even when the email that sends it is written in another language. + ## Review and Export Data Use **Data Hub** to find subjects, review records, export data, and graph measures. diff --git a/packages/react-core/src/components/InstrumentRenderer/InstrumentRenderer.tsx b/packages/react-core/src/components/InstrumentRenderer/InstrumentRenderer.tsx index e67b67e53..bbe19ab3c 100644 --- a/packages/react-core/src/components/InstrumentRenderer/InstrumentRenderer.tsx +++ b/packages/react-core/src/components/InstrumentRenderer/InstrumentRenderer.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from 'react'; +import type { Language } from '@opendatacapture/schemas/core'; import type { InstrumentBundleContainer } from '@opendatacapture/schemas/instrument'; import { ScalarInstrumentRenderer } from './ScalarInstrumentRenderer'; @@ -18,6 +19,8 @@ export type InstrumentRendererProps = { /** Whether to disable copy, download, print in the final summary */ disableSummaryActions?: boolean; initialSeriesIndex?: number; + /** The language to run the instrument in, leaving the interface language alone. Defaults to the interface language. */ + language?: Language; NavigationBlocker?: NavigationBlockerComponent; onSubmit: InstrumentSubmitHandler; subject?: SubjectDisplayInfo; diff --git a/packages/react-core/src/components/InstrumentRenderer/ScalarInstrumentRenderer.tsx b/packages/react-core/src/components/InstrumentRenderer/ScalarInstrumentRenderer.tsx index b0e1b6266..689b39340 100644 --- a/packages/react-core/src/components/InstrumentRenderer/ScalarInstrumentRenderer.tsx +++ b/packages/react-core/src/components/InstrumentRenderer/ScalarInstrumentRenderer.tsx @@ -6,9 +6,11 @@ import { Spinner } from '@douglasneuroinformatics/libui/components'; import { useNotificationsStore, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { InterpretOptions } from '@opendatacapture/instrument-interpreter'; import type { AnyScalarInstrument, AnyUnilingualScalarInstrument, Json } from '@opendatacapture/runtime-core'; +import type { Language } from '@opendatacapture/schemas/core'; import type { ScalarInstrumentBundleContainer } from '@opendatacapture/schemas/instrument'; import { match } from 'ts-pattern'; +import { useInstrumentLanguage } from '../../hooks/useInstrumentLanguage'; import { useInterpretedInstrument } from '../../hooks/useInterpretedInstrument'; import { FileInstrumentContent } from '../FileInstrumentContent'; import { FormContent } from '../FormContent'; @@ -31,6 +33,8 @@ export type ScalarInstrumentRendererProps = { disableBegin?: boolean; /** Whether to disable copy, download, print in the final summary */ disableSummaryActions?: boolean; + /** The language to run the instrument in, leaving the interface language alone. Defaults to the interface language. */ + language?: Language; NavigationBlocker?: NavigationBlockerComponent; /** @deprecated */ onCompileError?: (error: Error) => void; @@ -48,6 +52,7 @@ export const ScalarInstrumentRenderer = ({ className, disableBegin, disableSummaryActions, + language, NavigationBlocker, onCompileError, onSubmit, @@ -57,7 +62,8 @@ export const ScalarInstrumentRenderer = ({ target }: ScalarInstrumentRendererProps) => { const [data, setData] = useState(); - const interpreted = useInterpretedInstrument(target.bundle, options); + const [contentLanguage, changeContentLanguage] = useInstrumentLanguage(language); + const interpreted = useInterpretedInstrument(target.bundle, options, contentLanguage); const [index, setIndex] = useState<0 | 1 | 2>(0); const { t } = useTranslation(); const addNotification = useNotificationsStore((store) => store.addNotification); @@ -136,7 +142,9 @@ export const ScalarInstrumentRenderer = ({ enableLanguageLock={instrument.content.enableLanguageLock} enableLanguageSelect={instrument.content.enableLanguageSelect} enableLanguageToggle={instrument.content.enableLanguageToggle} + language={contentLanguage} supportedLanguages={instrument.supportedLanguages} + onChangeLanguage={changeContentLanguage} onSubmit={createSubmitHandler(instrument)} /> )) diff --git a/packages/react-core/src/components/InstrumentRenderer/SeriesInstrumentRenderer.tsx b/packages/react-core/src/components/InstrumentRenderer/SeriesInstrumentRenderer.tsx index 5a16dfcb8..15fd1b197 100644 --- a/packages/react-core/src/components/InstrumentRenderer/SeriesInstrumentRenderer.tsx +++ b/packages/react-core/src/components/InstrumentRenderer/SeriesInstrumentRenderer.tsx @@ -6,10 +6,12 @@ import { Button, Heading, Spinner } from '@douglasneuroinformatics/libui/compone import { useNotificationsStore, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { getSeriesInstrumentParams } from '@opendatacapture/instrument-utils'; import type { AnyUnilingualScalarInstrument, Json, UnilingualSeriesInstrument } from '@opendatacapture/runtime-core'; +import type { Language } from '@opendatacapture/schemas/core'; import type { SeriesInstrumentBundleContainer } from '@opendatacapture/schemas/instrument'; import { CircleCheckIcon } from 'lucide-react'; import { match } from 'ts-pattern'; +import { useInstrumentLanguage } from '../../hooks/useInstrumentLanguage'; import { useInterpretedInstrument } from '../../hooks/useInterpretedInstrument'; import { FormContent } from '../FormContent'; import { InstrumentOverview } from '../InstrumentOverview'; @@ -32,6 +34,8 @@ export type SeriesInstrumentRendererProps = { /** When true, the "Begin" button on the overview screen is disabled. */ disableBegin?: boolean; initialSeriesIndex?: number; + /** The language to run the instrument in, leaving the interface language alone. Defaults to the interface language. */ + language?: Language; NavigationBlocker?: NavigationBlockerComponent; onSubmit: InstrumentSubmitHandler<'SERIES'>; /** A localizable label for each constituent form's submit button. */ @@ -44,6 +48,7 @@ export const SeriesInstrumentRenderer = ({ className, disableBegin, initialSeriesIndex, + language, NavigationBlocker, onSubmit, submitButtonLabel, @@ -66,8 +71,13 @@ export const SeriesInstrumentRenderer = ({ const scalarBundle = target.items[currentItemIndex]?.bundle; const scalarId = target.items[currentItemIndex]?.id; - const rootState = useInterpretedInstrument(target.bundle); - const scalarState = useInterpretedInstrument(scalarBundle ?? ''); + const [contentLanguage, changeContentLanguage] = useInstrumentLanguage(language); + const rootState = useInterpretedInstrument(target.bundle, undefined, contentLanguage); + const scalarState = useInterpretedInstrument( + scalarBundle ?? '', + undefined, + contentLanguage + ); const [isInstrumentInProgress, setIsInstrumentInProgress] = useState(false); const [completion, setCompletion] = useState(null); @@ -213,6 +223,8 @@ export const SeriesInstrumentRenderer = ({ )) diff --git a/packages/react-core/src/components/InteractiveContent/InteractiveContent.stories.tsx b/packages/react-core/src/components/InteractiveContent/InteractiveContent.stories.tsx index bae7af097..ad4b347aa 100644 --- a/packages/react-core/src/components/InteractiveContent/InteractiveContent.stories.tsx +++ b/packages/react-core/src/components/InteractiveContent/InteractiveContent.stories.tsx @@ -21,6 +21,10 @@ export default { export const Default: Story = { args: { bundle: interactiveInstrument.bundle, + language: 'en', + onChangeLanguage() { + // The host owns the instrument's language; this story holds it fixed. + }, onSubmit({ data }) { alert(JSON.stringify(data, null, 2)); } diff --git a/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx b/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx index 0bb05e159..6174bdb1f 100644 --- a/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx +++ b/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx @@ -23,11 +23,13 @@ const _InteractiveContent = React.memo(function _Intera enableLanguageLock, enableLanguageSelect, enableLanguageToggle, + language, + onChangeLanguage, onSubmit, supportedLanguages = [] }) { const addNotification = useNotificationsStore((store) => store.addNotification); - const { changeLanguage, resolvedLanguage, t } = useTranslation(); + const { resolvedLanguage, t } = useTranslation(); const [_, updateTheme] = useTheme(); const [scale, setScale] = useState(100); const [hasSelectedLanguage, setHasSelectedLanguage] = useState( @@ -58,9 +60,9 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeLanguage(requested.data); + onChangeLanguage(requested.data); }, - [addNotification, changeLanguage, isLocked, t] + [addNotification, isLocked, onChangeLanguage, t] ); const handleChangeThemeEvent = useCallback( @@ -162,7 +164,7 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeLanguage(language); + onChangeLanguage(language); }} > {LANGUAGE_LABELS[language][resolvedLanguage]} @@ -177,7 +179,7 @@ const _InteractiveContent = React.memo(function _Intera allow="fullscreen" className="origin-top-left" data-bundle={bundle} - lang={resolvedLanguage} + lang={language} name="interactive-instrument" ref={iFrameRef} src="/runtime/v1/@opendatacapture/runtime-internal/interactive/iframe.html" @@ -201,7 +203,7 @@ const _InteractiveContent = React.memo(function _Intera key={language} type="button" onClick={() => { - changeLanguage(language); + onChangeLanguage(language); setHasSelectedLanguage(true); }} > @@ -260,6 +262,10 @@ export type InteractiveContentProps = Simplify< InteractiveInstrument['content'], 'defaultFullscreen' | 'enableLanguageLock' | 'enableLanguageSelect' | 'enableLanguageToggle' > & { + /** The language the instrument runs in, held by the host instead of the interface language. */ + language: InterfaceLanguage; + onChangeLanguage: (language: InterfaceLanguage) => void; + } & { bundle: string; onSubmit: (result: InteractiveContentSubmitResult) => Promisable; supportedLanguages?: Language[]; diff --git a/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx b/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx index a6490a073..4269e3383 100644 --- a/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx +++ b/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx @@ -35,7 +35,9 @@ function renderWithLanguageToggle({ enableLanguageLock }: { enableLanguageLock: enableLanguageToggle bundle="bundle text" enableLanguageLock={enableLanguageLock} + language="en" supportedLanguages={['en', 'fr']} + onChangeLanguage={changeLanguage} onSubmit={vi.fn()} /> ); @@ -61,7 +63,15 @@ describe('InteractiveContent', () => { }); it('should render the iframe directly when there is at most one supported language', () => { - render(); + render( + + ); expect(document.querySelector('iframe[data-bundle="bundle text"]')).toBeTruthy(); }); @@ -70,7 +80,9 @@ describe('InteractiveContent', () => { ); @@ -83,7 +95,9 @@ describe('InteractiveContent', () => { ); @@ -94,7 +108,15 @@ describe('InteractiveContent', () => { it("should call onSubmit with the event's parsed JSON detail when the bundle dispatches 'done'", async () => { const onSubmit = vi.fn(); - render(); + render( + + ); await act(async () => { dispatch('done', { message: 'Hello' }); await Promise.resolve(); @@ -103,7 +125,15 @@ describe('InteractiveContent', () => { }); it("should change the language when the bundle dispatches a 'changeLanguage' event for a supported language", () => { - render(); + render( + + ); act(() => { dispatch('changeLanguage', 'fr'); }); @@ -111,7 +141,15 @@ describe('InteractiveContent', () => { }); it("should notify an error rather than change the language when 'changeLanguage' requests an unsupported language", () => { - render(); + render( + + ); act(() => { dispatch('changeLanguage', 'klingon'); }); @@ -121,7 +159,14 @@ describe('InteractiveContent', () => { it('should open the lock dialog instead of changing language when the language is locked', () => { render( - + ); act(() => { dispatch('changeLanguage', 'fr'); @@ -131,7 +176,15 @@ describe('InteractiveContent', () => { }); it("should update the theme when the bundle dispatches a valid 'changeTheme' event", () => { - render(); + render( + + ); act(() => { dispatch('changeTheme', 'dark'); }); @@ -140,7 +193,15 @@ describe('InteractiveContent', () => { it("should log an error rather than update the theme when 'changeTheme' carries an invalid value", () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); - render(); + render( + + ); act(() => { dispatch('changeTheme', 'sepia'); }); @@ -149,15 +210,62 @@ describe('InteractiveContent', () => { }); it("should forward an 'addNotification' event's detail to the notifications store", () => { - render(); + render( + + ); act(() => { dispatch('addNotification', { message: 'From the bundle', type: 'success' }); }); expect(addNotification).toHaveBeenCalledWith({ message: 'From the bundle', type: 'success' }); }); + it('should run the iframe in the language the host holds, whatever the interface language', () => { + render( + + ); + expect(screen.getByTitle('Open Data Capture - Interactive Instrument').getAttribute('lang')).toBe('fr'); + }); + + it("should hand a bundle's language change to the host holding the language, leaving the interface alone", () => { + const onChangeLanguage = vi.fn(); + render( + + ); + act(() => { + dispatch('changeLanguage', 'fr'); + }); + expect(onChangeLanguage).toHaveBeenCalledWith('fr'); + expect(changeLanguage).not.toHaveBeenCalled(); + }); + it('should zoom the iframe in and out within its lower bound', () => { - render(); + render( + + ); expect(screen.getByText('100%')).toBeTruthy(); const [zoomOut, zoomIn] = screen.getAllByRole('button'); fireEvent.click(zoomIn!); @@ -176,7 +284,9 @@ describe('InteractiveContent', () => { ); @@ -185,7 +295,14 @@ describe('InteractiveContent', () => { it('should close the lock dialog when its OK button is clicked', () => { render( - + ); act(() => { dispatch('changeLanguage', 'fr'); @@ -211,26 +328,57 @@ describe('InteractiveContent', () => { it('should enter fullscreen on mount when the instrument asks to start fullscreen', () => { installFullscreen(null); render( - + ); expect(requestFullscreen.mock.contexts[0]).toBe(document.querySelector('iframe')); }); it('should not enter fullscreen on mount unless the instrument asks to', () => { installFullscreen(null); - render(); + render( + + ); expect(requestFullscreen).not.toHaveBeenCalled(); }); it('should put the iframe in fullscreen from the fullscreen button when nothing is fullscreen', () => { installFullscreen(null); - render(); + render( + + ); fireEvent.click(screen.getAllByRole('button')[2]!); expect(requestFullscreen.mock.contexts[0]).toBe(document.querySelector('iframe')); }); it('should leave fullscreen from the fullscreen button when already fullscreen', () => { - render(); + render( + + ); installFullscreen(document.querySelector('iframe')); fireEvent.click(screen.getAllByRole('button')[2]!); expect(exitFullscreen).toHaveBeenCalledOnce(); diff --git a/packages/react-core/src/hooks/__tests__/useInstrumentLanguage.test.ts b/packages/react-core/src/hooks/__tests__/useInstrumentLanguage.test.ts new file mode 100644 index 000000000..099f4792c --- /dev/null +++ b/packages/react-core/src/hooks/__tests__/useInstrumentLanguage.test.ts @@ -0,0 +1,59 @@ +import { i18n } from '@douglasneuroinformatics/libui/i18n'; +import { act, renderHook } from '@testing-library/react'; +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { useInstrumentLanguage } from '../useInstrumentLanguage'; + +describe('useInstrumentLanguage', () => { + beforeAll(() => { + i18n.init({ translations: {} }); + }); + + beforeEach(() => { + i18n.changeLanguage('en'); + }); + + it('should follow the interface language when none is asked for', () => { + const { result } = renderHook(() => useInstrumentLanguage()); + expect(result.current[0]).toBe('en'); + }); + + it('should change the interface language when none is asked for, as instruments always have', () => { + const { result } = renderHook(() => useInstrumentLanguage()); + act(() => result.current[1]('fr')); + expect(i18n.resolvedLanguage).toBe('fr'); + }); + + it('should use the language asked for, whatever the interface language', () => { + const { result } = renderHook(() => useInstrumentLanguage('fr')); + expect(result.current[0]).toBe('fr'); + }); + + it('should change only the content language when one was asked for, leaving the interface alone', () => { + const { result } = renderHook(() => useInstrumentLanguage('fr')); + act(() => result.current[1]('en')); + expect(result.current[0]).toBe('en'); + expect(i18n.resolvedLanguage).toBe('en'); + act(() => result.current[1]('es')); + expect(result.current[0]).toBe('es'); + expect(i18n.resolvedLanguage).toBe('en'); + }); + + it('should take up a newly requested language, so a renderer kept mounted drops the previous one', () => { + const { rerender, result } = renderHook((language?: 'en' | 'fr') => useInstrumentLanguage(language), { + initialProps: 'fr' as 'en' | 'fr' | undefined + }); + expect(result.current[0]).toBe('fr'); + rerender('en'); + expect(result.current[0]).toBe('en'); + }); + + it('should follow the interface language again once nothing is requested', () => { + const { rerender, result } = renderHook((language?: 'en' | 'fr') => useInstrumentLanguage(language), { + initialProps: 'fr' as 'en' | 'fr' | undefined + }); + rerender(undefined); + act(() => result.current[1]('es')); + expect(i18n.resolvedLanguage).toBe('es'); + }); +}); diff --git a/packages/react-core/src/hooks/__tests__/useInterpretedInstrument.test.ts b/packages/react-core/src/hooks/__tests__/useInterpretedInstrument.test.ts index 900c606d8..35ead8546 100644 --- a/packages/react-core/src/hooks/__tests__/useInterpretedInstrument.test.ts +++ b/packages/react-core/src/hooks/__tests__/useInterpretedInstrument.test.ts @@ -138,4 +138,22 @@ describe('useInterpretedInstrument', () => { 'fr' ]); }); + + it('should translate into the language asked for rather than the interface language', async () => { + const bundle = `(async () => ({ + __runtimeVersion: 1, + kind: 'FORM', + language: ['en', 'fr'], + content: {}, + details: { + description: { en: 'English description', fr: 'Description française' }, + title: { en: 'English Title', fr: 'Titre français' } + }, + tags: { en: [], fr: [] } + }))()`; + const { result } = renderHook(() => useInterpretedInstrument(bundle, undefined, 'fr')); + await waitFor(() => { + expect(result.current).toMatchObject({ instrument: { details: { title: 'Titre français' } }, status: 'DONE' }); + }); + }); }); diff --git a/packages/react-core/src/hooks/useInstrumentLanguage.ts b/packages/react-core/src/hooks/useInstrumentLanguage.ts new file mode 100644 index 000000000..67543e63f --- /dev/null +++ b/packages/react-core/src/hooks/useInstrumentLanguage.ts @@ -0,0 +1,29 @@ +import { useState } from 'react'; + +import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import type { Language } from '@opendatacapture/schemas/core'; + +/** + * The language an instrument's content renders in, and how to change it. + * + * Without a `requestedLanguage` the content follows the interface language, so switching it from + * inside the instrument switches the whole application. A host that asks for a language — a + * clinician administering in the subject's language — gets it for the content alone, and a switch + * from inside the instrument then leaves the interface where it was. A host that asks for another + * language — rendering a second instrument without unmounting the renderer — gets that one, rather + * than keeping the first instrument's. + */ +export function useInstrumentLanguage(requestedLanguage?: Language): [Language, (language: Language) => void] { + const { changeLanguage, resolvedLanguage } = useTranslation(); + const [contentLanguage, setContentLanguage] = useState(requestedLanguage); + const [requested, setRequested] = useState(requestedLanguage); + + if (requestedLanguage !== requested) { + setRequested(requestedLanguage); + setContentLanguage(requestedLanguage); + } + if (!contentLanguage) { + return [resolvedLanguage, changeLanguage]; + } + return [contentLanguage, setContentLanguage]; +} diff --git a/packages/react-core/src/hooks/useInterpretedInstrument.ts b/packages/react-core/src/hooks/useInterpretedInstrument.ts index 45dccb95e..019c84a82 100644 --- a/packages/react-core/src/hooks/useInterpretedInstrument.ts +++ b/packages/react-core/src/hooks/useInterpretedInstrument.ts @@ -5,6 +5,7 @@ import { InstrumentInterpreter } from '@opendatacapture/instrument-interpreter'; import type { InterpretOptions } from '@opendatacapture/instrument-interpreter'; import { translateInstrument } from '@opendatacapture/instrument-utils'; import type { AnyInstrument, AnyUnilingualInstrument, Language } from '@opendatacapture/runtime-core'; +import type { Language as InterfaceLanguage } from '@opendatacapture/schemas/core'; /** The outcome of interpreting one bundle, kept alongside the bundle that produced it. */ type Interpretation = @@ -20,15 +21,18 @@ export type InterpretedInstrumentState( bundle: string, - options?: InterpretOptions + options?: InterpretOptions, + language?: InterfaceLanguage ): InterpretedInstrumentState { const interpreter = useMemo(() => new InstrumentInterpreter(), []); const [interpretation, setInterpretation] = useState(null); const { resolvedLanguage } = useTranslation(); + const targetLanguage = language ?? resolvedLanguage; useEffect(() => { // A bundle that resolves after the hook has moved on to another one would otherwise be reported @@ -66,12 +70,12 @@ export function useInterpretedInstrument { + await this.instrumentCard(title).locator('[data-testid^="instrument-language-"]').click(); + await this.$ref.getByRole('option', { name }).click(); + } + /** Cards carry a content-hash testid, so match on the visible title instead. */ instrumentCard(title: string): Locator { return this.instrumentShowcase.locator('[data-testid^="instrument-card-"]').filter({ hasText: title }).first(); diff --git a/testing/src/pages/_app/session/remote-assignment.page.ts b/testing/src/pages/_app/session/remote-assignment.page.ts index 7aecd7683..5fd9ab8e3 100644 --- a/testing/src/pages/_app/session/remote-assignment.page.ts +++ b/testing/src/pages/_app/session/remote-assignment.page.ts @@ -28,6 +28,12 @@ export class RemoteAssignmentPage extends AppPage { this.closeResultButton = page.getByRole('button', { name: 'Close' }).first(); } + /** Language options are named in the interface language, e.g. 'French' for an English reader. */ + async chooseLanguage(name: string) { + await this.createDialog.getByTestId('administration-language').click(); + await this.$ref.getByRole('option', { name }).click(); + } + /** Cards carry a content-hash testid, so match on the visible title instead. */ instrumentCard(title: string): Locator { return this.instrumentShowcase.locator('[data-testid^="instrument-card-"]').filter({ hasText: title }).first(); diff --git a/testing/src/specs/accessible-instruments.spec.ts b/testing/src/specs/accessible-instruments.spec.ts index 574e739b7..8c64973f1 100644 --- a/testing/src/specs/accessible-instruments.spec.ts +++ b/testing/src/specs/accessible-instruments.spec.ts @@ -1,6 +1,28 @@ +import type { Page } from '@playwright/test'; + +import { AccessibleInstrumentsPage } from '../pages/_app/instruments/accessible-instruments.page'; +import { RenderInstrumentPage } from '../pages/_app/instruments/render/$id.page'; import { PHONE_VIEWPORT } from '../support/constants'; import { expect, test } from '../support/fixtures'; +import type { GetPageModel } from '../support/fixtures'; + +/** + * Starts a session, then reaches Administer Instrument through the sidebar: the session lives in + * the client's memory, so a hard navigation would drop it and disable the nav buttons. + */ +async function openAdministerWithSession(getPageModel: GetPageModel, page: Page, uniqueId: string) { + const startSessionPage = await getPageModel('/session/start-session'); + await startSessionPage.sessionForm.waitFor({ state: 'visible' }); + await startSessionPage.selectIdentificationMethod('PERSONAL_INFO'); + await startSessionPage.fillSessionForm(`Administer${uniqueId}`, `Subject${uniqueId}`, 'Female'); + await startSessionPage.submitForm(); + await expect(startSessionPage.successMessage).toBeVisible(); + await page.getByTestId('nav-button-/instruments/accessible-instruments').click(); + await page.waitForURL('**/instruments/accessible-instruments'); + return new AccessibleInstrumentsPage(page); +} + test.describe('accessible instruments on a phone', () => { test.use({ viewport: PHONE_VIEWPORT }); @@ -18,3 +40,20 @@ test.describe('accessible instruments on a phone', () => { expect(kindFilterBox.y).toBeGreaterThanOrEqual(searchBarBox.y + searchBarBox.height); }); }); + +test.describe('administering an instrument', () => { + test('should run the instrument in the language chosen while the rest of the app keeps its own', async ({ + getPageModel, + page, + uniqueId + }) => { + const accessibleInstrumentsPage = await openAdministerWithSession(getPageModel, page, uniqueId); + await accessibleInstrumentsPage.chooseCardLanguage('Happiness Questionnaire', 'French'); + await accessibleInstrumentsPage.instrumentCard('Happiness Questionnaire').click(); + + const instrumentPage = new RenderInstrumentPage(page); + await instrumentPage.begin(); + await expect(page.getByText('Dans quelle mesure êtes-vous satisfait de votre vie personnelle ?')).toBeVisible(); + await expect(page.getByTestId('nav-button-/instruments/accessible-instruments')).toContainText('Administer'); + }); +}); diff --git a/testing/src/specs/gateway-landing.spec.ts b/testing/src/specs/gateway-landing.spec.ts index c2ef82810..19bfcab92 100644 --- a/testing/src/specs/gateway-landing.spec.ts +++ b/testing/src/specs/gateway-landing.spec.ts @@ -12,4 +12,24 @@ test.describe('gateway landing page', () => { await expect(landing).toBeVisible(); await expect(landing.getByRole('heading')).toHaveText('Bienvenue'); }); + + // A link is created before anyone knows what its reader speaks, so most carry no `lang` at all. + // The browser's own Accept-Language is then what decides, server-side, so the first paint is + // already in their language rather than swapping after hydration. + test('should open a link with no language in the language the browser asks for', async ({ browser }) => { + const frenchContext = await browser.newContext({ locale: 'fr-CA' }); + const frenchPage = await frenchContext.newPage(); + const landing = await frenchPage.goto(gatewayURL); + expect(await landing!.text()).toContain('Bienvenue'); + await expect(frenchPage.getByTestId('gateway-landing').getByRole('heading')).toHaveText('Bienvenue'); + await frenchContext.close(); + }); + + test('should prefer the language the link names over the one the browser asks for', async ({ browser }) => { + const frenchContext = await browser.newContext({ locale: 'fr-CA' }); + const frenchPage = await frenchContext.newPage(); + const english = await frenchPage.goto(`${gatewayURL}/?lang=en`); + expect(await english!.text()).toContain('Welcome'); + await frenchContext.close(); + }); }); diff --git a/testing/src/specs/mail.spec.ts b/testing/src/specs/mail.spec.ts index 19947c096..b2ee2ef82 100644 --- a/testing/src/specs/mail.spec.ts +++ b/testing/src/specs/mail.spec.ts @@ -97,5 +97,24 @@ test.describe('mail delivery', () => { expect(entry?.metadata?.recipient).toBe('p***@example.org'); expect(JSON.stringify(entries)).not.toContain(recipient); }); + + // A failed delivery still returns the rendered message, so the link it carried can be read back. + test('should email the link in the language the assignment was created in, whatever the email language', async ({ + api + }) => { + const group = await api.createGroup(); + const assignment = await api.createAssignment({ + expiresAt: new Date(Date.now() + 86_400_000), + groupId: group.id, + instrumentId: await api.findInstrumentId('FORM'), + language: 'fr', + subjectId: await api.createSubject(group.id) + }); + expect(assignment.url).toMatch(/\?lang=fr$/); + + const result = await api.sendAssignmentEmail(assignment.id, { language: 'en', recipient: 'p@example.org' }); + expect(result.message).toContain(assignment.url); + expect(result.message).not.toContain('lang=en'); + }); }); }); diff --git a/testing/src/specs/remote-assignment.spec.ts b/testing/src/specs/remote-assignment.spec.ts index a6c5cab92..34fe033df 100644 --- a/testing/src/specs/remote-assignment.spec.ts +++ b/testing/src/specs/remote-assignment.spec.ts @@ -112,6 +112,35 @@ test.describe('remote assignment', () => { await expect(remoteAssignmentPage.urlInput).not.toHaveValue(firstUrl); }); + // The default leaves the link without a language, so the gateway reads the subject's browser. + test('should create a link with no language unless one is chosen', async ({ getPageModel, page, uniqueId }) => { + await startSession(getPageModel, `Default${uniqueId}`, `User${uniqueId}`, 'Female'); + await page.getByTestId('nav-button-/session/remote-assignment').click(); + await page.waitForURL('**/session/remote-assignment'); + const remoteAssignmentPage = new RemoteAssignmentPage(page); + await remoteAssignmentPage.selectInstrument('Happiness Questionnaire'); + await remoteAssignmentPage.submitAssignmentForm(); + await expect(remoteAssignmentPage.urlInput).toHaveValue(/\/assignments\/[^?]+$/); + }); + + test('should create a link that opens the gateway in the language chosen for the assignment', async ({ + getPageModel, + page, + uniqueId + }) => { + await startSession(getPageModel, `Language${uniqueId}`, `User${uniqueId}`, 'Female'); + + await page.getByTestId('nav-button-/session/remote-assignment').click(); + await page.waitForURL('**/session/remote-assignment'); + + const remoteAssignmentPage = new RemoteAssignmentPage(page); + await remoteAssignmentPage.selectInstrument('Happiness Questionnaire'); + await remoteAssignmentPage.chooseLanguage('French'); + await remoteAssignmentPage.submitAssignmentForm(); + + await expect(remoteAssignmentPage.urlInput).toHaveValue(/\/assignments\/[^?]+\?lang=fr$/); + }); + // Entering by URL is the path a bookmarked link takes, and it runs the GATEWAY_ENABLED guard in // `beforeLoad` on a cold document load rather than on a client-side transition from the tab. // `goto` asserts it landed on the URL it asked for, so a guard that wrongly bounced the request