fix(i18n): resolve explicit dialog fallback parameters in the current language

This commit is contained in:
cesnimda
2026-11-17 14:49:05 +01:00
parent 04a8de37b9
commit 0bf0343c3f
8 changed files with 156 additions and 17 deletions
+1 -1
View File
@@ -407,7 +407,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
if (jobsToDelete.length === 0) return false;
if (jobsToDelete.length === 1) {
const job = jobsToDelete[0];
return confirmAction({ key: "jobTableMoveOneConfirm", params: { title: job.jobTitle, company: job.company?.name ?? t("jobTableCompany") } }, { title: { key: "jobTableMoveToTrashTitle" }, confirmLabel: { key: "jobTableMove" }, destructive: true });
return confirmAction({ key: "jobTableMoveOneConfirm", params: { title: job.jobTitle, company: job.company?.name ?? { key: "jobTableCompany" } } }, { title: { key: "jobTableMoveToTrashTitle" }, confirmLabel: { key: "jobTableMove" }, destructive: true });
}
return confirmAction({ key: "jobTableMoveManyConfirm", params: { count: jobsToDelete.length } }, { title: { key: "jobTableMoveJobsToTrashTitle" }, confirmLabel: { key: "jobTableMove" }, destructive: true });
};
@@ -1485,3 +1485,48 @@ test('user edits made during server acceptance are retained instead of overwritt
expect(screen.getByLabelText('Headline override')).toHaveValue('');
expect(mockedApi.put).not.toHaveBeenCalled();
});
test.each((['en', 'nb'] as const).flatMap(language => [
{ kind: 'custom', key: 'custom:sample', title: '' },
{ kind: 'custom', key: 'custom:sample', title: ' ' },
{ kind: 'custom', key: 'custom:sample', title: 'cvEditorUntitled' },
{ kind: 'builtin', key: 'skills', title: undefined },
{ kind: 'builtin', key: 'skills', title: '' },
{ kind: 'builtin', key: 'skills', title: 'cvSectionSkills' },
{ kind: 'builtin', key: 'legacy-section', title: undefined },
{ kind: 'builtin', key: 'constructor', title: undefined },
{ kind: 'builtin', key: '__proto__', title: undefined },
].map(fixture => [language, fixture] as const)))('fallback parameter for %s section %j preserves literal titles', async (language, fixture) => {
localStorage.setItem('uiLanguage', language);
const next = language === 'en' ? 'nb' : 'en';
const custom = fixture.kind === 'custom';
const settings = { ...variant.settings, sectionsExplicit: true, sections: [{ key: fixture.key, ...(fixture.title === undefined ? {} : { title: fixture.title }) }], customSections: custom ? [{ key: 'sample', title: fixture.title!, items: ['Keep original content'] }] : [] };
routeGet(() => Promise.resolve({ data: { ...variant, settings } }));
renderAt(3);
await screen.findByDisplayValue('Backend CV');
fireEvent.click(screen.getByRole('tab', { name: translations[language].cvEditorContent }));
const label = fixture.title ?? (fixture.key === 'skills' ? translations[language].cvSectionSkills : fixture.key);
const opener = screen.getByRole('button', { name: translations[language].cvEditorRemoveSection.replace('{section}', label).replace(/\s+/g, ' ').trim() });
opener.focus(); fireEvent.click(opener);
const titleKey = custom ? 'cvEditorDeleteCustomTitle' : 'cvEditorRemoveSectionTitle';
const dialog = await screen.findByRole('dialog', { name: translations[language][titleKey] });
const reads = mockedApi.get.mock.calls.length;
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: next })));
expect(screen.getByRole('dialog', { name: translations[next][titleKey] })).toBe(dialog);
const parameter = custom ? fixture.title || translations[next].cvEditorUntitled : fixture.title ?? (fixture.key === 'skills' ? translations[next].cvSectionSkills : fixture.key);
expect(dialog).toHaveAccessibleDescription((custom ? translations[next].cvEditorDeleteCustomMessage.replace('{title}', parameter) : translations[next].cvEditorRemoveSectionMessage.replace('{section}', parameter)).replace(/\s+/g, ' ').trim());
expect(within(dialog).getByRole('button', { name: translations[next][custom ? 'cvEditorDeleteSection' : 'cvEditorRemoveFromCv'] })).toBeInTheDocument();
expect(mockedApi.get).toHaveBeenCalledTimes(reads);
expect(mockedApi.put).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: translations[next].cancel }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(opener).toHaveFocus();
expect(screen.getByRole('button', { name: translations[next].cvEditorRemoveSection.replace('{section}', fixture.title ?? (fixture.key === 'skills' ? translations[next].cvSectionSkills : fixture.key)).replace(/\s+/g, ' ').trim() })).toBeInTheDocument();
expect(mockedApi.put).not.toHaveBeenCalled();
fireEvent.click(opener);
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: translations[next][custom ? 'cvEditorDeleteSection' : 'cvEditorRemoveFromCv'] }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: translations[next].cvEditorSaveNow }));
await waitFor(() => expect(mockedApi.put).toHaveBeenCalledWith('/cv/variants/3', expect.objectContaining({ expectedVersion: 4, settings: expect.objectContaining(custom ? { customSections: [], sections: [] } : { customSections: [], sections: [expect.objectContaining({ key: fixture.key, hidden: true })] }) })));
expect(mockedApi.put).toHaveBeenCalledTimes(1);
});
@@ -682,3 +682,26 @@ test('CV deletion requires confirmation and supports cancellation', async () =>
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledWith('/cv/variants/1'));
await waitFor(() => expect(screen.queryByText('Frontend CV')).not.toBeInTheDocument());
});
test.each((['en', 'nb'] as const).flatMap(language => ['', 'cvDashboardThisCv', 'Søknad 東京 <cv>'].map(name => [language, name] as const)))('fallback parameter for %s CV literal name %j remains literal', async (language, name) => {
localStorage.setItem('uiLanguage', language);
const next = language === 'en' ? 'nb' : 'en';
mockedApi.get.mockImplementation(async url => ({ data: url === '/cv/themes' ? themes : url === '/cv/variants' ? [{ ...existingCv, name }] : [] }) as any);
renderPage();
const opener = await screen.findByRole('button', { name: translations[language].cvDashboardActionsFor.replace('{name}', name).replace(/\s+/g, ' ').trim() });
fireEvent.click(opener);
fireEvent.click(await screen.findByRole('menuitem', { name: translations[language].cvDashboardDelete }));
const dialog = await screen.findByRole('dialog', { name: translations[language].cvDashboardDeleteCv });
const readCount = mockedApi.get.mock.calls.length;
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: next })));
expect(screen.getByRole('dialog', { name: translations[next].cvDashboardDeleteCv })).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(translations[next].cvDashboardDeleteMessage.replace('{name}', name));
expect(dialog.querySelector('cv')).toBeNull();
expect(mockedApi.get).toHaveBeenCalledTimes(readCount);
expect(mockedApi.delete).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: translations[next].cancel }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(mockedApi.delete).not.toHaveBeenCalled();
expect(mockedApi.put).not.toHaveBeenCalled();
expect(mockNavigate).not.toHaveBeenCalled();
});
+37 -1
View File
@@ -5,7 +5,8 @@ import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import { useDialogActions } from "./dialogs";
import { I18nProvider } from "./i18n/I18nProvider";
import type { DialogText } from "./dialogText";
import { resolveDialogText, type DialogText } from "./dialogText";
import { translations } from "./i18n/translations";
type Copy = { title: DialogText; message: DialogText; confirmLabel: DialogText; cancelLabel: DialogText };
type Kind = "confirm" | "prompt";
@@ -108,3 +109,38 @@ test.each([
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each([
["confirm", "en", "nb"], ["confirm", "nb", "en"],
["prompt", "en", "nb"], ["prompt", "nb", "en"],
] as const)("fallback parameter in pending %s follows %s to %s", async (kind, from, to) => {
localStorage.setItem("uiLanguage", from);
const result = jest.fn();
mount(kind, { ...metadata, message: { key: "jobTableMoveOneConfirm", params: { title: userText, company: { key: "jobTableCompany" } } } }, result);
const dialog = await screen.findByRole("dialog");
expect(dialog).toHaveAccessibleDescription(translations[from].jobTableMoveOneConfirm.replace("{title}", userText).replace("{company}", translations[from].jobTableCompany));
const input = kind === "prompt" ? within(dialog).getByRole("textbox") : null;
if (input) fireEvent.change(input, { target: { value: userText } });
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: to })));
expect(screen.getByRole("dialog")).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(translations[to].jobTableMoveOneConfirm.replace("{title}", userText).replace("{company}", translations[to].jobTableCompany));
expect(dialog.querySelector("img")).toBeNull();
if (input) expect(input).toHaveValue(userText);
expect(result).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole("button", { name: translations[to].cancel }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each(["confirm", "prompt"] as const)("fallback parameter in %s resolves English without context", async kind => {
const result = jest.fn();
mount(kind, { ...metadata, message: { key: "cvDashboardDeleteMessage", params: { name: { key: "cvDashboardThisCv" } } } }, result, false);
const dialog = await screen.findByRole("dialog");
expect(dialog).toHaveAccessibleDescription(translations.en.cvDashboardDeleteMessage.replace("{name}", translations.en.cvDashboardThisCv));
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
});
test.each(["", 0, "jobTableCompany", userText])("fallback parameter preserves primitive %j verbatim", value => {
expect(resolveDialogText({ key: "jobTableMoveOneConfirm", params: { title: value, company: { key: "jobTableCompany" } } })).toBe(translations.en.jobTableMoveOneConfirm.replace("{title}", String(value)).replace("{company}", translations.en.jobTableCompany));
});
+6 -2
View File
@@ -1,8 +1,12 @@
import { interpolate, type TranslationParams } from "./i18n/I18nProvider";
import { translations, type TranslationKey } from "./i18n/translations";
export type DialogText = string | { key: TranslationKey; params?: TranslationParams };
type DialogParams = Record<string, string | number | { key: TranslationKey }>;
export type DialogText = string | { key: TranslationKey; params?: DialogParams };
export function resolveDialogText(text: DialogText, t?: (key: TranslationKey, params?: TranslationParams) => string): string {
return typeof text === "string" ? text : t ? t(text.key, text.params) : interpolate(translations.en[text.key], text.params);
if (typeof text === "string") return text;
const translate = t ?? ((key: TranslationKey, params?: TranslationParams) => interpolate(translations.en[key], params));
const params = text.params && Object.fromEntries(Object.entries(text.params).map(([name, value]) => [name, typeof value === "object" ? translate(value.key) : value]));
return translate(text.key, params);
}
@@ -209,3 +209,27 @@ describe('individual application outcome language', () => {
if (action === 'delete' && outcome === 'resolve') expect(await screen.findByRole('button', { name: translations[to].jobTableUndo })).toBeVisible();
});
});
test.each((['en', 'nb'] as const).flatMap(language => [undefined, null, '', 'jobTableCompany', 'Søknad 東京 <company>'].map(company => [language, company] as const)))('fallback parameter for %s company %j preserves selection and literal names', async (language, company) => {
localStorage.setItem('uiLanguage', language);
const next = language === 'en' ? 'nb' : 'en';
const job = { ...jobs[0], company: company === undefined ? undefined : { id: 1, name: company } };
mockedApi.get.mockImplementation(async url => ({ data: url === '/jobapplications' ? { items: [job], total: 1, page: 1, pageSize: 15 } : [] }) as any);
show();
await waitFor(() => expect(document.querySelector('[data-job-row-id="1"]')).not.toBeNull());
fireEvent.click(screen.getByRole('button', { name: translations[language].jobTableSelectionMode }));
fireEvent.click(screen.getAllByRole('checkbox', { name: translations[language].jobTableSelectJob.replace('{title}', job.jobTitle) })[0]);
fireEvent.click(screen.getByRole('button', { name: translations[language].jobTableDeleteSelected }));
const dialog = await screen.findByRole('dialog', { name: translations[language].jobTableMoveToTrashTitle });
const readCount = mockedApi.get.mock.calls.length;
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: next })));
expect(screen.getByRole('dialog', { name: translations[next].jobTableMoveToTrashTitle })).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(translations[next].jobTableMoveOneConfirm.replace('{title}', job.jobTitle).replace('{company}', company ?? translations[next].jobTableCompany).replace(/\s+/g, ' ').trim());
expect(dialog.querySelector('company')).toBeNull();
expect(mockedApi.get).toHaveBeenCalledTimes(readCount);
expect(mockedApi.delete).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: translations[next].cancel }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(screen.getAllByRole('checkbox', { name: translations[next].jobTableSelectJob.replace('{title}', job.jobTitle) })[0]).toBeChecked();
expect(mockedApi.delete).not.toHaveBeenCalled();
});
+19 -12
View File
@@ -41,6 +41,7 @@ import {
import { previewDocumentHtml } from "../cvPreview";
import { useDialogActions } from "../dialogs";
import { useI18n } from "../i18n/I18nProvider";
import type { TranslationKey } from "../i18n/translations";
import { PageHeader } from "../layout/PageLayout";
import ViewStateNotice from "../components/ViewStateNotice";
@@ -1016,14 +1017,20 @@ function DocumentAiTab({ settings, outline, onGenerate, onAccept }: CvAiCallback
type Translate = ReturnType<typeof useI18n>["t"];
const SECTION_NAME_KEYS: Record<string, TranslationKey> = {
summary: "cvSectionSummary", experience: "cvSectionExperience", education: "cvSectionEducation",
projects: "cvSectionProjects", skills: "cvSectionSkills", certifications: "cvSectionCertifications",
languages: "cvSectionLanguages", interests: "cvSectionInterests", awards: "cvSectionAwards",
publications: "cvSectionPublications", organisations: "cvSectionOrganisations", references: "cvSectionReferences",
};
function sectionNameText(key: string, fallback: string) {
return Object.hasOwn(SECTION_NAME_KEYS, key) ? { key: SECTION_NAME_KEYS[key] } : typeof fallback === "string" ? fallback : key;
}
function sectionName(key: string, fallback: string, t: Translate) {
const labels: Record<string, string> = {
summary: t("cvSectionSummary"), experience: t("cvSectionExperience"), education: t("cvSectionEducation"),
projects: t("cvSectionProjects"), skills: t("cvSectionSkills"), certifications: t("cvSectionCertifications"),
languages: t("cvSectionLanguages"), interests: t("cvSectionInterests"), awards: t("cvSectionAwards"),
publications: t("cvSectionPublications"), organisations: t("cvSectionOrganisations"), references: t("cvSectionReferences"),
};
return labels[key] ?? fallback;
const text = sectionNameText(key, fallback);
return typeof text === "string" ? text : t(text.key);
}
function presetLabel(key: string, fallback: string, t: Translate) {
@@ -1135,9 +1142,9 @@ function ContentTab({ settings, update, outline, showPreviewEntry, onFocusPrevie
const updateCustom = (key: string, patch: Partial<CvCustomSectionSetting>) =>
update({ customSections: settings.customSections.map((c) => (c.key === key ? { ...c, ...patch } : c)) });
const removeCustom = async (section: CvCustomSectionSetting) => {
if (!(await confirmAction(t("cvEditorDeleteCustomMessage", { title: section.title || t("cvEditorUntitled") }), {
title: t("cvEditorDeleteCustomTitle"),
confirmLabel: t("cvEditorDeleteSection"),
if (!(await confirmAction({ key: "cvEditorDeleteCustomMessage", params: { title: section.title || { key: "cvEditorUntitled" } } }, {
title: { key: "cvEditorDeleteCustomTitle" },
confirmLabel: { key: "cvEditorDeleteSection" },
destructive: true,
}))) return;
update({
@@ -1186,7 +1193,7 @@ function ContentTab({ settings, update, outline, showPreviewEntry, onFocusPrevie
dragging={sectionDrag.dragIndex === i}
over={sectionDrag.overIndex === i && sectionDrag.dragIndex !== i}
outlineSection={outlineByKey[row.key]}
customSection={customBySectionKey[row.key]}
customSection={Object.hasOwn(customBySectionKey, row.key) ? customBySectionKey[row.key] : undefined}
settings={settings}
expanded={expandedSections.has(row.key)}
onToggle={() => toggleSection(row.key)}
@@ -1319,7 +1326,7 @@ function SectionRow({
</IconButton>
<IconButton size="small" aria-label={t("cvEditorRemoveSection", { section: sectionLabel })} onClick={() => {
if (customSection) onRemoveCustom();
else void confirmAction(t("cvEditorRemoveSectionMessage", { section: sectionLabel }), { title: t("cvEditorRemoveSectionTitle"), confirmLabel: t("cvEditorRemoveFromCv"), destructive: true }).then((confirmed) => { if (confirmed) onPatch({ hidden: true }); });
else void confirmAction({ key: "cvEditorRemoveSectionMessage", params: { section: row.title ?? sectionNameText(row.key, SECTION_LABELS[row.key] ?? row.key) } }, { title: { key: "cvEditorRemoveSectionTitle" }, confirmLabel: { key: "cvEditorRemoveFromCv" }, destructive: true }).then((confirmed) => { if (confirmed) onPatch({ hidden: true }); });
}}><DeleteOutlineIcon fontSize="small" /></IconButton>
<IconButton ref={toggleRef} size="small" aria-label={t(expanded ? "cvEditorCollapseSection" : "cvEditorExpandSection", { section: sectionLabel })} aria-expanded={expanded} onClick={onToggle}
sx={{ transform: expanded ? "rotate(180deg)" : "none", transition: "transform 150ms" }}>
+1 -1
View File
@@ -151,7 +151,7 @@ export default function CvBuilderPage() {
if (!active) return;
const variant = variants.find((item) => item.id === id);
try {
if (!(await confirmAction({ key: "cvDashboardDeleteMessage", params: { name: variant?.name ?? t("cvDashboardThisCv") } }, {
if (!(await confirmAction({ key: "cvDashboardDeleteMessage", params: { name: variant?.name ?? { key: "cvDashboardThisCv" } } }, {
title: { key: "cvDashboardDeleteCv" },
confirmLabel: { key: "cvDashboardDeleteCv" },
destructive: true,