Skip to content

Open source CapCut alternative.

TypeScript

fix(site): save language picks and stop reload loops

David Le882fe4ba4de5
diff --git a/site/src/app/[locale]/cut/app/(home)/settings/profile/EditorSection.tsx b/site/src/app/[locale]/cut/app/(home)/settings/profile/EditorSection.tsx
index 0c673fc6..0b6aa9c6 100644
--- a/site/src/app/[locale]/cut/app/(home)/settings/profile/EditorSection.tsx
+++ b/site/src/app/[locale]/cut/app/(home)/settings/profile/EditorSection.tsx
@@ -21,7 +21,6 @@ import {
THEME_CHOICES,
type ThemeChoice,
} from "@/lib/theme";
-import { useUpdateLocale } from "@/queries/accountProfile";
import { useAccountFlags, useSetAccountFlag } from "@/queries/featureFlags";
// Editor preferences: the language and theme, then the account flags that
@@ -69,7 +68,6 @@ export function EditorSection() {
// emails and its chat replies follow it.
function LanguageRow() {
const t = useTranslations("settings.editor");
- const updateLocale = useUpdateLocale();
return (
<div className="flex items-center justify-between gap-6">
@@ -77,7 +75,7 @@ function LanguageRow() {
<span className="block text-sm font-medium">{t("language")}</span>
<span className="mt-0.5 block text-sm text-muted-foreground">{t("languageHint")}</span>
</span>
- <LanguagePicker placement="settings" save={(locale) => updateLocale.mutateAsync(locale)} />
+ <LanguagePicker placement="settings" />
</div>
);
}
diff --git a/site/src/clients/chatgpt/server/embed.ts b/site/src/clients/chatgpt/server/embed.ts
index 2380cd8b..d9ce0184 100644
--- a/site/src/clients/chatgpt/server/embed.ts
+++ b/site/src/clients/chatgpt/server/embed.ts
@@ -7,7 +7,8 @@ import {
OAuthRateLimitError,
} from "@/clients/chatgpt/server/oauthRateLimit";
import { recordEditorSession, redeemEditorCode } from "@/clients/chatgpt/server/oauthTokens";
-import { escapeHtml, requestLocale } from "@/clients/chatgpt/server/locale";
+import { escapeHtml } from "@/clients/chatgpt/server/locale";
+import { requestLocale } from "@/i18n/requestLocale";
import type { Locale } from "@/i18n/locales";
import type { Messages } from "@/i18n/namespaces";
import { translatorFor } from "@/i18n/translator";
diff --git a/site/src/clients/chatgpt/server/locale.test.ts b/site/src/clients/chatgpt/server/locale.test.ts
index ea818f0b..91332dd3 100644
--- a/site/src/clients/chatgpt/server/locale.test.ts
+++ b/site/src/clients/chatgpt/server/locale.test.ts
@@ -1,5 +1,7 @@
import { expect, test } from "bun:test";
-import { escapeHtml, mcpLocale, requestLocale } from "./locale";
+import { requestLocale } from "@/i18n/requestLocale";
+
+import { escapeHtml, mcpLocale } from "./locale";
const page = (headers: Record<string, string>) => new Request("https://donkeycut.com/api/chatgpt/embed", { headers });
const rpc = (body: unknown) =>
diff --git a/site/src/clients/chatgpt/server/locale.ts b/site/src/clients/chatgpt/server/locale.ts
index 7170081b..7073d839 100644
--- a/site/src/clients/chatgpt/server/locale.ts
+++ b/site/src/clients/chatgpt/server/locale.ts
@@ -1,4 +1,4 @@
-import { isLocale, LOCALE_COOKIE, type Locale } from "@/i18n/locales";
+import { isLocale, type Locale } from "@/i18n/locales";
import { negotiateLocale } from "@/i18n/negotiate";
import { prisma } from "@/lib/prisma";
@@ -6,21 +6,6 @@ import { prisma } from "@/lib/prisma";
// use the second key.
const META_LOCALE_KEYS = ["openai/locale", "webplus/i18n"] as const;
-/** The language of a page this adapter draws: the language the browser chose
- * on donkeycut.com, else its Accept-Language. */
-export function requestLocale(request: Request): Locale {
- const saved = request.headers
- .get("cookie")
- ?.split(";")
- .map((part) => part.trim())
- .find((part) => part.startsWith(`${LOCALE_COOKIE}=`))
- ?.slice(LOCALE_COOKIE.length + 1);
- if (isLocale(saved)) {
- return saved;
- }
- return negotiateLocale(request.headers.get("accept-language"));
-}
-
/**
* The language of the status lines ChatGPT shows under a tool call. ChatGPT
* sends its locale on initialize and tool calls; a tools/list request, which
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.ts b/site/src/clients/chatgpt/server/oauthRoutes.ts
index 4090c4ad..6c4127bf 100644
--- a/site/src/clients/chatgpt/server/oauthRoutes.ts
+++ b/site/src/clients/chatgpt/server/oauthRoutes.ts
@@ -34,7 +34,8 @@ import {
} from "@/clients/chatgpt/server/oauthRateLimit";
import { identitySigner, openIdMetadata } from "@/clients/chatgpt/server/oidc";
import { signInReturnCookie } from "@/lib/signInReturn";
-import { escapeHtml, requestLocale } from "@/clients/chatgpt/server/locale";
+import { escapeHtml } from "@/clients/chatgpt/server/locale";
+import { requestLocale } from "@/i18n/requestLocale";
import type { Locale } from "@/i18n/locales";
import { translatorFor } from "@/i18n/translator";
diff --git a/site/src/components/LanguagePicker.tsx b/site/src/components/LanguagePicker.tsx
index 1432e6e1..a43e8cd6 100644
--- a/site/src/components/LanguagePicker.tsx
+++ b/site/src/components/LanguagePicker.tsx
@@ -6,14 +6,16 @@ import { useState } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { switchLocale } from "@/i18n/localeCookie";
+import { ApiError } from "@/queries/apiClient";
+import { useUpdateLocale } from "@/queries/accountProfile";
import { LOCALE_NAMES, LOCALES, isLocale, type Locale } from "@/i18n/locales";
-// Where the picker sits decides how its trigger looks: the marketing footer's
-// bold bordered style, or the settings rows' compact one.
+// Where the picker sits decides how its trigger sizes: fit to the label in the
+// marketing footer, a fixed width in the settings rows.
type Placement = "footer" | "settings";
const TRIGGER_CLASS: Record<Placement, string> = {
- footer: "h-9 gap-2 rounded-lg border-2 border-foreground bg-card text-[15px] font-semibold text-foreground",
+ footer: "gap-2",
settings: "w-44",
};
@@ -50,47 +52,64 @@ function LanguageLabel({ locale }: { locale: Locale }) {
);
}
+// The account answers 401 to a visitor who is not signed in; their choice
+// lives in this browser alone.
+const UNAUTHORIZED = 401;
+
+// Why a pick did not take, worded under `common`.
+type PickFailure = "languageSaveFailed" | "languageBlocked";
+
/**
* The language menu. Each language is named in itself; choosing one saves it
- * (the account's copy too, through `save`, when someone is signed in) and
- * reloads the page in it.
+ * to the account when someone is signed in, so the editor does not switch it
+ * back, then reloads the page in it.
*/
-export function LanguagePicker({
- placement,
- save,
-}: {
- placement: Placement;
- save?: (locale: Locale) => Promise<unknown>;
-}) {
+export function LanguagePicker({ placement }: { placement: Placement }) {
const t = useTranslations("common");
const locale = useLocale();
+ const updateLocale = useUpdateLocale();
const [busy, setBusy] = useState(false);
+ const [failure, setFailure] = useState<PickFailure | null>(null);
- // Save first, so the reload already reads the account's new choice.
+ // Save first, so the reload already reads the account's new choice. A save
+ // that fails leaves the page as it is: switching anyway would be undone by
+ // the account's old language on the next editor load.
const pick = async (value: unknown) => {
if (!isLocale(value) || value === locale) {
return;
}
setBusy(true);
+ setFailure(null);
try {
- await save?.(value);
- } finally {
- switchLocale(value);
+ await updateLocale.mutateAsync(value);
+ } catch (error) {
+ if (!(error instanceof ApiError && error.status === UNAUTHORIZED)) {
+ setFailure("languageSaveFailed");
+ setBusy(false);
+ return;
+ }
+ }
+ if (!switchLocale(value)) {
+ setFailure("languageBlocked");
+ setBusy(false);
}
};
return (
- <Select value={locale} onValueChange={(value) => void pick(value)} disabled={busy}>
- <SelectTrigger aria-label={t("language")} className={TRIGGER_CLASS[placement]}>
- <SelectValue />
- </SelectTrigger>
- <SelectContent {...MENU_PROPS[placement]}>
- {LOCALES.map((choice) => (
- <SelectItem key={choice} value={choice} lang={choice}>
- <LanguageLabel locale={choice} />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <div>
+ <Select value={locale} onValueChange={(value) => void pick(value)} disabled={busy}>
+ <SelectTrigger aria-label={t("language")} className={TRIGGER_CLASS[placement]}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent {...MENU_PROPS[placement]}>
+ {LOCALES.map((choice) => (
+ <SelectItem key={choice} value={choice} lang={choice}>
+ <LanguageLabel locale={choice} />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {failure ? <p className="mt-2 text-sm text-destructive">{t(failure)}</p> : null}
+ </div>
);
}
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index f24c33c3..e4e45df7 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -1639,7 +1639,9 @@ function ChatSession({
void (async () => {
await Promise.all([flushThreadSaves(), flushCloudThreadSaves(), flushEditorSave(projectId)]);
await updateLocale.mutateAsync(next);
- switchLocale(next);
+ if (!switchLocale(next)) {
+ throw new UserError("language_cookie_blocked", "This browser isn't saving cookies, so the language can't change.");
+ }
})().catch((error: unknown) => setSendError(error));
}, [busy, projectId, updateLocale]);
useEffect(() => {
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 2c0ca0ea..0b501a2d 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -1176,7 +1176,7 @@ export function Editor({
e.preventDefault();
s.toggleGuidesShown();
} else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey && !e.altKey) {
- s.addOverlay({ text: t("defaultText") });
+ s.addOverlay();
} else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {
e.preventDefault();
// While playing, arrows skip in 1s jumps and playback rolls on (seek
diff --git a/site/src/cut/components/LocaleSync.tsx b/site/src/cut/components/LocaleSync.tsx
index 0ea0b622..0d04fa56 100644
--- a/site/src/cut/components/LocaleSync.tsx
+++ b/site/src/cut/components/LocaleSync.tsx
@@ -4,6 +4,7 @@ import { useLocale } from "next-intl";
import { useEffect, useRef } from "react";
import { bindCreatorLocale } from "@/cut/lib/defaultNames";
+import { editorHost } from "@/cut/lib/environment";
import { switchLocale } from "@/i18n/localeCookie";
import { useAccountProfile, useUpdateLocale } from "@/queries/accountProfile";
@@ -11,12 +12,15 @@ import { useAccountProfile, useUpdateLocale } from "@/queries/accountProfile";
// cookie decides what the proxy serves, so once the profile loads, an account
// language that differs from the page's switches the page to it. An account
// with no language yet takes this browser's, which is what its emails and
-// headless chat turns are written in from then on.
+// headless chat turns are written in from then on. Inside ChatGPT the page
+// speaks ChatGPT's language and leaves the account alone. A switch is tried
+// once per load: a browser that drops the cookie would reload forever.
export function LocaleSync() {
const locale = useLocale();
const profile = useAccountProfile();
const updateLocale = useUpdateLocale();
const recorded = useRef(false);
+ const switched = useRef(false);
const saved = profile.data?.locale;
// What the editor creates (an untitled project, a new title) is named in
@@ -26,11 +30,14 @@ export function LocaleSync() {
}, [locale]);
useEffect(() => {
- if (!profile.data) {
+ if (!profile.data || editorHost() === "chatgpt") {
return;
}
if (saved && saved !== locale) {
- switchLocale(saved);
+ if (!switched.current) {
+ switched.current = true;
+ switchLocale(saved);
+ }
return;
}
if (!saved && !recorded.current) {
diff --git a/site/src/i18n/localeCookie.ts b/site/src/i18n/localeCookie.ts
index 17472344..7e48b988 100644
--- a/site/src/i18n/localeCookie.ts
+++ b/site/src/i18n/localeCookie.ts
@@ -12,9 +12,15 @@ export function readLocaleCookie(): Locale | null {
/**
* Switches this browser to a locale. Every URL serves every language, and the
* router caches pages by URL, so the page reloads to draw in the new one.
+ * A browser that refuses the cookie (blocked cookies, a cross-site frame)
+ * would serve the old language again, so it stays put and this answers false.
*/
-export function switchLocale(locale: Locale) {
+export function switchLocale(locale: Locale): boolean {
const secure = location.protocol === "https:" ? "; Secure" : "";
document.cookie = `${LOCALE_COOKIE}=${locale}; Path=/; Max-Age=${LOCALE_COOKIE_MAX_AGE_S}; SameSite=Lax${secure}`;
+ if (readLocaleCookie() !== locale) {
+ return false;
+ }
location.reload();
+ return true;
}
diff --git a/site/src/i18n/messages/en/common.json b/site/src/i18n/messages/en/common.json
index a08eb4b4..04d49112 100644
--- a/site/src/i18n/messages/en/common.json
+++ b/site/src/i18n/messages/en/common.json
@@ -41,5 +41,7 @@
"no_payment_method": "Buy credits once to save a card, then turn on auto-reload.",
"unsupported_image_type": "Unsupported image type.",
"image_too_large": "Image too large."
- }
+ },
+ "languageSaveFailed": "Couldn't save your language. Try again.",
+ "languageBlocked": "This browser isn't saving cookies, so the language can't change."
}
diff --git a/site/src/i18n/messages/en/editor.json b/site/src/i18n/messages/en/editor.json
index 684409c3..bb765e48 100644
--- a/site/src/i18n/messages/en/editor.json
+++ b/site/src/i18n/messages/en/editor.json
@@ -357,8 +357,7 @@
"needsApp": "This is a local project — it lives on this Mac. Open the Donkey app and it opens here.",
"shareGone": "This share is no longer available.",
"conflictReloaded": "Reloaded a newer version saved elsewhere.",
- "dismiss": "Dismiss",
- "defaultText": "Your text"
+ "dismiss": "Dismiss"
},
"preview": {
"showingOriginal": "Showing the original — click to see the cutout",
diff --git a/site/src/i18n/messages/en/errors.json b/site/src/i18n/messages/en/errors.json
index fbfad7da..7bddd204 100644
--- a/site/src/i18n/messages/en/errors.json
+++ b/site/src/i18n/messages/en/errors.json
@@ -140,6 +140,7 @@
"label_delete_failed": "Could not delete the label.",
"label_name_required": "Label name required.",
"label_save_failed": "Could not save the label.",
+ "language_cookie_blocked": "This browser isn't saving cookies, so the language can't change.",
"library_add_failed": "Could not add from library.",
"library_asset_not_found": "Library asset not found.",
"library_asset_update_failed": "Could not update the library asset.",
diff --git a/site/src/i18n/requestLocale.ts b/site/src/i18n/requestLocale.ts
index 26b914c2..3db3f306 100644
--- a/site/src/i18n/requestLocale.ts
+++ b/site/src/i18n/requestLocale.ts
@@ -1,10 +1,21 @@
-import type { NextRequest } from "next/server";
+import { isLocale, LOCALE_COOKIE, type Locale } from "@/i18n/locales";
+import { negotiateLocale } from "@/i18n/negotiate";
-import { DEFAULT_LOCALE, isLocale, LOCALE_COOKIE, type Locale } from "@/i18n/locales";
-
-/** The reader's locale in a route handler, which has no root params: the
- * cookie the proxy routes on, else English. */
-export function requestLocale(request: NextRequest): Locale {
- const picked = request.cookies.get(LOCALE_COOKIE)?.value;
- return isLocale(picked) ? picked : DEFAULT_LOCALE;
+/**
+ * The language a request is served in, the same everywhere a request lands:
+ * the language a picker saved in the cookie, else the closest match to the
+ * browser's Accept-Language. The proxy routes pages on it, so a route handler
+ * that reads it answers in the language the page was drawn in.
+ */
+export function requestLocale(request: Request): Locale {
+ const picked = request.headers
+ .get("cookie")
+ ?.split(";")
+ .map((part) => part.trim())
+ .find((part) => part.startsWith(`${LOCALE_COOKIE}=`))
+ ?.slice(LOCALE_COOKIE.length + 1);
+ if (isLocale(picked)) {
+ return picked;
+ }
+ return negotiateLocale(request.headers.get("accept-language"));
}
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index 045749c6..aef1f40c 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -2,8 +2,7 @@ import { NextResponse, type NextRequest } from "next/server";
import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";
import { DONKEYCUT_CANONICAL, isDonkeycutHost } from "@/cut/lib/hosts";
-import { LOCALE_COOKIE, isLocale, type Locale } from "@/i18n/locales";
-import { negotiateLocale } from "@/i18n/negotiate";
+import { requestLocale } from "@/i18n/requestLocale";
import { BEACON_PATH, META_COOKIE_MAX_AGE_S, metaCookies } from "@/lib/meta/identity";
// Cut (the video editor, publicly "Donkey Cut") lives under /cut in this single
@@ -95,15 +94,9 @@ function withMetaCookies(req: NextRequest, res: NextResponse): NextResponse {
// of the mapping below prefixes the internal path with the visitor's locale:
// the language they picked (the cookie the pickers write), or else the
// closest match to their browser's Accept-Language, worked out per request.
-function visitorLocale(req: NextRequest): Locale {
- const picked = req.cookies.get(LOCALE_COOKIE)?.value;
- if (isLocale(picked)) return picked;
- return negotiateLocale(req.headers.get("accept-language"));
-}
-
function localized(req: NextRequest, internalPath: string): NextResponse {
const url = new URL(req.url);
- url.pathname = `/${visitorLocale(req)}${internalPath === "/" ? "" : internalPath}`;
+ url.pathname = `/${requestLocale(req)}${internalPath === "/" ? "" : internalPath}`;
return withMetaCookies(req, NextResponse.rewrite(url));
}