diff --git a/apps/api/src/assignments/__tests__/assignments.controller.test.ts b/apps/api/src/assignments/__tests__/assignments.controller.test.ts
index fb8d392e0..23767ebe6 100644
--- a/apps/api/src/assignments/__tests__/assignments.controller.test.ts
+++ b/apps/api/src/assignments/__tests__/assignments.controller.test.ts
@@ -138,7 +138,7 @@ describe('AssignmentsController', () => {
await sendEmail({ language: 'en', recipient: 'p@x.org' });
expect(groupsService.findById).not.toHaveBeenCalled();
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
- links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }],
+ links: [{ expiresAt: assignment.expiresAt, url: assignment.url }],
recipient: 'p@x.org',
template: DEFAULT_ASSIGNMENT_EMAIL_TEMPLATE
});
@@ -150,7 +150,7 @@ describe('AssignmentsController', () => {
assignmentsService.findById.mockResolvedValueOnce({ ...assignment, groupId: null });
await sendEmail({ language: 'en', recipient: 'p@x.org' });
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
- links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }]
+ links: [{ expiresAt: assignment.expiresAt, url: assignment.url }]
});
});
@@ -237,7 +237,17 @@ describe('AssignmentsController', () => {
await sendEmail({ language: 'fr', recipient: 'p@x.org' });
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
language: 'fr',
- links: [{ url: `${assignment.url}?lang=fr` }]
+ links: [{ url: assignment.url }]
+ });
+ });
+
+ it('never re-points the link, so an email in another language cannot override what the link says', async () => {
+ assignmentsService.findById.mockResolvedValueOnce({ ...assignment, url: `${assignment.url}?lang=en` });
+ groupsService.findById.mockResolvedValueOnce({ emailTemplates: [] });
+ await sendEmail({ language: 'fr', recipient: 'p@x.org' });
+ expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
+ language: 'fr',
+ links: [{ url: `${assignment.url}?lang=en` }]
});
});
@@ -329,8 +339,8 @@ describe('AssignmentsController', () => {
expect(mailService.sendAssignmentEmail).toHaveBeenCalledOnce();
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
links: [
- { expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` },
- { expiresAt: second.expiresAt, url: `${second.url}?lang=en` }
+ { expiresAt: assignment.expiresAt, url: assignment.url },
+ { expiresAt: second.expiresAt, url: second.url }
],
recipient: 'p@x.org'
});
diff --git a/apps/api/src/assignments/__tests__/assignments.service.test.ts b/apps/api/src/assignments/__tests__/assignments.service.test.ts
index fdbe45413..7a9c828c4 100644
--- a/apps/api/src/assignments/__tests__/assignments.service.test.ts
+++ b/apps/api/src/assignments/__tests__/assignments.service.test.ts
@@ -388,6 +388,12 @@ describe('AssignmentsService', () => {
expect(url).toBe(`http://localhost:3500/assignments/${id}`);
});
+ it('should open the participant link in the language chosen for the assignment', async () => {
+ await assignmentsService.create({ ...data(), language: 'fr' }, permissiveUser());
+ const { id, url } = assignmentModel.create.mock.lastCall?.[0].data ?? {};
+ expect(url).toBe(`http://localhost:3500/assignments/${id}?lang=fr`);
+ });
+
it('should point the participant link at the gateway site address in production', async () => {
await compile({
get: (key) => (key === 'NODE_ENV' ? 'production' : undefined),
diff --git a/apps/api/src/assignments/assignments.controller.ts b/apps/api/src/assignments/assignments.controller.ts
index eb218ccde..270600874 100644
--- a/apps/api/src/assignments/assignments.controller.ts
+++ b/apps/api/src/assignments/assignments.controller.ts
@@ -132,7 +132,7 @@ export class AssignmentsController {
language,
links: assignments.map((assignment) => ({
expiresAt: assignment.expiresAt,
- url: `${assignment.url}?lang=${language}`
+ url: assignment.url
})),
recipient,
template: await this.resolveTemplate(groupId ?? null, templateId, ability)
@@ -156,7 +156,7 @@ export class AssignmentsController {
const assignment = await this.assignmentsService.findById(id, { ability });
const result = await this.mailService.sendAssignmentEmail({
language,
- links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=${language}` }],
+ links: [{ expiresAt: assignment.expiresAt, url: assignment.url }],
recipient,
template: await this.resolveTemplate(assignment.groupId ?? null, templateId, ability)
});
diff --git a/apps/api/src/assignments/assignments.service.ts b/apps/api/src/assignments/assignments.service.ts
index 5f29c30ce..554aebf11 100644
--- a/apps/api/src/assignments/assignments.service.ts
+++ b/apps/api/src/assignments/assignments.service.ts
@@ -15,6 +15,7 @@ import type {
BulkAssignmentIssue,
BulkAssignmentPreflightResult
} from '@opendatacapture/schemas/assignment';
+import type { Language } from '@opendatacapture/schemas/core';
import { AuditLogger } from '@/audit/audit.logger';
import { accessibleQuery, forcedAppSubject } from '@/auth/ability.utils';
@@ -76,7 +77,7 @@ export class AssignmentsService {
}
async create(
- { expiresAt, groupId, instrumentId, redirectUrl, subjectId }: $CreateAssignmentData,
+ { expiresAt, groupId, instrumentId, language, redirectUrl, subjectId }: $CreateAssignmentData,
currentUser: RequestUser
): Promise {
if (groupId) {
@@ -96,6 +97,7 @@ export class AssignmentsService {
expiresAt,
groupId,
instrumentId,
+ language,
redirectUrl,
subjectId
});
@@ -350,17 +352,20 @@ export class AssignmentsService {
expiresAt,
groupId,
instrumentId,
+ language,
redirectUrl,
subjectId
}: {
expiresAt: Date;
groupId?: null | string;
instrumentId: string;
+ language?: Language;
redirectUrl?: string;
subjectId: string;
}): Promise<{ assignment: Assignment; publicKey: webcrypto.CryptoKey }> {
const { privateKey, publicKey } = await HybridCrypto.generateKeyPair();
const id = crypto.randomUUID();
+ const link = `${this.assignmentBaseUrl}/assignments/${id}`;
const assignment = await this.assignmentModel.create({
data: {
encryptionKeyPair: {
@@ -374,7 +379,10 @@ export class AssignmentsService {
redirectUrl,
status: 'OUTSTANDING',
subject: { connect: { id: subjectId } },
- url: `${this.assignmentBaseUrl}/assignments/${id}`
+ // The language is named on the link only when the assignment is created: a link left
+ // without one is one the subject's own browser decides, and nothing later — an email
+ // written in another language included — overrides that.
+ url: language ? `${link}?lang=${language}` : link
}
});
return { assignment, publicKey };
diff --git a/apps/gateway/src/lib/__tests__/setup-state.test.ts b/apps/gateway/src/lib/__tests__/setup-state.test.ts
index cbf0179b8..ac2da2bb7 100644
--- a/apps/gateway/src/lib/__tests__/setup-state.test.ts
+++ b/apps/gateway/src/lib/__tests__/setup-state.test.ts
@@ -36,4 +36,59 @@ describe('resolveLanguage', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(['fr', 'en'])).toBe('en');
});
+
+ it('should open a link with no language in the language the browser asks for', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'fr-CA,fr;q=0.9,en;q=0.8')).toBe('fr');
+ });
+
+ it('should fall back to the browser for a link pinned to a language the instance has since turned off', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage('es', 'fr-CA,fr;q=0.9')).toBe('fr');
+ });
+
+ it('should prefer the language the link names over the one the browser asks for', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage('en', 'fr-CA,fr;q=0.9')).toBe('en');
+ });
+
+ it('should take the most wanted language the instance has active, not merely the first listed', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'de;q=0.9,fr;q=0.8,en;q=0.7')).toBe('fr');
+ });
+
+ it('should order by quality rather than by the order the header lists them', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'en;q=0.3,fr;q=0.9')).toBe('fr');
+ });
+
+ it('should ignore a language the browser explicitly refuses with q=0', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'fr;q=0,en;q=0.5')).toBe('en');
+ });
+
+ it('should fall back to the first active language when the browser asks for none it has', () => {
+ updateSetupState({ activeLanguages: ['fr', 'en'] });
+ expect(resolveLanguage(undefined, 'de,it')).toBe('fr');
+ });
+
+ it('should fall back to the first active language for a header it cannot read', () => {
+ updateSetupState({ activeLanguages: ['fr', 'en'] });
+ expect(resolveLanguage(undefined, ';;;')).toBe('fr');
+ });
+
+ it('should treat an unreadable quality as the strongest preference, since the language was still named', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'fr;q=high,en;q=0.9')).toBe('fr');
+ });
+
+ it('should treat a quality of punctuation alone as the strongest preference rather than dropping the language', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'fr;q=.,en;q=0.9')).toBe('fr');
+ });
+
+ it('should read a quality the client spells with a capital Q, which HTTP allows', () => {
+ updateSetupState({ activeLanguages: ['en', 'fr'] });
+ expect(resolveLanguage(undefined, 'fr;Q=0.1,en;Q=0.9')).toBe('en');
+ });
});
diff --git a/apps/gateway/src/lib/setup-state.ts b/apps/gateway/src/lib/setup-state.ts
index cdf6cb818..65198fa70 100644
--- a/apps/gateway/src/lib/setup-state.ts
+++ b/apps/gateway/src/lib/setup-state.ts
@@ -1,7 +1,31 @@
-import { $Language, DEFAULT_ACTIVE_LANGUAGES, resolveActiveLanguage } from '@opendatacapture/schemas/core';
+import { $Language, DEFAULT_ACTIVE_LANGUAGES } from '@opendatacapture/schemas/core';
import type { ActiveLanguages, Language } from '@opendatacapture/schemas/core';
import type { RemoteSetupState } from '@opendatacapture/schemas/gateway';
+/**
+ * The languages an `Accept-Language` header asks for, most wanted first.
+ *
+ * Only the base language is kept, so `fr-CA` counts as a request for French, and a tag with `q=0`
+ * is dropped because that is how a client says it does not want one. An unreadable quality is
+ * treated as the default of 1 rather than discarded, since a client that sends one still wants the
+ * language it named. A parameter name is matched either case, as HTTP does not distinguish them.
+ */
+const parseAcceptLanguage = (header: string): string[] => {
+ return header
+ .split(',')
+ .map((part) => {
+ const [tag = '', ...parameters] = part.trim().split(';');
+ const quality = parameters
+ .map((parameter) => /^\s*q=(?[\d.]+)\s*$/iu.exec(parameter)?.groups?.value)
+ .find((value) => value !== undefined);
+ const parsedQuality = quality === undefined ? 1 : Number.parseFloat(quality);
+ return { quality: Number.isNaN(parsedQuality) ? 1 : parsedQuality, tag: tag.trim() };
+ })
+ .filter(({ quality, tag }) => tag.length > 0 && quality > 0)
+ .sort((a, b) => b.quality - a.quality)
+ .map(({ tag }) => tag.split('-')[0]!.toLowerCase());
+};
+
/**
* The setup state of the instance this gateway serves, as last pushed by `apps/api`.
*
@@ -18,16 +42,24 @@ export function getActiveLanguages(): ActiveLanguages {
/**
* The language to render a page in: the one a `?lang=` query asks for when the instance offers it,
- * otherwise the first active language. Resolved server-side rather than from `window.location` so
- * the SSR pass and the hydration pass agree; anything else renders the page in English and then
- * swaps it.
+ * otherwise the first language the reader's browser asks for that the instance offers, and failing
+ * both the first active language. Resolved server-side rather than from `window.location` or
+ * `navigator` so the SSR pass and the hydration pass agree; anything else renders the page in one
+ * language and then swaps it.
+ *
+ * A link created without a language is the common case — an assignment is assigned before anyone
+ * knows what the subject reads — so the header is what makes that link open in their own language.
*/
-export function resolveLanguage(requested: unknown): Language {
+export function resolveLanguage(requested: unknown, acceptLanguage?: string): Language {
const activeLanguages = getActiveLanguages();
const requestedLanguage = $Language.safeParse(requested);
- return requestedLanguage.success
- ? resolveActiveLanguage(requestedLanguage.data, activeLanguages)
- : activeLanguages[0];
+ if (requestedLanguage.success && activeLanguages.includes(requestedLanguage.data)) {
+ return requestedLanguage.data;
+ }
+ const accepted = parseAcceptLanguage(acceptLanguage ?? '')
+ .map((tag) => $Language.safeParse(tag))
+ .find((parsed) => parsed.success && activeLanguages.includes(parsed.data));
+ return accepted?.success ? accepted.data : activeLanguages[0];
}
export function updateSetupState(state: RemoteSetupState): void {
diff --git a/apps/gateway/src/routers/__tests__/root.router.test.ts b/apps/gateway/src/routers/__tests__/root.router.test.ts
index 84af7aa16..557c3e0d9 100644
--- a/apps/gateway/src/routers/__tests__/root.router.test.ts
+++ b/apps/gateway/src/routers/__tests__/root.router.test.ts
@@ -40,8 +40,8 @@ function storeAssignment(stored: {
});
}
-async function getRootProps(path: string): Promise {
- const response = await fetch(`${baseUrl}${path}`);
+async function getRootProps(path: string, headers?: { [key: string]: string }): Promise {
+ const response = await fetch(`${baseUrl}${path}`, { headers });
return response.json();
}
@@ -111,6 +111,19 @@ describe('rootRouter', () => {
});
});
+ it('should open a link with no language in the language the browser asks for, which is how most links are created', async () => {
+ storeAssignment({});
+ expect(
+ await getRootProps('/assignments/assignment-1', { 'accept-language': 'fr-CA,fr;q=0.9,en;q=0.8' })
+ ).toMatchObject({ language: 'fr' });
+ });
+
+ it('should name Accept-Language as what the page varies on, so a shared cache cannot serve one subject the language of another', async () => {
+ storeAssignment({});
+ const response = await fetch(`${baseUrl}/assignments/assignment-1`);
+ expect(response.headers.get('vary')).toBe('Accept-Language');
+ });
+
it('should hand the page the redirect URL the assignment was created with, so it can send the subject on', async () => {
storeAssignment({ redirectUrl: 'https://example.com/done' });
expect(await getRootProps('/assignments/assignment-1')).toMatchObject({
diff --git a/apps/gateway/src/routers/root.router.ts b/apps/gateway/src/routers/root.router.ts
index 10d38e56c..bb80a5830 100644
--- a/apps/gateway/src/routers/root.router.ts
+++ b/apps/gateway/src/routers/root.router.ts
@@ -50,12 +50,12 @@ router.get(
id,
initialSeriesIndex,
kind: 'assignment',
- language: resolveLanguage(req.query.lang),
+ language: resolveLanguage(req.query.lang, req.headers['accept-language']),
redirectUrl: assignment.redirectUrl ?? undefined,
target: targetParseResult.data,
token
} satisfies RootProps);
- res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
+ res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html);
})
);
@@ -63,9 +63,9 @@ router.get('/', (req, res) => {
const html = res.locals.loadRoot({
activeLanguages: getActiveLanguages(),
kind: 'landing',
- language: resolveLanguage(req.query.lang)
+ language: resolveLanguage(req.query.lang, req.headers['accept-language'])
} satisfies RootProps);
- res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
+ res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html);
});
export { router as rootRouter };
diff --git a/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx
new file mode 100644
index 000000000..823e14603
--- /dev/null
+++ b/apps/web/src/components/AdministrationOptions/AdministrationOptions.tsx
@@ -0,0 +1,55 @@
+import { Label, Select } from '@douglasneuroinformatics/libui/components';
+import { useTranslation } from '@douglasneuroinformatics/libui/hooks';
+import { $Language } from '@opendatacapture/schemas/core';
+import type { Language } from '@opendatacapture/schemas/core';
+
+import type { AdministrationChoice } from '@/utils/administration-choice';
+import { LANGUAGE_LABELS } from '@/utils/language';
+
+/** Stands in for "no language", which a Select cannot hold as a value of its own. */
+const AUTOMATIC = '__automatic__';
+
+type AdministrationOptionsProps = {
+ choice: AdministrationChoice;
+ onLanguageChange: (language: Language | undefined) => void;
+};
+
+/**
+ * The language a remote assignment opens in. The default leaves it unset, so the gateway opens the
+ * link in whatever language the subject's browser asks for; picking one pins the link to it.
+ */
+export const AdministrationOptions = ({ choice, onLanguageChange }: AdministrationOptionsProps) => {
+ const { t } = useTranslation();
+ if (choice.languageOptions.length < 2) {
+ return null;
+ }
+ return (
+
+
+
+
+ );
+};
diff --git a/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx
new file mode 100644
index 000000000..bc6544ace
--- /dev/null
+++ b/apps/web/src/components/AdministrationOptions/__tests__/AdministrationOptions.test.tsx
@@ -0,0 +1,63 @@
+import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { AdministrationOptions } from '../AdministrationOptions';
+
+import '@/services/i18n';
+
+const instrument = { details: { title: 'Scale' }, id: 'scale', kind: 'FORM' } as unknown as TranslatedInstrumentInfo;
+
+const renderOptions = (
+ choice: Partial[0]['choice']>,
+ onLanguageChange = vi.fn()
+) => {
+ render(
+
+ );
+ return onLanguageChange;
+};
+
+const chooseOption = (name: string) => {
+ fireEvent.click(screen.getByTestId('administration-language'));
+ fireEvent.click(screen.getByRole('option', { name }));
+};
+
+describe('AdministrationOptions', () => {
+ afterEach(cleanup);
+
+ it('should offer the languages of an instrument that has more than one', () => {
+ renderOptions({ languageOptions: ['en', 'fr'] });
+ expect(screen.getByTestId('administration-language')).toBeTruthy();
+ });
+
+ it('should leave out the language dropdown when there is only one language to choose', () => {
+ renderOptions({ languageOptions: ['en'] });
+ expect(screen.queryByTestId('administration-language')).toBeNull();
+ });
+
+ it('should leave out the language dropdown when no allowed language is offered, rather than offer an empty one', () => {
+ renderOptions({ language: undefined, languageOptions: [] });
+ expect(screen.queryByTestId('administration-language')).toBeNull();
+ });
+
+ it('should leave the language to the browser by default, which is what no choice means', () => {
+ renderOptions({ languageOptions: ['en', 'fr'] });
+ expect(screen.getByTestId('administration-language').textContent).toBe("The subject's browser language");
+ });
+
+ it('should pin the link to a language the user picks', () => {
+ const onLanguageChange = renderOptions({ languageOptions: ['en', 'fr'] });
+ chooseOption('French');
+ expect(onLanguageChange).toHaveBeenCalledWith('fr');
+ });
+
+ it('should hand back no language when the browser option is picked again', () => {
+ const onLanguageChange = renderOptions({ language: 'fr', languageOptions: ['en', 'fr'] });
+ chooseOption("The subject's browser language");
+ expect(onLanguageChange).toHaveBeenCalledWith(undefined);
+ });
+});
diff --git a/apps/web/src/components/AdministrationOptions/index.ts b/apps/web/src/components/AdministrationOptions/index.ts
new file mode 100644
index 000000000..67687f6a5
--- /dev/null
+++ b/apps/web/src/components/AdministrationOptions/index.ts
@@ -0,0 +1 @@
+export * from './AdministrationOptions';
diff --git a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx
index cd80fffd4..b6f709442 100644
--- a/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx
+++ b/apps/web/src/components/AssignmentEmailForm/AssignmentEmailForm.tsx
@@ -12,25 +12,31 @@ import { useGroupQuery } from '@/hooks/useGroupQuery';
import { useMailErrorMessage } from '@/hooks/useMailErrorMessage';
import { useSendAssignmentEmailMutation } from '@/hooks/useSendAssignmentEmailMutation';
import { useSetupStateQuery } from '@/hooks/useSetupStateQuery';
+import { getLinkLanguage } from '@/utils/assignment-link';
import { sendableLanguages } from '@/utils/language';
+import { ConfirmEmailLanguageDialog } from './ConfirmEmailLanguageDialog';
+
const DEFAULT_TEMPLATE_OPTION = '__default__';
export type AssignmentEmailFormProps = {
assignment: Assignment | null;
+ /** The email language to start from; defaults to the interface language. Read once, on mount. */
+ initialLanguage?: Language;
instrumentLanguages?: string[];
};
-export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: AssignmentEmailFormProps) => {
+export const AssignmentEmailForm = ({ assignment, initialLanguage, instrumentLanguages }: AssignmentEmailFormProps) => {
const { resolvedLanguage, t } = useTranslation();
const setupStateQuery = useSetupStateQuery();
const sendEmailMutation = useSendAssignmentEmailMutation();
const addNotification = useNotificationsStore((store) => store.addNotification);
const mailErrorMessage = useMailErrorMessage();
const [recipient, setRecipient] = useState('');
- const [languageChoice, setLanguageChoice] = useState(resolvedLanguage);
+ const [languageChoice, setLanguageChoice] = useState(initialLanguage ?? resolvedLanguage);
const [templateChoice, setTemplateChoice] = useState(null);
const [feedback, setFeedback] = useState(null);
+ const [isConfirmingLanguage, setIsConfirmingLanguage] = useState(false);
// The server resolves the template from the assignment's own group, so this must query that
// group rather than whichever one is currently selected in the app store - on the datahub they
@@ -63,10 +69,19 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm
// leave the trigger showing a value with no matching item while a different one is posted.
const language = languageOptions.includes(languageChoice) ? languageChoice : (languageOptions[0] ?? 'en');
+ // The link's own language, which the email's does not have to match — so it is worth confirming,
+ // but only where the sender could pick it: a template authored in neither of the link's languages
+ // leaves them nothing to resolve, and a warning they can only override is a warning they learn to
+ // ignore.
+ const pinnedLinkLanguage = assignment ? getLinkLanguage(assignment.url) : undefined;
+ const linkLanguage =
+ pinnedLinkLanguage && languageOptions.includes(pinnedLinkLanguage) ? pinnedLinkLanguage : undefined;
+
const handleSendEmail = () => {
if (!assignment || !recipient) {
return;
}
+ setIsConfirmingLanguage(false);
setFeedback(null);
const fail = (message: string) => {
setFeedback({ message, tone: 'error' });
@@ -154,11 +169,10 @@ export const AssignmentEmailForm = ({ assignment, instrumentLanguages }: Assignm
- {/* Only the email is localized: the gateway does not read the link's `lang` param. */}
{t({
- en: 'The email is sent in the selected language when the template has been written in it. Participants choose their own language when they open the assignment.',
- es: 'El correo se envía en el idioma seleccionado cuando la plantilla se ha redactado en ese idioma. Los participantes eligen su propio idioma al abrir la tarea.',
- fr: "Le courriel est envoyé dans la langue sélectionnée lorsque le modèle a été rédigé dans celle-ci. Les participants choisissent leur propre langue à l'ouverture de l'évaluation."
+ en: 'The email is sent in the selected language when the template has been written in it. The link opens in the language the assignment was created in, whatever language the email is sent in.',
+ es: 'El correo se envía en el idioma seleccionado cuando la plantilla se ha redactado en ese idioma. El enlace se abre en el idioma en que se creó la tarea, sea cual sea el idioma del correo.',
+ fr: "Le courriel est envoyé dans la langue sélectionnée lorsque le modèle a été rédigé dans celle-ci. Le lien s'ouvre dans la langue de création de la tâche, quelle que soit la langue du courriel."
})}
)}
+ {linkLanguage && isConfirmingLanguage && (
+
+ )}
);
};
diff --git a/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx
new file mode 100644
index 000000000..ba7ddf86e
--- /dev/null
+++ b/apps/web/src/components/AssignmentEmailForm/ConfirmEmailLanguageDialog.tsx
@@ -0,0 +1,61 @@
+import { Button, Dialog } from '@douglasneuroinformatics/libui/components';
+import { useTranslation } from '@douglasneuroinformatics/libui/hooks';
+import type { Language } from '@opendatacapture/schemas/core';
+
+import { LANGUAGE_LABELS } from '@/utils/language';
+
+export type ConfirmEmailLanguageDialogProps = {
+ /** The language the email will be written in. */
+ emailLanguage: Language;
+ isPending: boolean;
+ /** The language the assignment link opens the instrument in. */
+ linkLanguage: Language;
+ onConfirm: () => void;
+ onOpenChange: (open: boolean) => void;
+};
+
+/**
+ * Asks before sending an email written in one language for a link that opens in another. The two
+ * are set separately and nothing else in the app shows them side by side, so the mismatch is easy
+ * to create and invisible until the subject opens the link.
+ *
+ * Rendered only while confirming, so it needs no closed state of its own.
+ */
+export const ConfirmEmailLanguageDialog = ({
+ emailLanguage,
+ isPending,
+ linkLanguage,
+ onConfirm,
+ onOpenChange
+}: ConfirmEmailLanguageDialogProps) => {
+ const { t } = useTranslation();
+ return (
+
+ );
+};
diff --git a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx
index 0f857112c..2edaf5355 100644
--- a/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx
+++ b/apps/web/src/components/AssignmentEmailForm/__tests__/AssignmentEmailForm.test.tsx
@@ -329,4 +329,71 @@ describe('AssignmentEmailForm', () => {
submit('q@x.org');
expect(screen.queryByTestId('assignment-email-feedback')).toBeNull();
});
+
+ describe('a link pinned to a language', () => {
+ const pinnedAssignment: Assignment = { ...assignment, url: `${assignment.url}?lang=fr` };
+
+ const chooseEmailLanguage = (name: string) => {
+ fireEvent.click(screen.getByTestId('assignment-language'));
+ fireEvent.click(screen.getByRole('option', { name }));
+ };
+
+ it('sends without asking when the email is in the language the link opens in', () => {
+ render();
+ submit('p@x.org');
+ expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull();
+ expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'fr' }), expect.anything());
+ });
+
+ it('asks before sending an email in a language the link does not open in', () => {
+ render();
+ chooseEmailLanguage('English');
+ submit('p@x.org');
+ expect(screen.getByTestId('confirm-email-language-dialog')).toBeTruthy();
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+ });
+
+ it('names both languages, so the sender can see which is which', () => {
+ render();
+ chooseEmailLanguage('English');
+ submit('p@x.org');
+ expect(screen.getByTestId('confirm-email-language-dialog').textContent).toContain(
+ 'written in English, but the link opens the instrument in French'
+ );
+ });
+
+ it('sends once the mismatch is confirmed', () => {
+ render();
+ chooseEmailLanguage('English');
+ submit('p@x.org');
+ fireEvent.click(screen.getByTestId('confirm-email-language'));
+ expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'en' }), expect.anything());
+ });
+
+ // Otherwise the warning fires on every send with nothing the sender can do but override it,
+ // which is how a warning stops being read.
+ it('asks nothing when no template is authored in the language the link opens in, since there is nothing to resolve', () => {
+ mockGroup('tpl-en', [englishTemplate]);
+ render();
+ submit('p@x.org');
+ expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull();
+ expect(mocks.sendEmail).toHaveBeenCalledWith(expect.objectContaining({ language: 'en' }), expect.anything());
+ });
+
+ it('sends nothing when the mismatch is dismissed', () => {
+ render();
+ chooseEmailLanguage('English');
+ submit('p@x.org');
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull();
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+ });
+ });
+
+ it('asks nothing of a link with no language, which the browser that opens it decides', () => {
+ render();
+ submit('p@x.org');
+ expect(screen.queryByTestId('confirm-email-language-dialog')).toBeNull();
+ expect(mocks.sendEmail).toHaveBeenCalled();
+ });
});
diff --git a/apps/web/src/components/InstrumentCard/InstrumentCard.tsx b/apps/web/src/components/InstrumentCard/InstrumentCard.tsx
index 8800daa34..d1b54e6e1 100644
--- a/apps/web/src/components/InstrumentCard/InstrumentCard.tsx
+++ b/apps/web/src/components/InstrumentCard/InstrumentCard.tsx
@@ -1,13 +1,16 @@
import React from 'react';
-import { Card, Heading, Tooltip } from '@douglasneuroinformatics/libui/components';
+import { Card, Heading, Label, Tooltip } from '@douglasneuroinformatics/libui/components';
import { useTranslation } from '@douglasneuroinformatics/libui/hooks';
import { cn } from '@douglasneuroinformatics/libui/utils';
import { licenses } from '@opendatacapture/licenses';
import { InstrumentIcon } from '@opendatacapture/react-core';
+import type { Language } from '@opendatacapture/schemas/core';
import type { TranslatedInstrumentInfo } from '@opendatacapture/schemas/instrument';
import { BadgeAlertIcon, BadgeCheckIcon } from 'lucide-react';
+import { LanguageSelect } from '../LanguageSelect';
+
type BaseCardItem = { label: string; tooltip?: React.ReactNode };
type LinkCardItem = BaseCardItem & { href?: null | string; kind: 'link' };
@@ -19,12 +22,30 @@ type CardItem = LinkCardItem | TextCardItem;
type InstrumentCardProps = {
highlighted?: boolean;
instrument: TranslatedInstrumentInfo;
+ /** The language the card will be opened in, where the card offers a choice of them. */
+ language?: Language;
+ /** The languages to offer; the dropdown replaces the static list only when there are two or more. */
+ languageOptions?: Language[];
onClick: () => void;
+ onLanguageChange?: (language: Language) => void;
};
-export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentCardProps) => {
+export const InstrumentCard = ({
+ highlighted,
+ instrument,
+ language,
+ languageOptions,
+ onClick,
+ onLanguageChange
+}: InstrumentCardProps) => {
const { t } = useTranslation();
+ // Narrowed once, so the dropdown's own props need no assertions.
+ const languageSelect =
+ language && onLanguageChange && languageOptions && languageOptions.length > 1
+ ? { onLanguageChange, options: languageOptions, value: language }
+ : null;
+
const license = licenses.get(instrument.details.license);
const content: CardItem[] = [
@@ -62,16 +83,18 @@ export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentC
es: 'Idiomas',
fr: 'Langues'
}),
- text: instrument.supportedLanguages
- .map((language) => {
- switch (language) {
- case 'en':
- return 'English';
- case 'fr':
- return 'Français';
- }
- })
- .join(', ')
+ text: languageSelect
+ ? undefined
+ : instrument.supportedLanguages
+ .map((supported) => {
+ switch (supported) {
+ case 'en':
+ return 'English';
+ case 'fr':
+ return 'Français';
+ }
+ })
+ .join(', ')
},
{
kind: 'text',
@@ -178,6 +201,22 @@ export const InstrumentCard = ({ highlighted, instrument, onClick }: InstrumentC
);
})}
+ {languageSelect && (
+