fix(i18n): keep opted-in dialog copy current while pending

This commit is contained in:
cesnimda
2026-11-17 07:21:47 +01:00
parent df853cb37b
commit b3ebf632fa
8 changed files with 172 additions and 25 deletions
@@ -483,7 +483,7 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
const generation = session.generation;
const active = () => session.active && session.jobId === jobId && session.generation === generation;
if (!active()) return;
if (!(await confirmAction(t("correspondenceDeleteConfirm"), { title: t("correspondenceDeleteTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
if (!(await confirmAction({ key: "correspondenceDeleteConfirm" }, { title: { key: "correspondenceDeleteTitle" }, confirmLabel: { key: "adminUsersDelete" }, destructive: true }))) return;
if (!active()) return;
try {
await api.delete(`/correspondence/${messageId}`);
+9 -8
View File
@@ -1,12 +1,13 @@
import { resolveDialogText, type DialogText } from "./dialogText";
import React, { createContext, useCallback, useContext, useId, useMemo, useRef, useState } from "react";
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from "@mui/material";
import { useOptionalI18n } from "./i18n/I18nProvider";
type ConfirmOptions = {
title?: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
title?: DialogText;
message: DialogText;
confirmLabel?: DialogText;
cancelLabel?: DialogText;
destructive?: boolean;
};
@@ -66,19 +67,19 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
if (node.ownerDocument.activeElement === node) cancelRef.current?.focus();
} },
}}>
<DialogTitle id={titleId} sx={{ pb: 1, fontWeight: 800 }}>{state.title ?? i18n?.t("confirmAction") ?? "Confirm action"}</DialogTitle>
<DialogTitle id={titleId} sx={{ pb: 1, fontWeight: 800 }}>{resolveDialogText(state.title ?? { key: "confirmAction" }, i18n?.t)}</DialogTitle>
<DialogContent role="region" aria-labelledby={titleId} tabIndex={0}>
<Alert severity={state.destructive ? "warning" : "info"} variant="outlined" sx={{ mb: 2 }}>
{state.destructive
? i18n?.t("confirmDestructiveHint") ?? "This action may be hard to undo."
: i18n?.t("confirmStandardHint") ?? "Please confirm this action."}
</Alert>
<Typography id={messageId} sx={{ color: "text.secondary" }}>{state.message}</Typography>
<Typography id={messageId} sx={{ color: "text.secondary" }}>{resolveDialogText(state.message, i18n?.t)}</Typography>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5, gap: 1 }}>
<Button ref={cancelRef} autoFocus onClick={() => closeWith(false)}>{state.cancelLabel ?? i18n?.t("cancel") ?? "Cancel"}</Button>
<Button ref={cancelRef} autoFocus onClick={() => closeWith(false)}>{resolveDialogText(state.cancelLabel ?? { key: "cancel" }, i18n?.t)}</Button>
<Button color={state.destructive ? "error" : "primary"} variant="contained" onClick={() => closeWith(true)}>
{state.confirmLabel ?? i18n?.t("confirm") ?? "Confirm"}
{resolveDialogText(state.confirmLabel ?? { key: "confirm" }, i18n?.t)}
</Button>
</DialogActions>
</Dialog>
@@ -1,6 +1,6 @@
import React from "react";
import "@testing-library/jest-dom";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import { ToastProvider } from "./toast";
@@ -694,15 +694,41 @@ describe("correspondence Gmail import", () => {
});
describe("confirmed correspondence deletion lifetime", () => {
async function requestDeletion() {
async function requestDeletion(language: 'en' | 'nb' = 'en') {
window.localStorage.setItem('uiLanguage', language);
correspondenceMessages = [{ id: 700, jobApplicationId: 42, from: "Company", content: "Recorded correspondence" }];
const view = renderDialog();
fireEvent.click(await screen.findByRole("button", { name: translations.en.correspondenceDeleteTitle }));
await screen.findByRole("dialog", { name: translations.en.correspondenceDeleteTitle });
fireEvent.click(await screen.findByRole("button", { name: translations[language].correspondenceDeleteTitle }));
await screen.findByRole("dialog", { name: translations[language].correspondenceDeleteTitle });
expect(mockedApi.delete).not.toHaveBeenCalled();
return view;
}
test.each([['en', 'nb', true], ['nb', 'en', false]] as const)('open delete confirmation follows %s to %s without resolving its pending decision', async (from, to, accept) => {
if (accept) mockedApi.delete.mockResolvedValueOnce({ data: {} } as any);
await requestDeletion(from);
const opened = screen.getByRole('dialog', { name: translations[from].correspondenceDeleteTitle });
const focused = within(opened).getByRole('button', { name: translations[from].cancel });
act(() => focused.focus());
const reads = mockedApi.get.mock.calls.length;
await act(async () => { window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })); });
const dialog = screen.getByRole('dialog', { name: translations[to].correspondenceDeleteTitle });
expect(within(dialog).getByText(translations[to].correspondenceDeleteConfirm)).toBeVisible();
expect(focused).toHaveFocus();
expect(mockedApi.get).toHaveBeenCalledTimes(reads);
expect(mockedApi.delete).not.toHaveBeenCalled();
if (accept) {
correspondenceMessages = [];
fireEvent.click(within(dialog).getByRole('button', { name: translations[to].adminUsersDelete }));
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledWith('/correspondence/700'));
expect(mockedApi.delete).toHaveBeenCalledTimes(1);
} else {
fireEvent.click(within(dialog).getByRole('button', { name: translations[to].cancel }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(mockedApi.delete).not.toHaveBeenCalled();
}
});
test("cancel keeps the recorded correspondence and sends no DELETE", async () => {
await requestDeletion();
fireEvent.click(screen.getByRole("button", { name: translations.en.cancel }));
+110
View File
@@ -0,0 +1,110 @@
import React from "react";
import "@testing-library/jest-dom";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import { useDialogActions } from "./dialogs";
import { I18nProvider } from "./i18n/I18nProvider";
import type { DialogText } from "./dialogText";
type Copy = { title: DialogText; message: DialogText; confirmLabel: DialogText; cancelLabel: DialogText };
type Kind = "confirm" | "prompt";
const userText = 'Søknad 東京 🧑‍💻 <img src=x onerror=alert(1)> & {count}';
const metadata: Copy = {
title: { key: "attachmentsTitle", params: { count: 0 } },
message: { key: "attachmentsDeleteConfirm", params: { name: userText } },
confirmLabel: { key: "confirm" },
cancelLabel: { key: "cancel" },
};
const copyByLanguage = {
en: { title: "Attachments (0)", message: `Delete attachment "${userText}"?`, confirm: "Confirm", cancel: "Cancel" },
nb: { title: "Vedlegg (0)", message: `Slette vedlegget "${userText}"?`, confirm: "Bekreft", cancel: "Avbryt" },
};
function Caller({ kind, copy, result }: { kind: Kind; copy: Copy; result: (value: boolean | string | null) => void }) {
const { confirmAction, promptForValue } = useDialogActions();
return <button onClick={() => {
if (kind === "confirm") void confirmAction(copy.message, { ...copy, destructive: true }).then(result);
else void promptForValue(copy.message, "Original draft", copy).then(result);
}}>Open</button>;
}
function mount(kind: Kind, copy: Copy, result: (value: boolean | string | null) => void, localized = true) {
const providers = <ConfirmProvider><PromptProvider><Caller kind={kind} copy={copy} result={result} /></PromptProvider></ConfirmProvider>;
render(localized ? <I18nProvider>{providers}</I18nProvider> : providers);
const opener = screen.getByRole("button", { name: "Open" });
opener.focus();
fireEvent.click(opener);
}
afterEach(() => localStorage.removeItem("uiLanguage"));
test.each([
["confirm", "en", "nb", true], ["confirm", "nb", "en", false],
["prompt", "en", "nb", true], ["prompt", "nb", "en", false],
] as const)("pending %s resolves metadata from %s to %s and settles once", async (kind, from, to, accepted) => {
localStorage.setItem("uiLanguage", from);
const result = jest.fn();
mount(kind, metadata, result);
const dialog = await screen.findByRole("dialog", { name: copyByLanguage[from].title });
expect(dialog).toHaveAccessibleDescription(copyByLanguage[from].message);
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].confirm })).toBeVisible();
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].cancel })).toBeVisible();
const input = kind === "prompt" ? within(dialog).getByRole("textbox") as HTMLInputElement : null;
if (input) {
await waitFor(() => expect(input).toHaveFocus());
fireEvent.change(input, { target: { value: userText } });
input.setSelectionRange(2, 7);
expect(input).toHaveAttribute("maxlength", "180");
expect(input).toHaveAccessibleDescription(`${userText.length}/180`);
} else {
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].cancel })).toHaveFocus();
}
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: to })));
expect(screen.getByRole("dialog", { name: copyByLanguage[to].title })).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(copyByLanguage[to].message);
expect(dialog.querySelector("img")).toBeNull();
if (input) {
expect(within(dialog).getByRole("textbox", { name: copyByLanguage[to].message })).toBe(input);
expect(input).toHaveValue(userText);
expect(input).toHaveFocus();
expect([input.selectionStart, input.selectionEnd]).toEqual([2, 7]);
}
expect(result).not.toHaveBeenCalled();
const action = within(dialog).getByRole("button", { name: copyByLanguage[to][accepted ? "confirm" : "cancel"] });
fireEvent.click(action); fireEvent.click(action);
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? accepted : accepted ? userText : null);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Open" })).toHaveFocus();
});
test.each(["confirm", "prompt"] as const)("%s metadata falls back to interpolated English without I18n context", async kind => {
localStorage.setItem("uiLanguage", "nb");
const result = jest.fn();
mount(kind, metadata, result, false);
const dialog = await screen.findByRole("dialog", { name: "Attachments (0)" });
expect(dialog).toHaveAccessibleDescription(`Delete attachment "${userText}"?`);
expect(dialog.querySelector("img")).toBeNull();
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each([
["confirm", ""], ["prompt", ""],
["confirm", "confirmAction"], ["prompt", "enterValue"],
] as const)("%s leaves literal %j verbatim during locale changes", async (kind, literal) => {
localStorage.setItem("uiLanguage", "en");
const result = jest.fn();
mount(kind, { title: literal, message: literal, confirmLabel: literal, cancelLabel: literal }, result);
const dialog = await screen.findByRole("dialog");
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })));
expect(within(dialog).getByRole("heading").textContent).toBe(literal);
expect(document.getElementById(dialog.getAttribute("aria-describedby")!)?.textContent).toBe(literal);
expect(within(dialog).getAllByRole("button").map(button => button.textContent)).toEqual([literal, literal]);
expect(result).not.toHaveBeenCalled();
fireEvent.keyDown(dialog, { key: "Escape" });
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
+8
View File
@@ -0,0 +1,8 @@
import { interpolate, type TranslationParams } from "./i18n/I18nProvider";
import { translations, type TranslationKey } from "./i18n/translations";
export type DialogText = string | { key: TranslationKey; params?: TranslationParams };
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);
}
+3 -2
View File
@@ -1,3 +1,4 @@
import { type DialogText } from "./dialogText";
import { useConfirm } from "./confirm";
import { usePrompt } from "./prompt";
@@ -6,7 +7,7 @@ export function useDialogActions() {
const { prompt } = usePrompt();
return {
confirmAction: (message: string, options?: { title?: string; confirmLabel?: string; cancelLabel?: string; destructive?: boolean }) =>
confirmAction: (message: DialogText, options?: { title?: DialogText; confirmLabel?: DialogText; cancelLabel?: DialogText; destructive?: boolean }) =>
confirm({
message,
title: options?.title,
@@ -14,7 +15,7 @@ export function useDialogActions() {
cancelLabel: options?.cancelLabel,
destructive: options?.destructive,
}),
promptForValue: (message: string, defaultValue = "", options?: { title?: string; confirmLabel?: string; cancelLabel?: string }) =>
promptForValue: (message: DialogText, defaultValue = "", options?: { title?: DialogText; confirmLabel?: DialogText; cancelLabel?: DialogText }) =>
prompt({
message,
defaultValue,
+2 -2
View File
@@ -3,7 +3,7 @@ import { translations, TranslationKey, UiLanguage } from "./translations";
import { api } from "../api";
import { useOptionalToast } from "../toast";
type TranslationParams = Record<string, string | number>;
export type TranslationParams = Record<string, string | number>;
type Ctx = {
language: UiLanguage;
@@ -15,7 +15,7 @@ type Ctx = {
const I18nContext = createContext<Ctx | null>(null);
function interpolate(template: string, params?: TranslationParams) {
export function interpolate(template: string, params?: TranslationParams) {
if (!params) return template;
return template.replace(/\{(\w+)\}/g, (_, key) => String(params[key] ?? `{${key}}`));
}
+9 -8
View File
@@ -1,13 +1,14 @@
import { resolveDialogText, type DialogText } from "./dialogText";
import React, { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField, Typography } from "@mui/material";
import { useOptionalI18n } from "./i18n/I18nProvider";
type PromptOptions = {
title?: string;
message: string;
title?: DialogText;
message: DialogText;
defaultValue?: string;
confirmLabel?: string;
cancelLabel?: string;
confirmLabel?: DialogText;
cancelLabel?: DialogText;
};
type PromptContextValue = {
@@ -67,14 +68,14 @@ export function PromptProvider({ children }: { children: React.ReactNode }) {
{children}
<Dialog open={state.open} onClose={() => closeWith(null)} aria-describedby={messageId} fullWidth maxWidth="xs"
slotProps={{ paper: { sx: { borderRadius: 3, border: 1, borderColor: "divider", backgroundImage: "none" } } }}>
<DialogTitle sx={{ pb: 1, fontWeight: 800 }}>{state.title ?? i18n?.t("enterValue") ?? "Enter value"}</DialogTitle>
<DialogTitle sx={{ pb: 1, fontWeight: 800 }}>{resolveDialogText(state.title ?? { key: "enterValue" }, i18n?.t)}</DialogTitle>
<DialogContent>
<Typography id={messageId} sx={{ color: "text.secondary", mb: 1.5 }}>{state.message}</Typography>
<Typography id={messageId} sx={{ color: "text.secondary", mb: 1.5 }}>{resolveDialogText(state.message, i18n?.t)}</Typography>
<TextField inputRef={inputRef} autoFocus fullWidth value={value} onChange={(e) => setValue(e.target.value)} inputProps={{ maxLength: 180, "aria-labelledby": messageId }} helperText={`${value.length}/180`} />
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2.5, gap: 1 }}>
<Button onClick={() => closeWith(null)}>{state.cancelLabel ?? i18n?.t("cancel") ?? "Cancel"}</Button>
<Button variant="contained" onClick={() => closeWith(value)}>{state.confirmLabel ?? i18n?.t("save") ?? "Save"}</Button>
<Button onClick={() => closeWith(null)}>{resolveDialogText(state.cancelLabel ?? { key: "cancel" }, i18n?.t)}</Button>
<Button variant="contained" onClick={() => closeWith(value)}>{resolveDialogText(state.confirmLabel ?? { key: "save" }, i18n?.t)}</Button>
</DialogActions>
</Dialog>
</PromptContext.Provider>