Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(toasts): give a toast a cross to close it, inside its top end corner

Nicolas Gonzalezb86449f9e58b
diff --git a/src/components/ui/sonner.test.tsx b/src/components/ui/sonner.test.tsx
new file mode 100644
index 000000000..a34108fab
--- /dev/null
+++ b/src/components/ui/sonner.test.tsx
@@ -0,0 +1,77 @@
+// @vitest-environment jsdom
+// A toast used to be dismissable only by waiting. That is fine for a confirmation and
+// wrong for an error: the 3s timer can retire a long description before it has been read,
+// and a run of failures stacks up over the editor with nothing to clear it.
+//
+// The placement itself (top END corner, mirrored for RTL) is CSS custom properties in
+// src/index.css, which jsdom does not apply — what is pinned here is that the button
+// exists at all and that it speaks the app's language rather than sonner's hardcoded
+// "Close toast".
+import "@testing-library/jest-dom";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { render, screen } from "@testing-library/react";
+import { toast } from "sonner";
+import { afterEach, describe, expect, it } from "vitest";
+import { I18nProvider } from "@/contexts/I18nContext";
+import { Toaster } from "./sonner";
+
+afterEach(() => {
+ toast.dismiss();
+});
+
+describe("Toaster", () => {
+ it("gives every toast a close button", async () => {
+ render(
+ <I18nProvider>
+ <Toaster />
+ </I18nProvider>,
+ );
+ toast("Export finished");
+ expect(await screen.findByText("Export finished")).toBeInTheDocument();
+ expect(await screen.findByRole("button", { name: /close notification/i })).toBeInTheDocument();
+ });
+
+ // Sonner's default label is the untranslated "Close toast", and a screen reader in any
+ // of the other twelve locales would hear it.
+ it("labels it from the app's own strings, not sonner's default", async () => {
+ render(
+ <I18nProvider>
+ <Toaster />
+ </I18nProvider>,
+ );
+ toast.error("Could not export");
+ const close = await screen.findByRole("button", { name: /close notification/i });
+ expect(close).toHaveAttribute("data-close-button", "true");
+ expect(screen.queryByRole("button", { name: /close toast/i })).not.toBeInTheDocument();
+ });
+});
+
+// The placement is three CSS custom properties that sonner owns. jsdom cannot tell us
+// where the button lands, but it can tell us the contract still exists — and that is the
+// failure mode that matters: on a sonner upgrade that renames them, the override quietly
+// stops applying and the cross goes back to the top LEFT with every test still green.
+describe("close button placement contract", () => {
+ const root = path.resolve(__dirname, "..", "..", "..");
+ const sonnerCss = readFileSync(path.join(root, "node_modules/sonner/dist/styles.css"), "utf8");
+ const appCss = readFileSync(path.join(root, "src/index.css"), "utf8");
+
+ for (const variable of [
+ "--toast-close-button-start",
+ "--toast-close-button-end",
+ "--toast-close-button-transform",
+ ]) {
+ it(`sonner still positions the close button with ${variable}`, () => {
+ expect(sonnerCss).toContain(variable);
+ expect(appCss).toContain(variable);
+ });
+ }
+
+ // Both directions, because the override exists to MOVE the button, and doing that in
+ // one direction only would leave ar mirrored the wrong way once the app sets `dir`.
+ for (const dir of ["ltr", "rtl"]) {
+ it(`overrides it for dir="${dir}"`, () => {
+ expect(appCss).toContain(`[data-sonner-toaster][dir="${dir}"]`);
+ });
+ }
+});
diff --git a/src/components/ui/sonner.tsx b/src/components/ui/sonner.tsx
index 54cd6023d..f12071cc0 100644
--- a/src/components/ui/sonner.tsx
+++ b/src/components/ui/sonner.tsx
@@ -1,5 +1,6 @@
import type { CSSProperties } from "react";
import { Toaster as Sonner } from "sonner";
+import { useScopedT } from "@/contexts/I18nContext";
import { cn } from "@/lib/utils";
type ToasterProps = React.ComponentProps<typeof Sonner>;
@@ -18,6 +19,7 @@ const TOKEN_STYLE = {
} as CSSProperties;
const Toaster = ({ className, style, ...props }: ToasterProps) => {
+ const tc = useScopedT("common");
return (
<Sonner
className={cn(
@@ -26,7 +28,16 @@ const Toaster = ({ className, style, ...props }: ToasterProps) => {
)}
style={{ ...TOKEN_STYLE, ...style }}
duration={3000}
+ // A toast that can only be waited out is the one case where the 3s timer works
+ // against the reader: an error with a long description is dismissed before it is
+ // finished, and a stack of them hides the editor with no way to clear it. The
+ // cross is placed on the END side by `src/index.css` — sonner puts it on the
+ // start side, which is not where anything else in this app closes.
+ closeButton
toastOptions={{
+ // Sonner's default is the untranslated "Close toast"; the rest of the app
+ // speaks 13 languages.
+ closeButtonAriaLabel: tc("actions.closeNotification"),
style: { boxShadow: "var(--elev-pop)" },
classNames: {
// `!`: sonner colours the description per its own theme, above any plain class.
@@ -35,6 +46,8 @@ const Toaster = ({ className, style, ...props }: ToasterProps) => {
"!h-7 !rounded-[8px] !bg-[var(--accent)] !px-2.5 !text-[13px] !text-[var(--accent-on)]",
cancelButton:
"!h-7 !rounded-[8px] !bg-[var(--surface-3)] !px-2.5 !text-[13px] !text-[var(--fg)]",
+ // The button's placement lives in src/index.css; only its colours follow the tokens.
+ closeButton: "!text-[var(--muted)] hover:!text-[var(--fg)]",
},
}}
{...props}
diff --git a/src/i18n/locales/ar/common.json b/src/i18n/locales/ar/common.json
index 9ca616a41..7bc5182b4 100644
--- a/src/i18n/locales/ar/common.json
+++ b/src/i18n/locales/ar/common.json
@@ -48,7 +48,8 @@
"unhide": "إظهار الكل",
"saveDiagnostics": "حفظ التشخيصات",
"starOnGithub": "ضع نجمة على GitHub",
- "permissions": "الأذونات…"
+ "permissions": "الأذونات…",
+ "closeNotification": "إغلاق الإشعار"
},
"updates": {
"available": "يتوفر OpenScreen {{latestVersion}}. الإصدار المثبت هو {{currentVersion}}.",
diff --git a/src/i18n/locales/cs/common.json b/src/i18n/locales/cs/common.json
index 0ceb1aabb..955e374d8 100644
--- a/src/i18n/locales/cs/common.json
+++ b/src/i18n/locales/cs/common.json
@@ -48,7 +48,8 @@
"unhide": "Zobrazit vše",
"saveDiagnostics": "Uložit diagnostiku",
"starOnGithub": "Dát hvězdu na GitHubu",
- "permissions": "Oprávnění…"
+ "permissions": "Oprávnění…",
+ "closeNotification": "Zavřít oznámení"
},
"updates": {
"available": "OpenScreen {{latestVersion}} je k dispozici. Používáte verzi {{currentVersion}}.",
diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json
index cc7aec870..8644d50a5 100644
--- a/src/i18n/locales/en/common.json
+++ b/src/i18n/locales/en/common.json
@@ -48,7 +48,8 @@
"unhide": "Show All",
"saveDiagnostics": "Save Diagnostics",
"starOnGithub": "Star on GitHub",
- "permissions": "Permissions…"
+ "permissions": "Permissions…",
+ "closeNotification": "Close notification"
},
"updates": {
"available": "OpenScreen {{latestVersion}} is available. You are using {{currentVersion}}.",
diff --git a/src/i18n/locales/es/common.json b/src/i18n/locales/es/common.json
index c39a9ce34..23ffca48a 100644
--- a/src/i18n/locales/es/common.json
+++ b/src/i18n/locales/es/common.json
@@ -48,7 +48,8 @@
"unhide": "Mostrar todo",
"saveDiagnostics": "Guardar diagnósticos",
"starOnGithub": "Dar una estrella en GitHub",
- "permissions": "Permisos…"
+ "permissions": "Permisos…",
+ "closeNotification": "Cerrar la notificación"
},
"updates": {
"available": "OpenScreen {{latestVersion}} está disponible. Estás usando {{currentVersion}}.",
diff --git a/src/i18n/locales/fr/common.json b/src/i18n/locales/fr/common.json
index 8c9262612..6ff9b1b9e 100644
--- a/src/i18n/locales/fr/common.json
+++ b/src/i18n/locales/fr/common.json
@@ -48,7 +48,8 @@
"unhide": "Tout afficher",
"saveDiagnostics": "Enregistrer les diagnostics",
"starOnGithub": "Mettre une étoile sur GitHub",
- "permissions": "Autorisations…"
+ "permissions": "Autorisations…",
+ "closeNotification": "Fermer la notification"
},
"updates": {
"available": "OpenScreen {{latestVersion}} est disponible. Vous utilisez la version {{currentVersion}}.",
diff --git a/src/i18n/locales/it/common.json b/src/i18n/locales/it/common.json
index 274854cae..171aa03bc 100644
--- a/src/i18n/locales/it/common.json
+++ b/src/i18n/locales/it/common.json
@@ -48,7 +48,8 @@
"unhide": "Mostra tutto",
"saveDiagnostics": "Salva dati diagnostici",
"starOnGithub": "Metti una stella su GitHub",
- "permissions": "Permessi…"
+ "permissions": "Permessi…",
+ "closeNotification": "Chiudi la notifica"
},
"updates": {
"available": "OpenScreen {{latestVersion}} è disponibile. Stai usando la versione {{currentVersion}}.",
diff --git a/src/i18n/locales/ja-JP/common.json b/src/i18n/locales/ja-JP/common.json
index 164873f7b..71e0424e4 100644
--- a/src/i18n/locales/ja-JP/common.json
+++ b/src/i18n/locales/ja-JP/common.json
@@ -48,7 +48,8 @@
"unhide": "すべて表示",
"saveDiagnostics": "診断情報を保存",
"starOnGithub": "GitHub でスターを付ける",
- "permissions": "アクセス許可…"
+ "permissions": "アクセス許可…",
+ "closeNotification": "通知を閉じる"
},
"updates": {
"available": "OpenScreen {{latestVersion}} を利用できます。現在のバージョンは {{currentVersion}} です。",
diff --git a/src/i18n/locales/ko-KR/common.json b/src/i18n/locales/ko-KR/common.json
index abc264f4d..0a63f2500 100644
--- a/src/i18n/locales/ko-KR/common.json
+++ b/src/i18n/locales/ko-KR/common.json
@@ -48,7 +48,8 @@
"unhide": "모두 보기",
"saveDiagnostics": "진단 정보 저장",
"starOnGithub": "GitHub에서 별 누르기",
- "permissions": "권한…"
+ "permissions": "권한…",
+ "closeNotification": "알림 닫기"
},
"updates": {
"available": "OpenScreen {{latestVersion}} 버전을 사용할 수 있습니다. 현재 버전은 {{currentVersion}}입니다.",
diff --git a/src/i18n/locales/pt-BR/common.json b/src/i18n/locales/pt-BR/common.json
index 0e7c91a97..6bcdcafcc 100644
--- a/src/i18n/locales/pt-BR/common.json
+++ b/src/i18n/locales/pt-BR/common.json
@@ -48,7 +48,8 @@
"unhide": "Mostrar Todos",
"saveDiagnostics": "Salvar Diagnósticos",
"starOnGithub": "Dar uma estrela no GitHub",
- "permissions": "Permissões…"
+ "permissions": "Permissões…",
+ "closeNotification": "Fechar a notificação"
},
"updates": {
"available": "O OpenScreen {{latestVersion}} está disponível. Você está usando a versão {{currentVersion}}.",
diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json
index e8c0e1dab..9a1375939 100644
--- a/src/i18n/locales/ru/common.json
+++ b/src/i18n/locales/ru/common.json
@@ -48,7 +48,8 @@
"unhide": "Показать все",
"saveDiagnostics": "Сохранить диагностику",
"starOnGithub": "Поставить звезду на GitHub",
- "permissions": "Разрешения…"
+ "permissions": "Разрешения…",
+ "closeNotification": "Закрыть уведомление"
},
"updates": {
"available": "Доступен OpenScreen {{latestVersion}}. Установлена версия {{currentVersion}}.",
diff --git a/src/i18n/locales/tr/common.json b/src/i18n/locales/tr/common.json
index 9b2f951ce..0d057ebec 100644
--- a/src/i18n/locales/tr/common.json
+++ b/src/i18n/locales/tr/common.json
@@ -48,7 +48,8 @@
"unhide": "Tümünü Göster",
"saveDiagnostics": "Teşhis Verilerini Kaydet",
"starOnGithub": "GitHub'da yıldız ver",
- "permissions": "İzinler…"
+ "permissions": "İzinler…",
+ "closeNotification": "Bildirimi kapat"
},
"updates": {
"available": "OpenScreen {{latestVersion}} kullanılabilir. Mevcut sürümünüz {{currentVersion}}.",
diff --git a/src/i18n/locales/vi/common.json b/src/i18n/locales/vi/common.json
index 68829ec45..d54016331 100644
--- a/src/i18n/locales/vi/common.json
+++ b/src/i18n/locales/vi/common.json
@@ -48,7 +48,8 @@
"unhide": "Hiển thị tất cả",
"saveDiagnostics": "Lưu thông tin chẩn đoán",
"starOnGithub": "Gắn sao trên GitHub",
- "permissions": "Quyền…"
+ "permissions": "Quyền…",
+ "closeNotification": "Đóng thông báo"
},
"updates": {
"available": "Đã có OpenScreen {{latestVersion}}. Bạn đang dùng phiên bản {{currentVersion}}.",
diff --git a/src/i18n/locales/zh-CN/common.json b/src/i18n/locales/zh-CN/common.json
index be2d19927..49ad7d680 100644
--- a/src/i18n/locales/zh-CN/common.json
+++ b/src/i18n/locales/zh-CN/common.json
@@ -48,7 +48,8 @@
"unhide": "显示全部",
"saveDiagnostics": "保存诊断信息",
"starOnGithub": "在 GitHub 上点星标",
- "permissions": "权限…"
+ "permissions": "权限…",
+ "closeNotification": "关闭通知"
},
"updates": {
"available": "OpenScreen {{latestVersion}} 已发布。当前版本为 {{currentVersion}}。",
diff --git a/src/i18n/locales/zh-TW/common.json b/src/i18n/locales/zh-TW/common.json
index f40a31bc9..90c550424 100644
--- a/src/i18n/locales/zh-TW/common.json
+++ b/src/i18n/locales/zh-TW/common.json
@@ -48,7 +48,8 @@
"unhide": "全部顯示",
"saveDiagnostics": "儲存診斷資料",
"starOnGithub": "在 GitHub 上給星",
- "permissions": "權限…"
+ "permissions": "權限…",
+ "closeNotification": "關閉通知"
},
"updates": {
"available": "OpenScreen {{latestVersion}} 已推出。目前版本為 {{currentVersion}}。",
diff --git a/src/index.css b/src/index.css
index 47ed55d2e..71b8fd853 100644
--- a/src/index.css
+++ b/src/index.css
@@ -336,3 +336,53 @@
-ms-overflow-style: none;
}
}
+
+/* Sonner puts the toast close button on the START side — top-left in a left-to-right UI —
+ and overhanging the corner, half outside the toast. Nothing else in this app closes
+ there: every dialog, pane and inspector puts its cross INSIDE the top end corner, and a
+ dismiss control that moves depending on the surface is one the eye has to hunt for.
+
+ Three things have to change together, which is why this is not a one-liner:
+ - the side, via sonner's own custom properties;
+ - the overhang, by dropping its translate — sonner's default pulls the button out of
+ the box by 35% in both axes;
+ - `top`, which sonner hardcodes to 0 rather than exposing as a variable, so it takes a
+ rule on the element itself.
+
+ Flipped per direction rather than hard-coded to `right`, so the mirroring survives an
+ RTL locale (ar ships today; the app does not set `dir` yet, but this must not be the
+ thing that breaks when it does).
+
+ The leading `html` is not decoration: sonner injects its stylesheet at runtime, after
+ this file, so an override of equal specificity would lose on source order. */
+html [data-sonner-toaster][dir="ltr"] {
+ --toast-close-button-start: unset;
+ --toast-close-button-end: 8px;
+ --toast-close-button-transform: none;
+}
+
+html [data-sonner-toaster][dir="rtl"] {
+ --toast-close-button-start: 8px;
+ --toast-close-button-end: unset;
+ --toast-close-button-transform: none;
+}
+
+/* Room for the button, so a long title does not run under it. Logical, not `padding-right`,
+ for the same mirroring reason as above. */
+html [data-sonner-toaster] [data-sonner-toast][data-styled="true"] {
+ padding-inline-end: 36px;
+}
+
+/* Inside the box, the chrome sonner gives the button stops making sense: a bordered,
+ opaque chip reads as a badge stuck on the corner when it is overhanging, and as a second
+ surface floating on the toast when it is not. Plain icon, weight on hover only. */
+html [data-sonner-toaster] [data-sonner-toast][data-styled="true"] [data-close-button] {
+ top: 8px;
+ border-color: transparent;
+ background: transparent;
+ transition: background 0.12s ease-out, color 0.12s ease-out;
+}
+
+html [data-sonner-toaster] [data-sonner-toast][data-styled="true"] [data-close-button]:hover {
+ background: rgb(255 255 255 / 10%);
+}