From 84656b68a494a59a39bb9371c8ffac605116e25e Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Wed, 18 Nov 2026 23:56:27 -0500 Subject: [PATCH 1/9] feat: choose the language when administering or assigning an instrument Each card on Administer Instrument carries a Language dropdown where the instrument offers more than one, set to the interface language, so the clinician changes it in place and the instrument still starts on one click. Only the languages the instance has active are offered, and a card with no choice to make carries no dropdown. - Administering: the chosen language applies to the instrument only, interactive instruments included, so the application interface keeps its own language and a switch from inside the instrument no longer moves the interface with it. - Assigning: the create dialog asks for the language, and the assignment carries it on the link as ?lang=, which the gateway already honours, so the copied link, the QR code and the emailed link all open in the same language. The email language changes only the email text; a link created without a language still takes the email's. Co-Authored-By: Claude Opus 5 --- .../__tests__/assignments.controller.test.ts | 10 ++ .../__tests__/assignments.service.test.ts | 6 + .../__tests__/assignments.utils.test.ts | 23 +++ .../src/assignments/assignments.controller.ts | 5 +- .../src/assignments/assignments.service.ts | 11 +- apps/api/src/assignments/assignments.utils.ts | 14 ++ .../AdministrationOptions.tsx | 31 ++++ .../__tests__/AdministrationOptions.test.tsx | 37 +++++ .../components/AdministrationOptions/index.ts | 1 + .../AssignmentEmailForm.tsx | 13 +- .../InstrumentCard/InstrumentCard.tsx | 63 ++++++-- .../InstrumentShowcase/InstrumentShowcase.tsx | 42 ++++- .../__tests__/InstrumentShowcase.test.tsx | 64 +++++++- .../LanguageSelect/LanguageSelect.tsx | 10 +- .../__tests__/useAdministrationChoice.test.ts | 67 ++++++++ apps/web/src/hooks/useAdministrationChoice.ts | 36 +++++ .../__tests__/accessible-instruments.test.tsx | 76 ++++++--- .../instruments/accessible-instruments.tsx | 8 +- .../routes/_app/instruments/render/$id.tsx | 7 +- .../instruments/render/__tests__/$id.test.tsx | 23 ++- .../__tests__/remote-assignment.test.tsx | 54 ++++++- .../routes/_app/session/remote-assignment.tsx | 144 ++++++++++-------- .../__tests__/administration-choice.test.ts | 42 +++++ apps/web/src/utils/administration-choice.ts | 34 +++++ .../3.4-how-to-get-started-with-odc.mdx | 2 + .../InstrumentRenderer/InstrumentRenderer.tsx | 3 + .../ScalarInstrumentRenderer.tsx | 10 +- .../SeriesInstrumentRenderer.tsx | 16 +- .../InteractiveContent/InteractiveContent.tsx | 32 ++-- .../__tests__/InteractiveContent.test.tsx | 36 +++++ .../__tests__/useInstrumentLanguage.test.ts | 59 +++++++ .../useInterpretedInstrument.test.ts | 18 +++ .../src/hooks/useInstrumentLanguage.ts | 29 ++++ .../src/hooks/useInterpretedInstrument.ts | 12 +- packages/schemas/src/assignment/assignment.ts | 4 +- .../accessible-instruments.page.ts | 9 ++ .../_app/session/remote-assignment.page.ts | 6 + .../src/specs/accessible-instruments.spec.ts | 37 +++++ testing/src/specs/mail.spec.ts | 19 +++ testing/src/specs/remote-assignment.spec.ts | 18 +++ 40 files changed, 986 insertions(+), 145 deletions(-) create mode 100644 apps/api/src/assignments/__tests__/assignments.utils.test.ts create mode 100644 apps/api/src/assignments/assignments.utils.ts create mode 100644 apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx create mode 100644 apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx create mode 100644 apps/web/src/components/AdministrationOptions/index.ts create mode 100644 apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts create mode 100644 apps/web/src/hooks/useAdministrationChoice.ts create mode 100644 apps/web/src/utils/__tests__/administration-choice.test.ts create mode 100644 apps/web/src/utils/administration-choice.ts create mode 100644 packages/react-core/src/hooks/__tests__/useInstrumentLanguage.test.ts create mode 100644 packages/react-core/src/hooks/useInstrumentLanguage.ts diff --git a/apps/api/src/assignments/__tests__/assignments.controller.test.ts b/apps/api/src/assignments/__tests__/assignments.controller.test.ts index fb8d392e0..c4047cfdd 100644 --- a/apps/api/src/assignments/__tests__/assignments.controller.test.ts +++ b/apps/api/src/assignments/__tests__/assignments.controller.test.ts @@ -241,6 +241,16 @@ describe('AssignmentsController', () => { }); }); + it('keeps the language the assignment was created in, so the emailed link matches the copied one', 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` }] + }); + }); + // Every admin reads the audit log, so it records the domain the link went to, not the address. it('records who sent what to which masked address, with the outcome, in the audit entry', async () => { assignmentsService.findById.mockResolvedValueOnce(assignment); 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/__tests__/assignments.utils.test.ts b/apps/api/src/assignments/__tests__/assignments.utils.test.ts new file mode 100644 index 000000000..7af22516c --- /dev/null +++ b/apps/api/src/assignments/__tests__/assignments.utils.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { withLinkLanguage } from '../assignments.utils'; + +describe('withLinkLanguage', () => { + it('should add ?lang= to a link with no query', () => { + expect(withLinkLanguage('https://gateway.example/assignments/abc', 'fr')).toBe( + 'https://gateway.example/assignments/abc?lang=fr' + ); + }); + + it('should keep the language a link was created in, so an email in another language cannot re-point it', () => { + expect(withLinkLanguage('https://gateway.example/assignments/abc?lang=en', 'es')).toBe( + 'https://gateway.example/assignments/abc?lang=en' + ); + }); + + it('should keep other query parameters', () => { + expect(withLinkLanguage('https://gateway.example/assignments/abc?x=1', 'en')).toBe( + 'https://gateway.example/assignments/abc?x=1&lang=en' + ); + }); +}); diff --git a/apps/api/src/assignments/assignments.controller.ts b/apps/api/src/assignments/assignments.controller.ts index eb218ccde..f1821ec99 100644 --- a/apps/api/src/assignments/assignments.controller.ts +++ b/apps/api/src/assignments/assignments.controller.ts @@ -41,6 +41,7 @@ import { MailService } from '@/mail/mail.service'; import { redactEmails } from '@/mail/mail.utils'; import { AssignmentsService } from './assignments.service'; +import { withLinkLanguage } from './assignments.utils'; @Controller('assignments') export class AssignmentsController { @@ -132,7 +133,7 @@ export class AssignmentsController { language, links: assignments.map((assignment) => ({ expiresAt: assignment.expiresAt, - url: `${assignment.url}?lang=${language}` + url: withLinkLanguage(assignment.url, language) })), recipient, template: await this.resolveTemplate(groupId ?? null, templateId, ability) @@ -156,7 +157,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: withLinkLanguage(assignment.url, language) }], 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..0a75c117d 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'; @@ -22,6 +23,8 @@ import type { EntityOperationOptions } from '@/core/types'; import { GatewayService } from '@/gateway/gateway.service'; import { InstrumentsService } from '@/instruments/instruments.service'; +import { withLinkLanguage } from './assignments.utils'; + /** * How many assignments a batch prepares at once. Key generation is CPU-bound, so an unbounded * `Promise.all` over 500 subjects would hold the event loop for the whole batch and stall every @@ -76,7 +79,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 +99,7 @@ export class AssignmentsService { expiresAt, groupId, instrumentId, + language, redirectUrl, subjectId }); @@ -350,17 +354,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 +381,7 @@ export class AssignmentsService { redirectUrl, status: 'OUTSTANDING', subject: { connect: { id: subjectId } }, - url: `${this.assignmentBaseUrl}/assignments/${id}` + url: language ? withLinkLanguage(link, language) : link } }); return { assignment, publicKey }; diff --git a/apps/api/src/assignments/assignments.utils.ts b/apps/api/src/assignments/assignments.utils.ts new file mode 100644 index 000000000..7285778c3 --- /dev/null +++ b/apps/api/src/assignments/assignments.utils.ts @@ -0,0 +1,14 @@ +import type { Language } from '@opendatacapture/schemas/core'; + +/** + * The assignment link, opening the gateway in `language` unless the link already names one. The + * gateway reads it from `?lang=`. A language chosen when the assignment was created is kept, so an + * email written in another language cannot send the subject a link that differs from the copied one. + */ +export function withLinkLanguage(url: string, language: Language): string { + const link = new URL(url); + if (!link.searchParams.has('lang')) { + link.searchParams.set('lang', language); + } + return link.href; +} diff --git a/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx new file mode 100644 index 000000000..1888ec2c5 --- /dev/null +++ b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx @@ -0,0 +1,31 @@ +import { Label } from '@douglasneuroinformatics/libui/components'; +import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import type { Language } from '@opendatacapture/schemas/core'; + +import type { AdministrationChoice } from '@/utils/administration-choice'; + +import { LanguageSelect } from '../LanguageSelect'; + +type AdministrationOptionsProps = { + choice: AdministrationChoice; + onLanguageChange: (language: Language) => void; +}; + +export const AdministrationOptions = ({ choice, onLanguageChange }: AdministrationOptionsProps) => { + const { t } = useTranslation(); + if (!choice.language || 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..95223ad58 --- /dev/null +++ b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx @@ -0,0 +1,37 @@ +import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; +import { cleanup, 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']>) => { + render( + + ); +}; + +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(); + }); +}); 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..6b43f3c96 100644 --- a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx +++ b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx @@ -18,17 +18,19 @@ 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); @@ -154,11 +156,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." })}

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..959bdc93f 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 @@ -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,26 @@ 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. */ +const waitForLink = () => { + return waitFor(() => expect(screen.getByRole('link', { name: 'Assignment Link' })).toBeTruthy()); +}; + 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 +233,30 @@ describe('Route', () => { expiresAt: new Date('2026-01-08'), groupId: 'group-1', instrumentId: 'instrument-1', + language: 'en', subjectId: 'subject-1' } }); }); + 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 only the languages the gateway serves, so the link cannot ask for one it would ignore', async () => { + mocks.activeLanguages = ['fr']; + selectInstrument(); + expect(screen.queryByTestId('administration-language')).toBeNull(); + submitForm(); + await waitForLink(); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: 'fr' }) }); + }); + 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 +271,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 +283,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 +303,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: 'en', + 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..e297b8113 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,12 +138,12 @@ 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..d2fb63e91 --- /dev/null +++ b/apps/web/src/utils/__tests__/administration-choice.test.ts @@ -0,0 +1,42 @@ +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']), { 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']), { 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/administration-choice.ts b/apps/web/src/utils/administration-choice.ts new file mode 100644 index 000000000..fae458a13 --- /dev/null +++ b/apps/web/src/utils/administration-choice.ts @@ -0,0 +1,34 @@ +import type { Language } from '@opendatacapture/schemas/core'; +import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; + +type AdministrationChoice = { + instrument: TranslatedInstrumentInfo; + /** Absent only when the instrument offers none of the allowed languages. */ + language: Language | undefined; + languageOptions: Language[]; +}; + +type AdministrationChoiceOptions = { + /** Narrows the instrument's own languages, e.g. 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 language a picked instrument is administered in, and the languages it could be. */ +function getAdministrationChoice( + instrument: TranslatedInstrumentInfo, + { allowedLanguages, preferredLanguage }: AdministrationChoiceOptions +): AdministrationChoice { + const languageOptions: Language[] = instrument.supportedLanguages.filter( + (language) => !allowedLanguages || allowedLanguages.includes(language) + ); + return { + instrument, + language: languageOptions.includes(preferredLanguage) ? preferredLanguage : languageOptions[0], + languageOptions + }; +} + +export { getAdministrationChoice }; +export type { AdministrationChoice }; 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.tsx b/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx index 0bb05e159..1e7d5f571 100644 --- a/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx +++ b/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx @@ -23,11 +23,15 @@ 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 contentLanguage = language ?? resolvedLanguage; + const changeContentLanguage = onChangeLanguage ?? changeLanguage; const [_, updateTheme] = useTheme(); const [scale, setScale] = useState(100); const [hasSelectedLanguage, setHasSelectedLanguage] = useState( @@ -58,9 +62,9 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeLanguage(requested.data); + changeContentLanguage(requested.data); }, - [addNotification, changeLanguage, isLocked, t] + [addNotification, changeContentLanguage, isLocked, t] ); const handleChangeThemeEvent = useCallback( @@ -162,7 +166,7 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeLanguage(language); + changeContentLanguage(language); }} > {LANGUAGE_LABELS[language][resolvedLanguage]} @@ -177,7 +181,7 @@ const _InteractiveContent = React.memo(function _Intera allow="fullscreen" className="origin-top-left" data-bundle={bundle} - lang={resolvedLanguage} + lang={contentLanguage} name="interactive-instrument" ref={iFrameRef} src="/runtime/v1/@opendatacapture/runtime-internal/interactive/iframe.html" @@ -201,7 +205,7 @@ const _InteractiveContent = React.memo(function _Intera key={language} type="button" onClick={() => { - changeLanguage(language); + changeContentLanguage(language); setHasSelectedLanguage(true); }} > @@ -259,11 +263,19 @@ export type InteractiveContentProps = Simplify< Pick< InteractiveInstrument['content'], 'defaultFullscreen' | 'enableLanguageLock' | 'enableLanguageSelect' | 'enableLanguageToggle' - > & { - bundle: string; - onSubmit: (result: InteractiveContentSubmitResult) => Promisable; - supportedLanguages?: Language[]; - } + > & + ( + | { + /** The language the instrument runs in, held by the host instead of the interface language. */ + language: InterfaceLanguage; + onChangeLanguage: (language: InterfaceLanguage) => void; + } + | { language?: never; onChangeLanguage?: never } + ) & { + bundle: string; + onSubmit: (result: InteractiveContentSubmitResult) => Promisable; + supportedLanguages?: Language[]; + } >; // eslint-disable-next-line react/function-component-definition -- the named function passed to memo gives the component its display name 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..57935358b 100644 --- a/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx +++ b/packages/react-core/src/components/InteractiveContent/__tests__/InteractiveContent.test.tsx @@ -156,6 +156,42 @@ describe('InteractiveContent', () => { expect(addNotification).toHaveBeenCalledWith({ message: 'From the bundle', type: 'success' }); }); + it('should run the iframe in the interface language when the host holds no language', () => { + render(); + expect(screen.getByTitle('Open Data Capture - Interactive Instrument').getAttribute('lang')).toBe('en'); + }); + + 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(); expect(screen.getByText('100%')).toBeTruthy(); 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..1f7fccf5f 100644 --- a/testing/src/specs/accessible-instruments.spec.ts +++ b/testing/src/specs/accessible-instruments.spec.ts @@ -1,6 +1,25 @@ +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 { StartSessionPage } from '../pages/_app/session/start-session.page'; import { PHONE_VIEWPORT } from '../support/constants'; import { expect, test } from '../support/fixtures'; +/** Starts a session, then reaches Administer Instrument through the sidebar, which keeps the in-memory session. */ +async function openAdministerWithSession(page: Page, uniqueId: string) { + const startSessionPage = new StartSessionPage(page); + await startSessionPage.goto('/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 +37,21 @@ 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 ({ + authenticateAs, + page, + uniqueId + }) => { + await authenticateAs('GROUP_MANAGER'); + const accessibleInstrumentsPage = await openAdministerWithSession(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/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..6ecb032b4 100644 --- a/testing/src/specs/remote-assignment.spec.ts +++ b/testing/src/specs/remote-assignment.spec.ts @@ -112,6 +112,24 @@ test.describe('remote assignment', () => { await expect(remoteAssignmentPage.urlInput).not.toHaveValue(firstUrl); }); + 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 From 4b26ea283e69e68c6a7e654f373dff6a1dc97748 Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Thu, 19 Nov 2026 02:26:15 -0500 Subject: [PATCH 2/9] feat(gateway): open a link with no language in the language the browser asks for A link is created before anyone knows what its reader speaks, so most carry no language of their own. Until now one of those opened in the instance's first active language whatever the reader's browser asked for; it now negotiates Accept-Language and falls back to that first active language only when the browser asks for none the instance has. Resolved server-side, like the ?lang= it falls back from, so the server-rendered pass and the hydration pass agree rather than rendering one language and swapping. Co-Authored-By: Claude Opus 5 --- .../src/lib/__tests__/setup-state.test.ts | 40 +++++++++++++++++ apps/gateway/src/lib/setup-state.ts | 45 ++++++++++++++++--- apps/gateway/src/routers/root.router.ts | 4 +- testing/src/specs/gateway-landing.spec.ts | 24 ++++++++++ 4 files changed, 104 insertions(+), 9 deletions(-) diff --git a/apps/gateway/src/lib/__tests__/setup-state.test.ts b/apps/gateway/src/lib/__tests__/setup-state.test.ts index cbf0179b8..8e5601983 100644 --- a/apps/gateway/src/lib/__tests__/setup-state.test.ts +++ b/apps/gateway/src/lib/__tests__/setup-state.test.ts @@ -36,4 +36,44 @@ 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 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'); + }); }); diff --git a/apps/gateway/src/lib/setup-state.ts b/apps/gateway/src/lib/setup-state.ts index cdf6cb818..122fe6604 100644 --- a/apps/gateway/src/lib/setup-state.ts +++ b/apps/gateway/src/lib/setup-state.ts @@ -2,6 +2,29 @@ import { $Language, DEFAULT_ACTIVE_LANGUAGES, resolveActiveLanguage } from '@ope 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 unparseable quality is + * treated as the default of 1 rather than discarded, since a client that sends one still wants the + * language it named. + */ +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*$/u.exec(parameter)?.groups?.value) + .find((value) => value !== undefined); + return { quality: quality === undefined ? 1 : Number.parseFloat(quality) || 0, 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 +41,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) { + return resolveActiveLanguage(requestedLanguage.data, activeLanguages); + } + 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/root.router.ts b/apps/gateway/src/routers/root.router.ts index 10d38e56c..c5b76e3b6 100644 --- a/apps/gateway/src/routers/root.router.ts +++ b/apps/gateway/src/routers/root.router.ts @@ -50,7 +50,7 @@ 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 @@ -63,7 +63,7 @@ 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); }); diff --git a/testing/src/specs/gateway-landing.spec.ts b/testing/src/specs/gateway-landing.spec.ts index c2ef82810..76f242237 100644 --- a/testing/src/specs/gateway-landing.spec.ts +++ b/testing/src/specs/gateway-landing.spec.ts @@ -12,4 +12,28 @@ 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(); + await expect(async () => { + const landing = await frenchPage.goto(gatewayURL); + expect(await landing!.text()).toContain('Bienvenue'); + }).toPass({ timeout: STALE_SETUP_STATE_TIMEOUT }); + 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(); + await expect(async () => { + const english = await frenchPage.goto(`${gatewayURL}/?lang=en`); + expect(await english!.text()).toContain('Welcome'); + }).toPass({ timeout: STALE_SETUP_STATE_TIMEOUT }); + await frenchContext.close(); + }); }); From b8b185e86ae2184f096470b95fe69655c1ec4834 Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Thu, 19 Nov 2026 02:26:23 -0500 Subject: [PATCH 3/9] feat(web): leave a remote assignment's language to the subject's browser by default The create dialog now offers the subject's browser language, which it starts on, beside one option per language the instrument offers. Choosing the default stores no language on the link, so the gateway reads the browser; choosing a language pins the link to it. Emailing no longer sets a language on a link that has none: with the browser default that is the common case, and setting it would override the subject's own browser from the sender's choice of email language. The email language now only ever changes the email text, and a confirmation asks before sending an email in a language the link does not open in. Co-Authored-By: Claude Opus 5 --- .../__tests__/assignments.controller.test.ts | 12 ++-- .../__tests__/assignments.utils.test.ts | 4 +- .../src/assignments/assignments.controller.ts | 5 +- apps/api/src/assignments/assignments.utils.ts | 12 ++-- .../AdministrationOptions.tsx | 46 +++++++++++---- .../__tests__/AdministrationOptions.test.tsx | 34 +++++++++-- .../AssignmentEmailForm.tsx | 25 +++++++- .../ConfirmEmailLanguageDialog.tsx | 59 +++++++++++++++++++ .../__tests__/AssignmentEmailForm.test.tsx | 57 ++++++++++++++++++ .../__tests__/useAdministrationChoice.test.ts | 14 ++--- apps/web/src/hooks/useAdministrationChoice.ts | 20 +++---- .../__tests__/remote-assignment.test.tsx | 18 ++++-- .../utils/__tests__/assignment-link.test.ts | 17 ++++++ apps/web/src/utils/administration-choice.ts | 21 +++++-- apps/web/src/utils/assignment-link.ts | 13 ++++ testing/src/specs/remote-assignment.spec.ts | 11 ++++ 16 files changed, 305 insertions(+), 63 deletions(-) create mode 100644 apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx create mode 100644 apps/web/src/utils/__tests__/assignment-link.test.ts create mode 100644 apps/web/src/utils/assignment-link.ts diff --git a/apps/api/src/assignments/__tests__/assignments.controller.test.ts b/apps/api/src/assignments/__tests__/assignments.controller.test.ts index c4047cfdd..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,11 +237,11 @@ 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('keeps the language the assignment was created in, so the emailed link matches the copied one', async () => { + 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' }); @@ -339,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.utils.test.ts b/apps/api/src/assignments/__tests__/assignments.utils.test.ts index 7af22516c..2dd4e3862 100644 --- a/apps/api/src/assignments/__tests__/assignments.utils.test.ts +++ b/apps/api/src/assignments/__tests__/assignments.utils.test.ts @@ -9,9 +9,9 @@ describe('withLinkLanguage', () => { ); }); - it('should keep the language a link was created in, so an email in another language cannot re-point it', () => { + it('should replace a language already on the link rather than name two', () => { expect(withLinkLanguage('https://gateway.example/assignments/abc?lang=en', 'es')).toBe( - 'https://gateway.example/assignments/abc?lang=en' + 'https://gateway.example/assignments/abc?lang=es' ); }); diff --git a/apps/api/src/assignments/assignments.controller.ts b/apps/api/src/assignments/assignments.controller.ts index f1821ec99..270600874 100644 --- a/apps/api/src/assignments/assignments.controller.ts +++ b/apps/api/src/assignments/assignments.controller.ts @@ -41,7 +41,6 @@ import { MailService } from '@/mail/mail.service'; import { redactEmails } from '@/mail/mail.utils'; import { AssignmentsService } from './assignments.service'; -import { withLinkLanguage } from './assignments.utils'; @Controller('assignments') export class AssignmentsController { @@ -133,7 +132,7 @@ export class AssignmentsController { language, links: assignments.map((assignment) => ({ expiresAt: assignment.expiresAt, - url: withLinkLanguage(assignment.url, language) + url: assignment.url })), recipient, template: await this.resolveTemplate(groupId ?? null, templateId, ability) @@ -157,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: withLinkLanguage(assignment.url, 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.utils.ts b/apps/api/src/assignments/assignments.utils.ts index 7285778c3..a23272af1 100644 --- a/apps/api/src/assignments/assignments.utils.ts +++ b/apps/api/src/assignments/assignments.utils.ts @@ -1,14 +1,14 @@ import type { Language } from '@opendatacapture/schemas/core'; /** - * The assignment link, opening the gateway in `language` unless the link already names one. The - * gateway reads it from `?lang=`. A language chosen when the assignment was created is kept, so an - * email written in another language cannot send the subject a link that differs from the copied one. + * The assignment link, opening the gateway in `language`, which it reads from `?lang=`. + * + * Set only when the assignment is created: a link left without a language is one the subject's own + * browser decides, and nothing later — an email written in another language included — overrides + * that. */ export function withLinkLanguage(url: string, language: Language): string { const link = new URL(url); - if (!link.searchParams.has('lang')) { - link.searchParams.set('lang', language); - } + link.searchParams.set('lang', language); return link.href; } diff --git a/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx index 1888ec2c5..823e14603 100644 --- a/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx +++ b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx @@ -1,31 +1,55 @@ -import { Label } from '@douglasneuroinformatics/libui/components'; +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'; -import { LanguageSelect } from '../LanguageSelect'; +/** 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) => void; + 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.language || choice.languageOptions.length < 2) { + 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 index 95223ad58..bc6544ace 100644 --- a/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx +++ b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx @@ -1,5 +1,5 @@ import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; -import { cleanup, render, screen } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { AdministrationOptions } from '../AdministrationOptions'; @@ -8,13 +8,22 @@ import '@/services/i18n'; const instrument = { details: { title: 'Scale' }, id: 'scale', kind: 'FORM' } as unknown as TranslatedInstrumentInfo; -const renderOptions = (choice: Partial[0]['choice']>) => { +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', () => { @@ -34,4 +43,21 @@ describe('AdministrationOptions', () => { 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/AssignmentEmailForm/AssignmentEmailForm.tsx b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx index 6b43f3c96..38c9f2c9f 100644 --- a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx +++ b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx @@ -12,8 +12,11 @@ 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 = { @@ -33,6 +36,7 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan 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 @@ -65,10 +69,14 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan // 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. + const linkLanguage = assignment ? getLinkLanguage(assignment.url) : undefined; + const handleSendEmail = () => { if (!assignment || !recipient) { return; } + setIsConfirmingLanguage(false); setFeedback(null); const fail = (message: string) => { setFeedback({ message, tone: 'error' }); @@ -204,7 +212,13 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan 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…' }) @@ -223,6 +237,15 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan {feedback.message}

    )} + {linkLanguage && ( + + )} ); }; diff --git a/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx new file mode 100644 index 000000000..be549bbe1 --- /dev/null +++ b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx @@ -0,0 +1,59 @@ +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, or null while the dialog is closed. */ + emailLanguage: Language | null; + 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. + */ +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 ?? linkLanguage]), 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..c61b842bf 100644 --- a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx +++ b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx @@ -329,4 +329,61 @@ 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()); + }); + + 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/hooks/__tests__/useAdministrationChoice.test.ts b/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts index 9e424d683..7cb1311c9 100644 --- a/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts +++ b/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts @@ -24,14 +24,14 @@ describe('useAdministrationChoice', () => { expect(result.current.choice).toBeNull(); }); - it('should start a pick at the interface language', () => { + it('should start a pick with no language, leaving it to the browser that opens the link', () => { const { result } = renderHook(() => useAdministrationChoice()); let picked: ReturnType | undefined; act(() => { picked = result.current.pick(scale); }); - expect(picked).toMatchObject({ instrument: { id: 'scale' }, language: 'en' }); - expect(result.current.choice).toMatchObject({ instrument: { id: 'scale' }, language: 'en' }); + expect(picked).toMatchObject({ instrument: { id: 'scale' }, language: undefined }); + expect(result.current.choice).toMatchObject({ instrument: { id: 'scale' }, language: undefined }); }); it('should keep the language the user chose', () => { @@ -45,7 +45,7 @@ describe('useAdministrationChoice', () => { expect(result.current.choice?.language).toBe('fr'); }); - it('should reset the language to the interface language on the next pick', () => { + it('should forget a chosen language on the next pick, so it cannot carry to another instrument', () => { const { result } = renderHook(() => useAdministrationChoice()); act(() => { result.current.pick(scale); @@ -54,14 +54,14 @@ describe('useAdministrationChoice', () => { act(() => { result.current.pick(instrument('other')); }); - expect(result.current.choice?.language).toBe('en'); + expect(result.current.choice?.language).toBeUndefined(); }); - it('should offer only the allowed languages, so a language the instance turned off is never used', () => { + it('should offer only the allowed languages, so a language the instance turned off is never offered', () => { const { result } = renderHook(() => useAdministrationChoice(['fr'])); act(() => { result.current.pick(scale); }); - expect(result.current.choice).toMatchObject({ language: 'fr', languageOptions: ['fr'] }); + expect(result.current.choice).toMatchObject({ languageOptions: ['fr'] }); }); }); diff --git a/apps/web/src/hooks/useAdministrationChoice.ts b/apps/web/src/hooks/useAdministrationChoice.ts index 8814a5162..3438e4105 100644 --- a/apps/web/src/hooks/useAdministrationChoice.ts +++ b/apps/web/src/hooks/useAdministrationChoice.ts @@ -1,35 +1,33 @@ import { useState } from 'react'; -import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { Language } from '@opendatacapture/schemas/core'; import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument'; -import { getAdministrationChoice } from '@/utils/administration-choice'; +import { getLanguageOptions } from '@/utils/administration-choice'; import type { AdministrationChoice } from '@/utils/administration-choice'; /** - * The language a picked instrument is administered in. Picking an instrument starts at the interface - * language, falling back as {@link getAdministrationChoice} does. + * The language a picked instrument is assigned in. No language is chosen to begin with, which + * leaves it to the subject's browser — the assignment is made before anyone knows what they read. * * @param allowedLanguages - narrows the instrument's own languages, e.g. to the instance's active ones */ export function useAdministrationChoice(allowedLanguages?: readonly Language[]) { - const { resolvedLanguage } = useTranslation(); const [instrument, setInstrument] = useState(null); - const [preferredLanguage, setLanguage] = useState(resolvedLanguage); + const [language, setLanguage] = useState(undefined); - const describe = (picked: TranslatedInstrumentInfo, preferred: Language): AdministrationChoice => { - return getAdministrationChoice(picked, { allowedLanguages, preferredLanguage: preferred }); + const describe = (picked: TranslatedInstrumentInfo, chosen: Language | undefined): AdministrationChoice => { + return { instrument: picked, language: chosen, languageOptions: getLanguageOptions(picked, allowedLanguages) }; }; const pick = (picked: TranslatedInstrumentInfo): AdministrationChoice => { setInstrument(picked); - setLanguage(resolvedLanguage); - return describe(picked, resolvedLanguage); + setLanguage(undefined); + return describe(picked, undefined); }; return { - choice: instrument ? describe(instrument, preferredLanguage) : null, + choice: instrument ? describe(instrument, language) : null, pick, setLanguage }; 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 959bdc93f..1953e485d 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 @@ -223,7 +223,8 @@ describe('Route', () => { fireEvent.blur(input); submitForm(); expect(await screen.findByText('Expiry date must be in the future')).toBeTruthy(); - expect(mocks.mutateAsync).not.toHaveBeenCalled(); + // Settles the form's own submit cycle, so no state update lands after the test has finished. + await waitFor(() => expect(mocks.mutateAsync).not.toHaveBeenCalled()); }); it('should create the assignment, expiring on the chosen day, for the session subject in the current group', async () => { @@ -233,12 +234,17 @@ describe('Route', () => { expiresAt: new Date('2026-01-08'), groupId: 'group-1', instrumentId: 'instrument-1', - language: 'en', + 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')); @@ -248,13 +254,13 @@ describe('Route', () => { expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: 'fr' }) }); }); - it('should offer only the languages the gateway serves, so the link cannot ask for one it would ignore', async () => { + 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: 'fr' }) }); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ data: expect.objectContaining({ language: undefined }) }); }); it('should refuse a redirect URL that is not https, without creating the assignment', async () => { @@ -262,7 +268,7 @@ describe('Route', () => { fireEvent.change(screen.getByLabelText('Redirect URL (Optional)'), { target: { value: 'http://example.com' } }); submitForm(); await waitFor(() => expect(screen.getByTestId('error-message-text')).toBeTruthy()); - expect(mocks.mutateAsync).not.toHaveBeenCalled(); + await waitFor(() => expect(mocks.mutateAsync).not.toHaveBeenCalled()); }); it('should create the assignment with the redirect URL given', async () => { @@ -305,7 +311,7 @@ describe('Route', () => { expect(mocks.QRCode.mock.lastCall?.[0]).toEqual({ url: assignment.url }); expect(mocks.AssignmentEmailForm.mock.lastCall?.[0]).toEqual({ assignment, - initialLanguage: 'en', + initialLanguage: undefined, instrumentLanguages: ['en', 'fr'] }); }); 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 index fae458a13..e361a82cc 100644 --- a/apps/web/src/utils/administration-choice.ts +++ b/apps/web/src/utils/administration-choice.ts @@ -3,7 +3,10 @@ import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrume type AdministrationChoice = { instrument: TranslatedInstrumentInfo; - /** Absent only when the instrument offers none of the allowed languages. */ + /** + * 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[]; }; @@ -15,14 +18,20 @@ type AdministrationChoiceOptions = { preferredLanguage: Language; }; -/** The language a picked instrument is administered in, and the languages it could be. */ +/** 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 || 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: Language[] = instrument.supportedLanguages.filter( - (language) => !allowedLanguages || allowedLanguages.includes(language) - ); + const languageOptions = getLanguageOptions(instrument, allowedLanguages); return { instrument, language: languageOptions.includes(preferredLanguage) ? preferredLanguage : languageOptions[0], @@ -30,5 +39,5 @@ function getAdministrationChoice( }; } -export { getAdministrationChoice }; +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/testing/src/specs/remote-assignment.spec.ts b/testing/src/specs/remote-assignment.spec.ts index 6ecb032b4..34fe033df 100644 --- a/testing/src/specs/remote-assignment.spec.ts +++ b/testing/src/specs/remote-assignment.spec.ts @@ -112,6 +112,17 @@ 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, From 9594ed94875a182b9b7f92bf98e0cbc5861c1c72 Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 12:28:58 -0500 Subject: [PATCH 4/9] fix(gateway): open a link pinned to an inactive language in one the reader asks for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `?lang=` naming a language the instance no longer offers short-circuited the negotiation and rendered the first active language, so a link pinned to a language an administrator later turned off ignored the reader's browser entirely — while a link naming an unparseable language honoured it. Only an active requested language now settles the matter. The negotiated HTML also declares `Vary: Accept-Language`, without which a shared cache may serve one subject the language of another, and the suite pins `locale: 'en-US'` so an assertion on English copy no longer depends on the locale of the machine running it. Co-Authored-By: Claude Opus 5 --- .../src/lib/__tests__/setup-state.test.ts | 5 +++++ apps/gateway/src/lib/setup-state.ts | 6 +++--- .../src/routers/__tests__/root.router.test.ts | 17 +++++++++++++++-- apps/gateway/src/routers/root.router.ts | 4 ++-- testing/playwright.config.ts | 6 +++++- 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/apps/gateway/src/lib/__tests__/setup-state.test.ts b/apps/gateway/src/lib/__tests__/setup-state.test.ts index 8e5601983..0a0373cd5 100644 --- a/apps/gateway/src/lib/__tests__/setup-state.test.ts +++ b/apps/gateway/src/lib/__tests__/setup-state.test.ts @@ -42,6 +42,11 @@ describe('resolveLanguage', () => { 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'); diff --git a/apps/gateway/src/lib/setup-state.ts b/apps/gateway/src/lib/setup-state.ts index 122fe6604..3123116ba 100644 --- a/apps/gateway/src/lib/setup-state.ts +++ b/apps/gateway/src/lib/setup-state.ts @@ -1,4 +1,4 @@ -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'; @@ -52,8 +52,8 @@ export function getActiveLanguages(): ActiveLanguages { export function resolveLanguage(requested: unknown, acceptLanguage?: string): Language { const activeLanguages = getActiveLanguages(); const requestedLanguage = $Language.safeParse(requested); - if (requestedLanguage.success) { - return resolveActiveLanguage(requestedLanguage.data, activeLanguages); + if (requestedLanguage.success && activeLanguages.includes(requestedLanguage.data)) { + return requestedLanguage.data; } const accepted = parseAcceptLanguage(acceptLanguage ?? '') .map((tag) => $Language.safeParse(tag)) 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 c5b76e3b6..bb80a5830 100644 --- a/apps/gateway/src/routers/root.router.ts +++ b/apps/gateway/src/routers/root.router.ts @@ -55,7 +55,7 @@ router.get( 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); }) ); @@ -65,7 +65,7 @@ router.get('/', (req, res) => { kind: 'landing', 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/testing/playwright.config.ts b/testing/playwright.config.ts index 3cc4e9e8c..9224c2eda 100644 --- a/testing/playwright.config.ts +++ b/testing/playwright.config.ts @@ -25,6 +25,10 @@ export default defineConfig({ expect: { timeout: 15_000 }, + // `locale` is pinned because the gateway negotiates the language of a link that carries none from + // Accept-Language, which a browser derives from its locale: left to the host's, every assertion on + // an English string would depend on the developer's own machine. A test about that negotiation opts + // into another locale with its own `browser.newContext({ locale })`. fullyParallel: true, outputDir: path.resolve(import.meta.dirname, '.playwright/output'), projects: [ @@ -34,7 +38,7 @@ export default defineConfig({ dependencies: ['setup'], name: 'chromium', testMatch: '**/specs/**/*.spec.ts', - use: { ...devices['Desktop Chrome'], baseURL, channel: 'chromium', headless: true } + use: { ...devices['Desktop Chrome'], baseURL, channel: 'chromium', headless: true, locale: 'en-US' } } ], reporter: [['html', { open: 'never', outputFolder: path.resolve(import.meta.dirname, '.playwright/report') }]], From cc63a81366e3f5b6bf25066deb2858ff6bb2deef Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 12:29:09 -0500 Subject: [PATCH 5/9] fix(web): start an assignment's email in the language its link opens in The datahub's email form defaulted to the clinician's own interface language, so emailing an assignment pinned to another one warned about a mismatch every time rather than only when the two genuinely diverge. Co-Authored-By: Claude Opus 5 --- .../src/routes/_app/datahub/subjects/$subjectId/assignments.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx b/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx index b333bf3d7..cf8e1a9f4 100644 --- a/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx +++ b/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx @@ -19,6 +19,7 @@ import { useAssignmentsQuery } from '@/hooks/useAssignmentsQuery'; import { useInstrument } from '@/hooks/useInstrument'; import { useInstrumentInfoQuery } from '@/hooks/useInstrumentInfoQuery'; import { useUpdateAssignment } from '@/hooks/useUpdateAssignment'; +import { getLinkLanguage } from '@/utils/assignment-link'; const AssignmentSlider: React.FC<{ assignment: Assignment | null; @@ -58,6 +59,7 @@ const AssignmentSlider: React.FC<{ {assignment?.status === 'OUTSTANDING' && ( From 7ad7af5f87203f3644b67d8ebda2a8142e9ec371 Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 12:29:10 -0500 Subject: [PATCH 6/9] refactor: drop the language-choice shapes nothing outside the tests reached `allowedLanguages` is required where every caller already passed it, `pick` no longer returns a choice its caller discards, and `withLinkLanguage` is inlined at its one call site, which composes the link a line earlier and so can never hand it the existing query the helper existed to replace. Also waits out libui's `suspendWhileSubmitting` window in the remote-assignment tests: the link renders before the form clears its own submitting state, so a test ending on the link left that update to land after teardown. Co-Authored-By: Claude Opus 5 --- .../__tests__/assignments.utils.test.ts | 23 ------------------- .../src/assignments/assignments.service.ts | 7 +++--- apps/api/src/assignments/assignments.utils.ts | 14 ----------- .../__tests__/useAdministrationChoice.test.ts | 12 ++++------ apps/web/src/hooks/useAdministrationChoice.ts | 7 +++--- .../__tests__/remote-assignment.test.tsx | 20 ++++++++++++---- .../__tests__/administration-choice.test.ts | 10 ++++++-- apps/web/src/utils/administration-choice.ts | 8 +++---- 8 files changed, 40 insertions(+), 61 deletions(-) delete mode 100644 apps/api/src/assignments/__tests__/assignments.utils.test.ts delete mode 100644 apps/api/src/assignments/assignments.utils.ts diff --git a/apps/api/src/assignments/__tests__/assignments.utils.test.ts b/apps/api/src/assignments/__tests__/assignments.utils.test.ts deleted file mode 100644 index 2dd4e3862..000000000 --- a/apps/api/src/assignments/__tests__/assignments.utils.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { withLinkLanguage } from '../assignments.utils'; - -describe('withLinkLanguage', () => { - it('should add ?lang= to a link with no query', () => { - expect(withLinkLanguage('https://gateway.example/assignments/abc', 'fr')).toBe( - 'https://gateway.example/assignments/abc?lang=fr' - ); - }); - - it('should replace a language already on the link rather than name two', () => { - expect(withLinkLanguage('https://gateway.example/assignments/abc?lang=en', 'es')).toBe( - 'https://gateway.example/assignments/abc?lang=es' - ); - }); - - it('should keep other query parameters', () => { - expect(withLinkLanguage('https://gateway.example/assignments/abc?x=1', 'en')).toBe( - 'https://gateway.example/assignments/abc?x=1&lang=en' - ); - }); -}); diff --git a/apps/api/src/assignments/assignments.service.ts b/apps/api/src/assignments/assignments.service.ts index 0a75c117d..554aebf11 100644 --- a/apps/api/src/assignments/assignments.service.ts +++ b/apps/api/src/assignments/assignments.service.ts @@ -23,8 +23,6 @@ import type { EntityOperationOptions } from '@/core/types'; import { GatewayService } from '@/gateway/gateway.service'; import { InstrumentsService } from '@/instruments/instruments.service'; -import { withLinkLanguage } from './assignments.utils'; - /** * How many assignments a batch prepares at once. Key generation is CPU-bound, so an unbounded * `Promise.all` over 500 subjects would hold the event loop for the whole batch and stall every @@ -381,7 +379,10 @@ export class AssignmentsService { redirectUrl, status: 'OUTSTANDING', subject: { connect: { id: subjectId } }, - url: language ? withLinkLanguage(link, language) : link + // 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/api/src/assignments/assignments.utils.ts b/apps/api/src/assignments/assignments.utils.ts deleted file mode 100644 index a23272af1..000000000 --- a/apps/api/src/assignments/assignments.utils.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Language } from '@opendatacapture/schemas/core'; - -/** - * The assignment link, opening the gateway in `language`, which it reads from `?lang=`. - * - * Set only when the assignment is created: a link left without a language is one the subject's own - * browser decides, and nothing later — an email written in another language included — overrides - * that. - */ -export function withLinkLanguage(url: string, language: Language): string { - const link = new URL(url); - link.searchParams.set('lang', language); - return link.href; -} diff --git a/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts b/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts index 7cb1311c9..f34bc3d82 100644 --- a/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts +++ b/apps/web/src/hooks/__tests__/useAdministrationChoice.test.ts @@ -20,22 +20,20 @@ const scale = instrument('scale'); describe('useAdministrationChoice', () => { it('should have no choice until an instrument is picked', () => { - const { result } = renderHook(() => useAdministrationChoice()); + const { result } = renderHook(() => useAdministrationChoice(['en', 'fr'])); expect(result.current.choice).toBeNull(); }); it('should start a pick with no language, leaving it to the browser that opens the link', () => { - const { result } = renderHook(() => useAdministrationChoice()); - let picked: ReturnType | undefined; + const { result } = renderHook(() => useAdministrationChoice(['en', 'fr'])); act(() => { - picked = result.current.pick(scale); + result.current.pick(scale); }); - expect(picked).toMatchObject({ instrument: { id: 'scale' }, language: undefined }); expect(result.current.choice).toMatchObject({ instrument: { id: 'scale' }, language: undefined }); }); it('should keep the language the user chose', () => { - const { result } = renderHook(() => useAdministrationChoice()); + const { result } = renderHook(() => useAdministrationChoice(['en', 'fr'])); act(() => { result.current.pick(scale); }); @@ -46,7 +44,7 @@ describe('useAdministrationChoice', () => { }); it('should forget a chosen language on the next pick, so it cannot carry to another instrument', () => { - const { result } = renderHook(() => useAdministrationChoice()); + const { result } = renderHook(() => useAdministrationChoice(['en', 'fr'])); act(() => { result.current.pick(scale); result.current.setLanguage('fr'); diff --git a/apps/web/src/hooks/useAdministrationChoice.ts b/apps/web/src/hooks/useAdministrationChoice.ts index 3438e4105..174955a29 100644 --- a/apps/web/src/hooks/useAdministrationChoice.ts +++ b/apps/web/src/hooks/useAdministrationChoice.ts @@ -10,9 +10,9 @@ import type { AdministrationChoice } from '@/utils/administration-choice'; * The language a picked instrument is assigned in. No language is chosen to begin with, which * leaves it to the subject's browser — the assignment is made before anyone knows what they read. * - * @param allowedLanguages - narrows the instrument's own languages, e.g. to the instance's active ones + * @param allowedLanguages - narrows the instrument's own languages to the instance's active ones */ -export function useAdministrationChoice(allowedLanguages?: readonly Language[]) { +export function useAdministrationChoice(allowedLanguages: readonly Language[]) { const [instrument, setInstrument] = useState(null); const [language, setLanguage] = useState(undefined); @@ -20,10 +20,9 @@ export function useAdministrationChoice(allowedLanguages?: readonly Language[]) return { instrument: picked, language: chosen, languageOptions: getLanguageOptions(picked, allowedLanguages) }; }; - const pick = (picked: TranslatedInstrumentInfo): AdministrationChoice => { + const pick = (picked: TranslatedInstrumentInfo): void => { setInstrument(picked); setLanguage(undefined); - return describe(picked, undefined); }; return { 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 1953e485d..c33517988 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'; @@ -126,9 +126,21 @@ 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. */ -const waitForLink = () => { - return waitFor(() => expect(screen.getByRole('link', { name: 'Assignment Link' })).toBeTruthy()); +/** + * 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 () => { diff --git a/apps/web/src/utils/__tests__/administration-choice.test.ts b/apps/web/src/utils/__tests__/administration-choice.test.ts index d2fb63e91..4b19e2b77 100644 --- a/apps/web/src/utils/__tests__/administration-choice.test.ts +++ b/apps/web/src/utils/__tests__/administration-choice.test.ts @@ -15,12 +15,18 @@ function createInfo(supportedLanguages: string[]): TranslatedInstrumentInfo { describe('getAdministrationChoice', () => { it('should return the preferred language when the instrument offers it', () => { - const result = getAdministrationChoice(createInfo(['en', 'fr']), { preferredLanguage: 'fr' }); + 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']), { preferredLanguage: 'en' }); + const result = getAdministrationChoice(createInfo(['fr']), { + allowedLanguages: ['en', 'fr'], + preferredLanguage: 'en' + }); expect(result.language).toBe('fr'); }); diff --git a/apps/web/src/utils/administration-choice.ts b/apps/web/src/utils/administration-choice.ts index e361a82cc..7ef40fe45 100644 --- a/apps/web/src/utils/administration-choice.ts +++ b/apps/web/src/utils/administration-choice.ts @@ -12,15 +12,15 @@ type AdministrationChoice = { }; type AdministrationChoiceOptions = { - /** Narrows the instrument's own languages, e.g. to those the instance has active. */ - allowedLanguages?: readonly Language[]; + /** 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 || allowedLanguages.includes(language)); +function getLanguageOptions(instrument: TranslatedInstrumentInfo, allowedLanguages: readonly Language[]): Language[] { + return instrument.supportedLanguages.filter((language) => allowedLanguages.includes(language)); } /** From 476d71e1b9eb5250a8f6915f2a5d9c839231fdac Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 15:51:59 -0500 Subject: [PATCH 7/9] fix(web): ask about a language mismatch only where the sender can resolve it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The confirmation fired whenever the email's language differed from the link's, including when no template was authored in the link's language at all — where "Send anyway" was the only way through, on every send. It now asks only when the sender could have picked that language, which is when the mismatch is a choice rather than the only option. Co-Authored-By: Claude Opus 5 --- .../AssignmentEmailForm/AssignmentEmailForm.tsx | 13 +++++++++---- .../ConfirmEmailLanguageDialog.tsx | 10 ++++++---- .../__tests__/AssignmentEmailForm.test.tsx | 10 ++++++++++ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx index 38c9f2c9f..b6f709442 100644 --- a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx +++ b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx @@ -69,8 +69,13 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan // 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. - const linkLanguage = assignment ? getLinkLanguage(assignment.url) : undefined; + // 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) { @@ -237,9 +242,9 @@ export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLan {feedback.message}

    )} - {linkLanguage && ( + {linkLanguage && isConfirmingLanguage && ( { const { t } = useTranslation(); return ( - + @@ -42,7 +44,7 @@ export const ConfirmEmailLanguageDialog = ({ 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 ?? linkLanguage]), t(LANGUAGE_LABELS[linkLanguage])] } + { 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 c61b842bf..2edaf5355 100644 --- a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx +++ b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx @@ -370,6 +370,16 @@ describe('AssignmentEmailForm', () => { 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'); From c20f29ef96d225a544bb2294471ff56c62b7422a Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 15:52:00 -0500 Subject: [PATCH 8/9] fix(gateway): read a quality the client spells with a capital Q MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HTTP does not distinguish the case of a parameter name, so `fr;Q=0.1,en;Q=0.9` gave both tags the default quality and served French — the language the client least wanted. A quality the header names but that cannot be read is now taken as the default of 1, as the documented rule always said, rather than as 0, which the filter then dropped. Co-Authored-By: Claude Opus 5 --- apps/gateway/src/lib/__tests__/setup-state.test.ts | 10 ++++++++++ apps/gateway/src/lib/setup-state.ts | 9 +++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/apps/gateway/src/lib/__tests__/setup-state.test.ts b/apps/gateway/src/lib/__tests__/setup-state.test.ts index 0a0373cd5..ac2da2bb7 100644 --- a/apps/gateway/src/lib/__tests__/setup-state.test.ts +++ b/apps/gateway/src/lib/__tests__/setup-state.test.ts @@ -81,4 +81,14 @@ describe('resolveLanguage', () => { 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 3123116ba..65198fa70 100644 --- a/apps/gateway/src/lib/setup-state.ts +++ b/apps/gateway/src/lib/setup-state.ts @@ -6,9 +6,9 @@ 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 unparseable quality is + * 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. + * language it named. A parameter name is matched either case, as HTTP does not distinguish them. */ const parseAcceptLanguage = (header: string): string[] => { return header @@ -16,9 +16,10 @@ const parseAcceptLanguage = (header: string): string[] => { .map((part) => { const [tag = '', ...parameters] = part.trim().split(';'); const quality = parameters - .map((parameter) => /^\s*q=(?[\d.]+)\s*$/u.exec(parameter)?.groups?.value) + .map((parameter) => /^\s*q=(?[\d.]+)\s*$/iu.exec(parameter)?.groups?.value) .find((value) => value !== undefined); - return { quality: quality === undefined ? 1 : Number.parseFloat(quality) || 0, tag: tag.trim() }; + 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) From 3509c78c741be14b922064b16834ec25773ab634 Mon Sep 17 00:00:00 2001 From: thomasbeaudry Date: Fri, 20 Nov 2026 15:52:01 -0500 Subject: [PATCH 9/9] refactor: require the language its host always holds `InteractiveContent` took `language` and `onChangeLanguage` as an optional pair and fell back to the interface language, though both call sites pass what `useInstrumentLanguage` always returns; the absent variant had no caller but its own test. The dialog's `isCreateModalOpen && choice !== null` loses an operand that cannot be false, two `waitFor`s whose assertion never throws are plain assertions again, the pinned-locale comment moves beside the locale, and the administer spec starts its session through `getPageModel` like its siblings. Co-Authored-By: Claude Opus 5 --- .../__tests__/remote-assignment.test.tsx | 5 +- .../routes/_app/session/remote-assignment.tsx | 2 +- .../InteractiveContent.stories.tsx | 4 + .../InteractiveContent/InteractiveContent.tsx | 36 ++--- .../__tests__/InteractiveContent.test.tsx | 150 +++++++++++++++--- testing/playwright.config.ts | 8 +- .../src/specs/accessible-instruments.spec.ts | 18 ++- testing/src/specs/gateway-landing.spec.ts | 12 +- 8 files changed, 171 insertions(+), 64 deletions(-) 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 c33517988..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 @@ -235,8 +235,7 @@ describe('Route', () => { fireEvent.blur(input); submitForm(); expect(await screen.findByText('Expiry date must be in the future')).toBeTruthy(); - // Settles the form's own submit cycle, so no state update lands after the test has finished. - await waitFor(() => expect(mocks.mutateAsync).not.toHaveBeenCalled()); + expect(mocks.mutateAsync).not.toHaveBeenCalled(); }); it('should create the assignment, expiring on the chosen day, for the session subject in the current group', async () => { @@ -280,7 +279,7 @@ describe('Route', () => { fireEvent.change(screen.getByLabelText('Redirect URL (Optional)'), { target: { value: 'http://example.com' } }); submitForm(); await waitFor(() => expect(screen.getByTestId('error-message-text')).toBeTruthy()); - await waitFor(() => expect(mocks.mutateAsync).not.toHaveBeenCalled()); + expect(mocks.mutateAsync).not.toHaveBeenCalled(); }); it('should create the assignment with the redirect URL given', async () => { diff --git a/apps/web/src/routes/_app/session/remote-assignment.tsx b/apps/web/src/routes/_app/session/remote-assignment.tsx index e297b8113..fa9e98bf4 100644 --- a/apps/web/src/routes/_app/session/remote-assignment.tsx +++ b/apps/web/src/routes/_app/session/remote-assignment.tsx @@ -143,7 +143,7 @@ const RouteComponent = () => { } }} /> - + { 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 1e7d5f571..6174bdb1f 100644 --- a/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx +++ b/packages/react-core/src/components/InteractiveContent/InteractiveContent.tsx @@ -29,9 +29,7 @@ const _InteractiveContent = React.memo(function _Intera supportedLanguages = [] }) { const addNotification = useNotificationsStore((store) => store.addNotification); - const { changeLanguage, resolvedLanguage, t } = useTranslation(); - const contentLanguage = language ?? resolvedLanguage; - const changeContentLanguage = onChangeLanguage ?? changeLanguage; + const { resolvedLanguage, t } = useTranslation(); const [_, updateTheme] = useTheme(); const [scale, setScale] = useState(100); const [hasSelectedLanguage, setHasSelectedLanguage] = useState( @@ -62,9 +60,9 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeContentLanguage(requested.data); + onChangeLanguage(requested.data); }, - [addNotification, changeContentLanguage, isLocked, t] + [addNotification, isLocked, onChangeLanguage, t] ); const handleChangeThemeEvent = useCallback( @@ -166,7 +164,7 @@ const _InteractiveContent = React.memo(function _Intera setLockDialogOpen(true); return; } - changeContentLanguage(language); + onChangeLanguage(language); }} > {LANGUAGE_LABELS[language][resolvedLanguage]} @@ -181,7 +179,7 @@ const _InteractiveContent = React.memo(function _Intera allow="fullscreen" className="origin-top-left" data-bundle={bundle} - lang={contentLanguage} + lang={language} name="interactive-instrument" ref={iFrameRef} src="/runtime/v1/@opendatacapture/runtime-internal/interactive/iframe.html" @@ -205,7 +203,7 @@ const _InteractiveContent = React.memo(function _Intera key={language} type="button" onClick={() => { - changeContentLanguage(language); + onChangeLanguage(language); setHasSelectedLanguage(true); }} > @@ -263,19 +261,15 @@ export type InteractiveContentProps = Simplify< Pick< 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; - } - | { language?: never; onChangeLanguage?: never } - ) & { - bundle: string; - onSubmit: (result: InteractiveContentSubmitResult) => Promisable; - supportedLanguages?: Language[]; - } + > & { + /** 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[]; + } >; // eslint-disable-next-line react/function-component-definition -- the named function passed to memo gives the component its display name 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 57935358b..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,18 +210,21 @@ 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 interface language when the host holds no language', () => { - render(); - expect(screen.getByTitle('Open Data Capture - Interactive Instrument').getAttribute('lang')).toBe('en'); - }); - it('should run the iframe in the language the host holds, whatever the interface language', () => { render( { }); 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!); @@ -212,7 +284,9 @@ describe('InteractiveContent', () => { ); @@ -221,7 +295,14 @@ describe('InteractiveContent', () => { it('should close the lock dialog when its OK button is clicked', () => { render( - + ); act(() => { dispatch('changeLanguage', 'fr'); @@ -247,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/testing/playwright.config.ts b/testing/playwright.config.ts index 9224c2eda..eb2439b36 100644 --- a/testing/playwright.config.ts +++ b/testing/playwright.config.ts @@ -25,10 +25,6 @@ export default defineConfig({ expect: { timeout: 15_000 }, - // `locale` is pinned because the gateway negotiates the language of a link that carries none from - // Accept-Language, which a browser derives from its locale: left to the host's, every assertion on - // an English string would depend on the developer's own machine. A test about that negotiation opts - // into another locale with its own `browser.newContext({ locale })`. fullyParallel: true, outputDir: path.resolve(import.meta.dirname, '.playwright/output'), projects: [ @@ -38,6 +34,10 @@ export default defineConfig({ dependencies: ['setup'], name: 'chromium', testMatch: '**/specs/**/*.spec.ts', + // `locale` is pinned because the gateway negotiates the language of a link that carries none + // from Accept-Language, which a browser derives from its locale: left to the host's, every + // assertion on an English string would depend on the developer's own machine. A test about + // that negotiation opts into another locale with its own `browser.newContext({ locale })`. use: { ...devices['Desktop Chrome'], baseURL, channel: 'chromium', headless: true, locale: 'en-US' } } ], diff --git a/testing/src/specs/accessible-instruments.spec.ts b/testing/src/specs/accessible-instruments.spec.ts index 1f7fccf5f..8c64973f1 100644 --- a/testing/src/specs/accessible-instruments.spec.ts +++ b/testing/src/specs/accessible-instruments.spec.ts @@ -2,14 +2,17 @@ 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 { StartSessionPage } from '../pages/_app/session/start-session.page'; import { PHONE_VIEWPORT } from '../support/constants'; import { expect, test } from '../support/fixtures'; -/** Starts a session, then reaches Administer Instrument through the sidebar, which keeps the in-memory session. */ -async function openAdministerWithSession(page: Page, uniqueId: string) { - const startSessionPage = new StartSessionPage(page); - await startSessionPage.goto('/session/start-session'); +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'); @@ -40,12 +43,11 @@ test.describe('accessible instruments on a phone', () => { test.describe('administering an instrument', () => { test('should run the instrument in the language chosen while the rest of the app keeps its own', async ({ - authenticateAs, + getPageModel, page, uniqueId }) => { - await authenticateAs('GROUP_MANAGER'); - const accessibleInstrumentsPage = await openAdministerWithSession(page, uniqueId); + const accessibleInstrumentsPage = await openAdministerWithSession(getPageModel, page, uniqueId); await accessibleInstrumentsPage.chooseCardLanguage('Happiness Questionnaire', 'French'); await accessibleInstrumentsPage.instrumentCard('Happiness Questionnaire').click(); diff --git a/testing/src/specs/gateway-landing.spec.ts b/testing/src/specs/gateway-landing.spec.ts index 76f242237..19bfcab92 100644 --- a/testing/src/specs/gateway-landing.spec.ts +++ b/testing/src/specs/gateway-landing.spec.ts @@ -19,10 +19,8 @@ test.describe('gateway landing page', () => { 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(); - await expect(async () => { - const landing = await frenchPage.goto(gatewayURL); - expect(await landing!.text()).toContain('Bienvenue'); - }).toPass({ timeout: STALE_SETUP_STATE_TIMEOUT }); + 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(); }); @@ -30,10 +28,8 @@ test.describe('gateway landing page', () => { 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(); - await expect(async () => { - const english = await frenchPage.goto(`${gatewayURL}/?lang=en`); - expect(await english!.text()).toContain('Welcome'); - }).toPass({ timeout: STALE_SETUP_STATE_TIMEOUT }); + const english = await frenchPage.goto(`${gatewayURL}/?lang=en`); + expect(await english!.text()).toContain('Welcome'); await frenchContext.close(); }); });