Skip to content

Open source CapCut alternative.

TypeScript

feat(site): translate the Cut editor [rebuild]

David Le0247f16ce6d0
diff --git a/site/scripts/eval-cut-headless.ts b/site/scripts/eval-cut-headless.ts
index 05a003e1..388487f8 100644
--- a/site/scripts/eval-cut-headless.ts
+++ b/site/scripts/eval-cut-headless.ts
@@ -16,6 +16,7 @@
import type { UIMessage } from "ai";
import { openCloudProject, pushCloudProject } from "../src/cut/lib/headless/docSession";
import { dropPiSession, streamCutChat } from "../src/cut/lib/pi/cutAgent";
+import { DEFAULT_LOCALE } from "../src/i18n/locales";
import { headlessDeps, type HeadlessSession } from "../src/cut/lib/pi/serverDeps";
import { geminiModelRoles } from "../src/lib/inference/gemini-models";
@@ -81,6 +82,7 @@ try {
threadId,
model: geminiModelRoles.chat,
messages,
+ locale: DEFAULT_LOCALE,
deps,
}).getReader();
try {
diff --git a/site/scripts/eval-cut-queue.ts b/site/scripts/eval-cut-queue.ts
index 4b83bb16..ec86a2bd 100644
--- a/site/scripts/eval-cut-queue.ts
+++ b/site/scripts/eval-cut-queue.ts
@@ -38,6 +38,7 @@ import {
import type { QueueVerdict } from "../src/cut/lib/queueTriage";
import { AUDIO_STATE, EDITOR_STATE, SAFE_TOOLS, SCENE_PLANNED, serveSafeTool, userTurn } from "./lib/cut-eval/fixtures";
import { queueCases, type QueueCase } from "./lib/cut-eval/queueCases";
+import { DEFAULT_LOCALE } from "../src/i18n/locales";
const args = process.argv.slice(2);
const argValue = (flag: string) => {
@@ -125,7 +126,7 @@ async function runLiveFold(): Promise<string[]> {
};
const messages = [userTurn("Add a title that says Welcome at the start")] as unknown as UIMessage[];
let reply = "";
- const stream = streamCutChat({ threadId, model: geminiModelRoleNames.chat, messages, deps: live });
+ const stream = streamCutChat({ threadId, model: geminiModelRoleNames.chat, messages, locale: DEFAULT_LOCALE, deps: live });
const reader = stream.getReader();
for (;;) {
const { done, value } = await reader.read();
@@ -194,7 +195,7 @@ async function runLiveQueueBack(): Promise<string[]> {
userTurn("turn my narration audio into a smooth 2D cartoon", { state: AUDIO_STATE }),
] as unknown as UIMessage[];
let reply = "";
- const stream = streamCutChat({ threadId, model: geminiModelRoleNames.chat, messages, deps: live });
+ const stream = streamCutChat({ threadId, model: geminiModelRoleNames.chat, messages, locale: DEFAULT_LOCALE, deps: live });
const reader = stream.getReader();
for (;;) {
const { done, value } = await reader.read();
diff --git a/site/scripts/lib/chatgpt-session-fixture.tsx b/site/scripts/lib/chatgpt-session-fixture.tsx
index 35b242c4..3b57f1dd 100644
--- a/site/scripts/lib/chatgpt-session-fixture.tsx
+++ b/site/scripts/lib/chatgpt-session-fixture.tsx
@@ -1,4 +1,8 @@
import { createRoot } from "react-dom/client";
+import { IntlProvider } from "use-intl";
+import editor from "../../src/i18n/messages/en/editor.json";
import { EmbeddedSignInFallback } from "../../src/cut/components/EmbeddedSignInFallback";
-createRoot(document.getElementById("session")!).render(<EmbeddedSignInFallback />);
+// The editor's provider is the page's; the fixture hands the component the
+// English editor catalog the same way.
+createRoot(document.getElementById("session")!).render(<IntlProvider locale="en" messages={{ editor }}><EmbeddedSignInFallback /></IntlProvider>);
diff --git a/site/scripts/lib/cut-eval/harness.ts b/site/scripts/lib/cut-eval/harness.ts
index d5ebadc6..42414155 100644
--- a/site/scripts/lib/cut-eval/harness.ts
+++ b/site/scripts/lib/cut-eval/harness.ts
@@ -14,6 +14,7 @@ import type { UIMessage } from "ai";
import { AI_SKILLS } from "../../../src/cut/server/ai/catalog";
import { geminiModelRoleNames, resolveGeminiModel } from "../../../src/lib/inference/gemini-models";
import { streamCutChat, dropPiSession, type CutAgentDeps } from "../../../src/cut/lib/pi/cutAgent";
+import { DEFAULT_LOCALE } from "../../../src/i18n/locales";
import type { TurnIntent } from "../../../src/cut/lib/turnJudge";
import { EDITOR_STATE, SAFE_TOOLS, serveSafeTool } from "./fixtures";
import { judgeReply, replyShapeNotes } from "./graders";
@@ -214,6 +215,7 @@ export async function runCase(c: EvalCase, cfg: RunConfig): Promise<CaseResult>
threadId,
model: cfg.complexModel,
messages: messages as unknown as UIMessage[],
+ locale: DEFAULT_LOCALE,
deps,
});
try {
diff --git a/site/src/clients/chatgpt/server/catalog.test.ts b/site/src/clients/chatgpt/server/catalog.test.ts
index ff5c06da..9a3f69a6 100644
--- a/site/src/clients/chatgpt/server/catalog.test.ts
+++ b/site/src/clients/chatgpt/server/catalog.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test";
import { AI_TOOLS, PROJECT_TOOLS } from "@/cut/server/ai/catalog";
-import { COMMANDS, READ_COMMANDS, SKILL_INDEX, readSkill, unknownCommandNames } from "./catalog";
+import { COMMAND_NAMES, COMMANDS, READ_COMMANDS, SKILL_INDEX, readSkill, unknownCommandNames } from "./catalog";
test("first-class history tools can queue their editor commands", () => {
expect(COMMANDS.some((tool) => tool.name === "undo" || tool.name === "redo")).toBe(false);
@@ -9,6 +9,11 @@ test("first-class history tools can queue their editor commands", () => {
expect(READ_COMMANDS.has("redo")).toBe(false);
});
+test("the editor's language setting stays out of ChatGPT's commands", () => {
+ expect(COMMAND_NAMES).not.toContain("set_interface_language");
+ expect(unknownCommandNames(["set_interface_language"])).toEqual(["set_interface_language"]);
+});
+
test("a command that keeps a picture box on the source saves the document", () => {
expect(READ_COMMANDS.has("detect_cuts")).toBe(false);
});
diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.ts
index 74f11e80..24be7d2f 100644
--- a/site/src/clients/chatgpt/server/catalog.ts
+++ b/site/src/clients/chatgpt/server/catalog.ts
@@ -19,6 +19,9 @@ const HIDDEN = new Set([
// Page-local: the editor's clipboard and playback.
"copy_selection",
"paste_selection",
+ // The card speaks ChatGPT's language, so the editor's own language setting
+ // stays with the editor.
+ "set_interface_language",
// Long generations settle after the batch ends, so nothing would place them.
"generate_video",
"generate_character_video",
diff --git a/site/src/clients/chatgpt/server/embed.ts b/site/src/clients/chatgpt/server/embed.ts
index 837f8fb5..2380cd8b 100644
--- a/site/src/clients/chatgpt/server/embed.ts
+++ b/site/src/clients/chatgpt/server/embed.ts
@@ -7,6 +7,10 @@ import {
OAuthRateLimitError,
} from "@/clients/chatgpt/server/oauthRateLimit";
import { recordEditorSession, redeemEditorCode } from "@/clients/chatgpt/server/oauthTokens";
+import { escapeHtml, requestLocale } from "@/clients/chatgpt/server/locale";
+import type { Locale } from "@/i18n/locales";
+import type { Messages } from "@/i18n/namespaces";
+import { translatorFor } from "@/i18n/translator";
const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
@@ -15,8 +19,8 @@ const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
* skeleton over the frame until the frame says it has something to show, so
* every answer here is either the editor or a page that says so.
*/
-function refusal(message: string, status: number, retryAfter?: string) {
- const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Donkey Cut</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box;background:#fff;color:#737373;font:14px/1.5 system-ui,sans-serif;text-align:center"><p>${message}</p><script>parent.postMessage({ type: "donkeycut:ready" }, "*")</script></body></html>`;
+function refusal(locale: Locale, message: string, status: number, retryAfter?: string) {
+ const page = `<!doctype html><html lang="${locale}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Donkey Cut</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box;background:#fff;color:#737373;font:14px/1.5 system-ui,sans-serif;text-align:center"><p>${escapeHtml(message)}</p><script>parent.postMessage({ type: "donkeycut:ready" }, "*")</script></body></html>`;
return new Response(page, {
status,
headers: {
@@ -27,7 +31,8 @@ function refusal(message: string, status: number, retryAfter?: string) {
});
}
-const TOO_MANY = "Too many requests. Try again in a minute.";
+type RefusalKey = keyof Messages["chatgpt"]["embed"];
+type Refuse = (key: RefusalKey, status: number, retryAfter?: string) => Response;
/**
* GET /api/chatgpt/embed?code=…&project=…: the card's frame redeems its one-use
@@ -36,29 +41,34 @@ const TOO_MANY = "Too many requests. Try again in a minute.";
* own sign-in never crosses into the frame, and the frame's never leaves it.
*/
export async function embedEndpoint(request: Request) {
+ // Every refusal reads in the frame's language.
+ const locale = requestLocale(request);
+ const t = await translatorFor(locale, "chatgpt");
+ const refuse: Refuse = (key, status, retryAfter) => refusal(locale, t(`embed.${key}`), status, retryAfter);
+
try {
- return await redeem(request);
+ return await redeem(request, refuse);
} catch (error) {
console.error("[chatgpt] embed redeem failed", error);
- return refusal("Donkey Cut could not open the editor. Open the project again from ChatGPT.", 500);
+ return refuse("failed", 500);
}
}
-async function redeem(request: Request) {
+async function redeem(request: Request, refuse: Refuse) {
const config = await chatgptConfig();
- if (!config.enabled) return refusal("ChatGPT connection is not enabled.", 503);
+ if (!config.enabled) return refuse("disabled", 503);
const limited = limitOAuthSource(request, "embed", config.oauthRequestsPerIpMinute);
- if (limited) return refusal(TOO_MANY, 429, limited.headers.get("Retry-After") ?? undefined);
+ if (limited) return refuse("tooMany", 429, limited.headers.get("Retry-After") ?? undefined);
const params = new URL(request.url).searchParams;
const project = params.get("project") ?? "";
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) return refusal("Bad request.", 400);
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) return refuse("badRequest", 400);
const redeemed = await redeemEditorCode(params.get("code") ?? "", config);
- if (!redeemed) return refusal("This editor link has expired. Open the project again from ChatGPT.", 403);
+ if (!redeemed) return refuse("expired", 403);
try {
enforceOAuthUserLimit(redeemed.userId, "embed", config.requestsPerMinute);
} catch (error) {
- if (error instanceof OAuthRateLimitError) return refusal(TOO_MANY, 429, String(error.retryAfterSeconds));
+ if (error instanceof OAuthRateLimitError) return refuse("tooMany", 429, String(error.retryAfterSeconds));
throw error;
}
diff --git a/site/src/clients/chatgpt/server/locale.test.ts b/site/src/clients/chatgpt/server/locale.test.ts
new file mode 100644
index 00000000..ea818f0b
--- /dev/null
+++ b/site/src/clients/chatgpt/server/locale.test.ts
@@ -0,0 +1,27 @@
+import { expect, test } from "bun:test";
+import { escapeHtml, mcpLocale, requestLocale } from "./locale";
+
+const page = (headers: Record<string, string>) => new Request("https://donkeycut.com/api/chatgpt/embed", { headers });
+const rpc = (body: unknown) =>
+ new Request("https://donkeycut.com/api/chatgpt/mcp", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+test("a page reads the saved language first, then Accept-Language", () => {
+ expect(requestLocale(page({ cookie: "a=1; NEXT_LOCALE=ko", "accept-language": "fr" }))).toBe("ko");
+ expect(requestLocale(page({ cookie: "NEXT_LOCALE=xx", "accept-language": "pt-PT,pt;q=0.9" }))).toBe("pt-BR");
+ expect(requestLocale(page({}))).toBe("en");
+});
+
+test("an MCP request speaks the locale ChatGPT names in _meta", async () => {
+ const call = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "undo", _meta: { "openai/locale": "ja-JP" } } };
+ expect(await mcpLocale(rpc(call), "owner")).toBe("ja");
+ const older = { jsonrpc: "2.0", id: 1, method: "initialize", params: { _meta: { "webplus/i18n": "de-AT" } } };
+ expect(await mcpLocale(rpc([older]), "owner")).toBe("de");
+});
+
+test("page text is escaped before it reaches the HTML", () => {
+ expect(escapeHtml(`<b class="x">'&'</b>`)).toBe("&lt;b class=&quot;x&quot;&gt;&#39;&amp;&#39;&lt;/b&gt;");
+});
diff --git a/site/src/clients/chatgpt/server/locale.ts b/site/src/clients/chatgpt/server/locale.ts
new file mode 100644
index 00000000..7170081b
--- /dev/null
+++ b/site/src/clients/chatgpt/server/locale.ts
@@ -0,0 +1,78 @@
+import { isLocale, LOCALE_COOKIE, type Locale } from "@/i18n/locales";
+import { negotiateLocale } from "@/i18n/negotiate";
+import { prisma } from "@/lib/prisma";
+
+// ChatGPT names the person's language in a request's _meta; older clients
+// 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
+ * carries the descriptors, may come without it, so the account's saved
+ * language answers there, then the request's Accept-Language.
+ */
+export async function mcpLocale(request: Request, userId: string): Promise<Locale> {
+ const tag = await metaLocale(request);
+ if (tag) {
+ return negotiateLocale(tag);
+ }
+
+ const user = await prisma.user.findUnique({ select: { locale: true }, where: { id: userId } });
+ if (isLocale(user?.locale)) {
+ return user.locale;
+ }
+ return negotiateLocale(request.headers.get("accept-language"));
+}
+
+/** The first locale tag in a JSON-RPC message's (or batch's) params._meta. */
+async function metaLocale(request: Request): Promise<string | null> {
+ if (!request.headers.get("content-type")?.includes("application/json")) {
+ return null;
+ }
+
+ let body: unknown;
+ try {
+ body = await request.clone().json();
+ } catch {
+ return null;
+ }
+ for (const message of Array.isArray(body) ? body : [body]) {
+ const meta = (message as { params?: { _meta?: Record<string, unknown> } } | null)?.params?._meta;
+ for (const key of META_LOCALE_KEYS) {
+ const tag = meta?.[key];
+ if (typeof tag === "string" && tag) {
+ return tag;
+ }
+ }
+ }
+ return null;
+}
+
+/** Text a page interpolates into its HTML. */
+export function escapeHtml(text: string): string {
+ return text.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character]!);
+}
+
+const HTML_ESCAPES: Record<string, string> = {
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ "'": "&#39;",
+};
diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.ts
index 24777625..71d74c4c 100644
--- a/site/src/clients/chatgpt/server/mcp.ts
+++ b/site/src/clients/chatgpt/server/mcp.ts
@@ -33,6 +33,13 @@ import {
} from "@/clients/chatgpt/server/projects";
import { widgetHtml } from "@/clients/chatgpt/widget.generated";
import { searchLinksOf, splitToolDisplay } from "@/cut/lib/toolDisplay";
+import { mcpLocale } from "@/clients/chatgpt/server/locale";
+import { DEFAULT_LOCALE } from "@/i18n/locales";
+import { prisma } from "@/lib/prisma";
+import type { Messages } from "@/i18n/namespaces";
+import { translatorFor } from "@/i18n/translator";
+import { createTranslator } from "use-intl/core";
+import englishMessages from "@/i18n/messages/en/chatgpt.json";
const idSchema = z.string().min(1).max(128);
const readOnlyAnnotations = {
@@ -111,10 +118,17 @@ function liftDisplay(view: ProjectView): void {
}
type Identity = { userId: string; scopes: string[]; grantId: string };
+type ChatgptTranslator = Awaited<ReturnType<typeof translatorFor<"chatgpt">>>;
+type StatusTool = keyof Messages["chatgpt"]["status"];
+
+// The English source, for servers built without a request (tests, evals).
+const ENGLISH = createTranslator({ locale: "en", messages: { chatgpt: englishMessages }, namespace: "chatgpt" });
+
export function createChatgptServer(
identity: Identity,
config: ChatgptConfig,
projects = projectTools(identity, config),
+ t: ChatgptTranslator = ENGLISH,
) {
const server = new McpServer(
{ name: "donkey-cut", title: "Donkey Cut", version: "1.1.0" },
@@ -133,9 +147,10 @@ export function createChatgptServer(
{ type: "oauth2", scopes: ["projects:read", "projects:write"] },
],
};
- const status = (invoking: string, invoked: string) => ({
- "openai/toolInvocation/invoking": invoking,
- "openai/toolInvocation/invoked": invoked,
+ // The status lines ChatGPT shows the person under a call, in their language.
+ const status = (tool: StatusTool) => ({
+ "openai/toolInvocation/invoking": t(`status.${tool}.invoking`),
+ "openai/toolInvocation/invoked": t(`status.${tool}.invoked`),
});
const scopeChallenge = (scope: string, text: string) => ({
isError: true,
@@ -252,7 +267,7 @@ export function createChatgptServer(
inputSchema: z.object({ name: z.string().min(1).max(120), aspect: z.string().max(16).optional() }),
outputSchema: viewSchema,
annotations: editAnnotations,
- _meta: { ...editMetadata, ...status("Creating the project", "Project created") },
+ _meta: { ...editMetadata, ...status("createProject") },
},
({ name, aspect }) => editing(() => runTool(() => projects.create(name, aspect))),
);
@@ -271,7 +286,7 @@ export function createChatgptServer(
}),
outputSchema: viewSchema,
annotations: { ...editAnnotations, openWorldHint: true },
- _meta: { ...editMetadata, "openai/fileParams": ["files"], ...status("Importing footage", "Footage imported") },
+ _meta: { ...editMetadata, "openai/fileParams": ["files"], ...status("importMedia") },
},
({ projectId, files, urls, audio_only }) =>
editing(() =>
@@ -298,7 +313,7 @@ export function createChatgptServer(
}),
outputSchema: viewSchema,
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Reading the project", "Project read") },
+ _meta: { ...readMetadata, ...status("inspectProject") },
},
({ projectId, commands }) => runTool(() => projects.inspect(projectId, commands?.map((c) => ({ name: c.name, input: c.input ?? {} })))),
);
@@ -312,7 +327,7 @@ export function createChatgptServer(
inputSchema: z.object({}),
outputSchema: z.object({ commands: z.array(z.object({ name: z.string(), summary: z.string(), reads: z.literal(true).optional() })) }),
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Listing commands", "Commands listed") },
+ _meta: { ...readMetadata, ...status("listCommands") },
},
() => {
const commands = commandIndex();
@@ -334,7 +349,7 @@ export function createChatgptServer(
unknown: z.array(z.string()),
}),
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Describing commands", "Commands described") },
+ _meta: { ...readMetadata, ...status("describeCommands") },
},
({ names }) => {
const { found, unknown } = describeCommands(names);
@@ -354,7 +369,7 @@ export function createChatgptServer(
inputSchema: z.object({}),
outputSchema: z.object({ skills: z.array(z.string()) }),
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Listing guides", "Guides listed") },
+ _meta: { ...readMetadata, ...status("listSkills") },
},
() => ({
content: [{ type: "text" as const, text: SKILL_INDEX.join("\n") }],
@@ -370,7 +385,7 @@ export function createChatgptServer(
inputSchema: z.object({ name: z.string().min(1).max(64) }),
outputSchema: z.object({ name: z.string(), guide: z.string() }),
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Reading the guide", "Guide read") },
+ _meta: { ...readMetadata, ...status("readSkill") },
},
({ name }) => {
const doc = readSkill(name);
@@ -392,7 +407,7 @@ export function createChatgptServer(
}),
outputSchema: viewSchema,
annotations: { ...editAnnotations, destructiveHint: true },
- _meta: { ...editMetadata, ...status("Editing the project", "Project edited") },
+ _meta: { ...editMetadata, ...status("editProject") },
},
({ projectId, commands, label }) =>
editing(() => runTool(() => projects.edit(projectId, commands.map((c) => ({ name: c.name, input: c.input ?? {} })), label))),
@@ -406,7 +421,7 @@ export function createChatgptServer(
inputSchema: z.object({ projectId: idSchema }),
outputSchema: viewSchema,
annotations: editAnnotations,
- _meta: { ...editMetadata, ...status("Undoing", "Undone") },
+ _meta: { ...editMetadata, ...status("undo") },
},
({ projectId }) => editing(() => runTool(() => projects.undo(projectId))),
);
@@ -419,7 +434,7 @@ export function createChatgptServer(
inputSchema: z.object({ projectId: idSchema }),
outputSchema: viewSchema,
annotations: editAnnotations,
- _meta: { ...editMetadata, ...status("Redoing", "Redone") },
+ _meta: { ...editMetadata, ...status("redo") },
},
({ projectId }) => editing(() => runTool(() => projects.redo(projectId))),
);
@@ -438,7 +453,7 @@ export function createChatgptServer(
}),
outputSchema: viewSchema,
annotations: editAnnotations,
- _meta: { ...editMetadata, ...status("Exporting the video", "Export started") },
+ _meta: { ...editMetadata, ...status("exportVideo") },
},
({ projectId, preset, loudness, stems }) =>
editing(() => runTool(() => projects.exportVideo(projectId, preset ?? "original", { loudness, stems }))),
@@ -452,7 +467,7 @@ export function createChatgptServer(
inputSchema: z.object({ jobId: idSchema }),
outputSchema: viewSchema,
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Checking the export", "Export checked") },
+ _meta: { ...readMetadata, ...status("exportStatus") },
},
({ jobId }) => runTool(() => projects.exportStatus(jobId)),
);
@@ -465,7 +480,7 @@ export function createChatgptServer(
inputSchema: z.object({ jobId: idSchema }),
outputSchema: viewSchema,
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Checking the job", "Job checked") },
+ _meta: { ...readMetadata, ...status("jobStatus") },
},
({ jobId }) => runTool(() => projects.jobStatus(jobId)),
);
@@ -478,7 +493,7 @@ export function createChatgptServer(
inputSchema: z.object({}),
outputSchema: viewSchema,
annotations: readOnlyAnnotations,
- _meta: { ...readMetadata, ...status("Reading the account", "Account read") },
+ _meta: { ...readMetadata, ...status("accountStatus") },
},
() => runTool(() => projects.account()),
);
@@ -517,7 +532,7 @@ function describeProjectView(view: ProjectView): string {
if (view.account) {
const { credits, storageBytes, storageQuotaBytes, plan } = view.account;
const storage = typeof storageQuotaBytes !== "number" ? `${mb(storageBytes)} MB used` : `${mb(storageBytes)} of ${mb(storageQuotaBytes)} MB used`;
- return `Plan: ${plan}. AI credit balance: ${formatCredits(credits)}. Cloud storage: ${storage}. Editing, previews and exports spend no credits.`;
+ return `Plan: ${plan}. AI credit balance: ${formatCredits(credits, DEFAULT_LOCALE)}. Cloud storage: ${storage}. Editing, previews and exports spend no credits.`;
}
if (view.view === "projects") {
if (!view.projects.length) {
@@ -610,7 +625,13 @@ export async function mcpEndpoint(request: Request) {
return rateLimitResponse(rateLimit.retryAfterSeconds);
}
- const handler = chatgptHttpHandler(identity, config);
+ const locale = await mcpLocale(request, identity.userId);
+ const handler = chatgptHttpHandler(
+ identity,
+ config,
+ projectTools(identity, config, prisma, locale),
+ await translatorFor(locale, "chatgpt"),
+ );
try {
const response = await handler.fetch(request);
// Materialize the body before closing the per-request handler.
@@ -636,9 +657,10 @@ export function chatgptHttpHandler(
identity: Identity,
config: ChatgptConfig,
projects?: ReturnType<typeof projectTools>,
+ t?: ChatgptTranslator,
) {
return createMcpHandler(
- () => createChatgptServer(identity, config, projects),
+ () => createChatgptServer(identity, config, projects, t),
{
onerror: (error) =>
console.warn("[chatgpt] mcp request rejected", error.message),
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.ts b/site/src/clients/chatgpt/server/oauthRoutes.ts
index 77cd158e..4090c4ad 100644
--- a/site/src/clients/chatgpt/server/oauthRoutes.ts
+++ b/site/src/clients/chatgpt/server/oauthRoutes.ts
@@ -34,6 +34,9 @@ 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 type { Locale } from "@/i18n/locales";
+import { translatorFor } from "@/i18n/translator";
const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
const CONSENT_COOKIE_NAME = "__Host-donkey-chatgpt-consent";
@@ -146,7 +149,7 @@ export async function authorize(request: Request) {
});
// Signed in now, so the remembered sign-in return has done its job.
- const page = consentPage(nonce, authorization, browserToken);
+ const page = await consentPage(requestLocale(request), nonce, authorization, browserToken);
page.headers.append("Set-Cookie", signInReturnCookie(null));
return page;
}
@@ -172,17 +175,17 @@ export const consent = withDonkeyAuth(async (request) => {
const { nonce, decision } = parsed.data;
const browserToken = consentBrowserToken(request.headers.get("cookie"));
- if (!browserToken) return expiredConsent();
+ if (!browserToken) return expiredConsent(request);
const challengeId = `chatgpt:${tokenHash(nonce)}`;
const challenge = await prisma.verification.findUnique({
where: { id: challengeId },
});
if (!challenge || challenge.expiresAt <= new Date()) {
- return expiredConsent();
+ return expiredConsent(request);
}
if (challenge.identifier !== `chatgpt-consent:${request.donkey.userId}`) {
- return expiredConsent();
+ return expiredConsent(request);
}
// Revalidate against current settings before issuing a code.
@@ -193,7 +196,7 @@ export const consent = withDonkeyAuth(async (request) => {
!parsedChallenge.success ||
!sameSecret(parsedChallenge.data.browserTokenHash, tokenHash(browserToken))
) {
- return expiredConsent();
+ return expiredConsent(request);
}
const { authorization } = parsedChallenge.data;
if (!authorizeInput(new URLSearchParams(authorization), config)) {
@@ -204,7 +207,7 @@ export const consent = withDonkeyAuth(async (request) => {
where: { id: challengeId, expiresAt: { gt: new Date() } },
});
if (!consumed.count) {
- return expiredConsent();
+ return expiredConsent(request);
}
const callbackUrl = new URL(authorization.redirect_uri);
@@ -353,9 +356,11 @@ function consentBrowserToken(header: string | null) {
return value && /^[A-Za-z0-9_-]{43}$/.test(value) ? value : null;
}
-function expiredConsent() {
+async function expiredConsent(request: Request) {
+ const locale = requestLocale(request);
+ const t = await translatorFor(locale, "chatgpt");
return new Response(
- `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Restart connection</title></head><body><h1>Start the connection again</h1><p>This connection page expired or your signed-in account changed. Return to OpenAI and start the connection again.</p></body></html>`,
+ `<!doctype html><html lang="${locale}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(t("consent.expiredTitle"))}</title></head><body><h1>${escapeHtml(t("consent.expiredHeading"))}</h1><p>${escapeHtml(t("consent.expiredBody"))}</p></body></html>`,
{
status: 400,
headers: {
@@ -368,30 +373,28 @@ function expiredConsent() {
);
}
-function consentPage(
+async function consentPage(
+ locale: Locale,
nonce: string,
authorization: Authorization,
browserToken: string,
) {
+ const t = await translatorFor(locale, "chatgpt");
const scopes = authorization.scope.split(" ");
- const access = scopes.includes("projects:write") ? "view and edit" : "view";
- const escapedNonce = nonce.replace(
- /[&<>"']/g,
- (character) =>
- ({
- "&": "&amp;",
- "<": "&lt;",
- ">": "&gt;",
- '"': "&quot;",
- "'": "&#39;",
- })[character]!,
- );
+
+ // One sentence for what the grant reaches: the projects, and the account
+ // identity when openid (and email) ride along.
+ const access = t("consent.access", {
+ access: scopes.includes("projects:write") ? "edit" : "view",
+ identity: !scopes.includes("openid") ? "none" : scopes.includes("email") ? "email" : "account",
+ });
+ const escapedNonce = escapeHtml(nonce);
const html = `<!doctype html>
-<html lang="en">
+<html lang="${locale}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
- <title>Connect to ChatGPT</title>
+ <title>${escapeHtml(t("consent.title"))}</title>
<style>
body { font: 17px system-ui; max-width: 460px; margin: 12vh auto; padding: 24px; color: #202020; background: #faf9f7; }
h1 { display: flex; align-items: center; gap: 14px; font-size: 34px; margin: 0 0 20px; }
@@ -404,11 +407,11 @@ function consentPage(
</head>
<body>
<h1><img src="/donkey-logo.svg" alt="">Donkey Cut</h1>
- <p>ChatGPT can ${access} your projects${scopes.includes("openid") ? ` and read your account information${scopes.includes("email") ? ", including your email address" : ""}` : ""}.</p>
+ <p>${escapeHtml(access)}</p>
<form method="post" action="${OAUTH_PATH}/authorize">
<input type="hidden" name="nonce" value="${escapedNonce}">
- <button name="decision" value="allow">Connect</button>
- <button name="decision" value="deny">Cancel</button>
+ <button name="decision" value="allow">${escapeHtml(t("consent.connect"))}</button>
+ <button name="decision" value="deny">${escapeHtml(t("consent.cancel"))}</button>
</form>
</body>
</html>`;
diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.ts
index c66d6961..9a164670 100644
--- a/site/src/clients/chatgpt/server/projects.ts
+++ b/site/src/clients/chatgpt/server/projects.ts
@@ -5,6 +5,8 @@ import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
import { cloudProjectsFull } from "@/lib/billing/project-limit-server";
import { isDonkeySuperUser } from "@/lib/super-user";
import { normalizeAspect, type ProjectDoc } from "@/cut/lib/types";
+import { defaultNames } from "@/cut/lib/defaultNames";
+import { DEFAULT_LOCALE, type Locale } from "@/i18n/locales";
import { ADOPT_COMMAND, type AdoptedAsset } from "@/cut/lib/commandBatch";
import { NO_CARD_OPEN, queueCommands, waitForJob, type CommandCall, type CommandJobResult, type JobRow } from "@/cut/server/cloud/commands";
import { needsWorker, queueDocExport, queueImportUrl } from "@/cut/server/cloud/jobs";
@@ -45,10 +47,13 @@ const jobStatus = (row: Pick<JobRow, "state">): "queued" | "running" | "done" |
const jobError = (row: Pick<JobRow, "state" | "error">) =>
row.state === "canceled" ? "The job was canceled." : row.error ?? undefined;
+// `locale` is the ChatGPT session's language, the one a project made with no
+// name is named in.
export function projectTools(
identity: Identity,
config: ChatgptConfig,
db = prisma,
+ locale: Locale = DEFAULT_LOCALE,
) {
const canRender = identity.scopes.includes("previews:render");
const canEdit = identity.scopes.includes("projects:write");
@@ -438,7 +443,7 @@ export function projectTools(
const now = Date.now();
const doc: ProjectDoc = {
version: 1,
- name: name.trim() || "Untitled",
+ name: name.trim() || (await defaultNames(locale)).untitled,
createdAt: now,
updatedAt: now,
assets: [],
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
index 0ed732ad..bfedb186 100644
--- a/site/src/clients/chatgpt/ui/PreviewApp.tsx
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -1,5 +1,6 @@
import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "use-intl";
import { useProjectApp } from "./useProjectApp";
import "./preview.css";
@@ -11,15 +12,17 @@ export function PreviewApp() {
// The frame whose editor has said it is on screen.
const [shown, setShown] = useState<string | null>(null);
const [downloadError, setDownloadError] = useState<string | null>(null);
+ const t = useTranslations("chatgpt.widget");
+ const problem = error && t(`problems.${error.key}`, { name: error.name ?? "" });
// The card is the whole surface, so a project that is gone has no projects
// home to fall back to: it says so in the editor's space and a new project
// opens there in its place.
if (view?.view === "missing") {
return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={busy}>
<div className="waiting">
- <p role="status">This project was deleted.</p>
- {error && <p role="alert">{error}</p>}
- <button className="primary" disabled={busy || !ready} onClick={createProject}>Create New Project</button>
+ <p role="status">{t("deleted")}</p>
+ {problem && <p role="alert">{problem}</p>}
+ <button className="primary" disabled={busy || !ready} onClick={createProject}>{t("createNewProject")}</button>
</div>
</main>;
}
@@ -32,42 +35,42 @@ export function PreviewApp() {
const loading = !editor || shown !== editor.url;
return <main className="editing" data-mode={fullscreen ? "fullscreen" : "inline"} aria-busy={loading}>
{editor && project && <EditorFrame key={editor.url} url={editor.url} name={project.name} inset={hostInset} fullscreen={fullscreen} onReady={() => setShown(editor.url)} onFullscreen={requestFullscreen} onOpen={openFromFrame} onSave={saveFromFrame} onDownloadError={setDownloadError} onReconnect={retryEditor} />}
- {downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>Dismiss</button></div>}
+ {downloadError && <div className="download-error"><p role="alert">{downloadError}</p><button onClick={() => setDownloadError(null)}>{t("dismiss")}</button></div>}
{error && project && !editor
? <div className="waiting">
- <p role="alert">{error}</p>
- <button disabled={busy || !ready} onClick={retryEditor}>Try again</button>
+ <p role="alert">{problem}</p>
+ <button disabled={busy || !ready} onClick={retryEditor}>{t("tryAgain")}</button>
</div>
: loading && <EditorSkeleton />}
</main>;
}
return <main aria-busy={busy}>
- <header><span className="brand">Donkey Cut</span><span>Cloud projects</span></header>
- {error && <p role="alert" className="error">{error}</p>}
- {!view && <p role="status">{ready ? "Choose a project to preview." : "Connecting to Donkey Cut…"}</p>}
- {!view && ready && <button onClick={() => void run("list_projects", {})}>Load projects</button>}
+ <header><span className="brand">Donkey Cut</span><span>{t("cloudProjects")}</span></header>
+ {problem && <p role="alert" className="error">{problem}</p>}
+ {!view && <p role="status">{ready ? t("chooseProject") : t("connecting")}</p>}
+ {!view && ready && <button onClick={() => void run("list_projects", {})}>{t("loadProjects")}</button>}
{view?.view === "projects" && <>
- <h1>Your projects</h1>
- {view.projects.length === 0 && <p>Save a project to the cloud in Donkey Cut to preview it here.</p>}
+ <h1>{t("yourProjects")}</h1>
+ {view.projects.length === 0 && <p>{t("noProjects")}</p>}
<div className="projects">{view.projects.map((p) => <button key={p.id} disabled={busy || !ready} onClick={() => void run("open_project", { projectId: p.id })}>
<span>{p.name}</span><span aria-hidden="true">→</span>
</button>)}</div>
- <nav>{view.nextCursor && <button disabled={busy} onClick={() => void run("list_projects", { cursor: view.nextCursor! })}>More projects</button>}
- <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>Refresh list</button></nav>
+ <nav>{view.nextCursor && <button disabled={busy} onClick={() => void run("list_projects", { cursor: view.nextCursor! })}>{t("moreProjects")}</button>}
+ <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>{t("refreshList")}</button></nav>
</>}
{project && <>
<h1>{project.name}</h1>
- {playback && <ArtifactVideo src={playback.url} format="file" active={visible} onError={playbackFailed} aria-label={`Preview of ${project.name}`} />}
- {rendering && <div role="status"><p>{preview.status === "queued" ? "Waiting to render…" : `Rendering preview… ${Math.round(preview.progress * 100)}%`}</p><progress max={1} value={preview.progress} /></div>}
- {!preview && <p>Render a preview to watch this project here.</p>}
- {preview?.status === "expired" && <p>This preview has expired. Render it again to watch.</p>}
+ {playback && <ArtifactVideo src={playback.url} format="file" active={visible} onError={playbackFailed} aria-label={t("previewOf", { name: project.name })} />}
+ {rendering && <div role="status"><p>{preview.status === "queued" ? t("waitingToRender") : t("rendering", { percent: Math.round(preview.progress * 100) })}</p><progress max={1} value={preview.progress} /></div>}
+ {!preview && <p>{t("renderToWatch")}</p>}
+ {preview?.status === "expired" && <p>{t("expired")}</p>}
{preview?.status === "error" && <p role="alert">{preview.error}</p>}
- {preview?.status === "done" && preview.revision !== project.revision && <p className="muted">This preview may be from an earlier edit.</p>}
+ {preview?.status === "done" && preview.revision !== project.revision && <p className="muted">{t("earlierEdit")}</p>}
<nav>
- {view.canRender && <button className="primary" disabled={busy || rendering || !ready} onClick={() => void run("render_preview", { projectId: project.id })}>Render preview</button>}
- <button disabled={!ready} onClick={() => openDonkey()}>Open in Donkey Cut ↗</button>
- <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>Projects</button>
- {error && <button disabled={busy || !ready} onClick={() => void run("open_project", { projectId: project.id })}>Try again</button>}
+ {view.canRender && <button className="primary" disabled={busy || rendering || !ready} onClick={() => void run("render_preview", { projectId: project.id })}>{t("renderPreview")}</button>}
+ <button disabled={!ready} onClick={() => openDonkey()}>{t("openInDonkey")}</button>
+ <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>{t("projects")}</button>
+ {error && <button disabled={busy || !ready} onClick={() => void run("open_project", { projectId: project.id })}>{t("tryAgain")}</button>}
</nav>
</>}
</main>;
@@ -76,7 +79,8 @@ export function PreviewApp() {
/** The editor's shape in its own white while it loads: the top bar, the tab
* rail, the preview and the timeline, drawn as the site's skeleton slabs. */
function EditorSkeleton() {
- return <div className="skeleton" role="status" aria-label="Opening the editor">
+ const t = useTranslations("chatgpt.widget");
+ return <div className="skeleton" role="status" aria-label={t("openingEditor")}>
<div className="bar"><i className="slab" /><i className="slab" /><span /><i className="slab" /><i className="slab" /></div>
<div className="rail">{[0, 1, 2, 3, 4].map((i) => <i key={i} className="slab" />)}</div>
<div className="stage"><i className="slab" /></div>
@@ -94,6 +98,7 @@ function EditorSkeleton() {
* blocks inside the frame. */
function EditorFrame({ url, name, inset, fullscreen, onReady, onFullscreen, onOpen, onSave, onDownloadError, onReconnect }: { url: string; name: string; inset: number; fullscreen: boolean; onReady: () => void; onFullscreen: () => void; onOpen: (url: string) => void; onSave: (text: string, name: string, mimeType: string) => void; onDownloadError: (message: string | null) => void; onReconnect: () => void }) {
const frame = useRef<HTMLIFrameElement>(null);
+ const t = useTranslations("chatgpt.widget");
const origin = new URL(url).origin;
const tell = () => frame.current?.contentWindow?.postMessage({ type: "donkeycut:host", insetBottom: inset, displayMode: fullscreen ? "fullscreen" : "inline" }, origin);
useEffect(tell, [inset, fullscreen, origin]);
@@ -120,5 +125,5 @@ function EditorFrame({ url, name, inset, fullscreen, onReady, onFullscreen, onOp
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
});
- return <iframe ref={frame} className="editor" src={url} onLoad={tell} title={`Editing ${name}`} allow="fullscreen; clipboard-read; clipboard-write" />;
+ return <iframe ref={frame} className="editor" src={url} onLoad={tell} title={t("editing", { name })} allow="fullscreen; clipboard-read; clipboard-write" />;
}
diff --git a/site/src/clients/chatgpt/ui/intl.tsx b/site/src/clients/chatgpt/ui/intl.tsx
new file mode 100644
index 00000000..14d5c4ea
--- /dev/null
+++ b/site/src/clients/chatgpt/ui/intl.tsx
@@ -0,0 +1,83 @@
+import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react";
+import { IntlProvider } from "use-intl";
+import de from "@/i18n/messages/de/chatgpt.json";
+import en from "@/i18n/messages/en/chatgpt.json";
+import es from "@/i18n/messages/es/chatgpt.json";
+import fr from "@/i18n/messages/fr/chatgpt.json";
+import ja from "@/i18n/messages/ja/chatgpt.json";
+import ko from "@/i18n/messages/ko/chatgpt.json";
+import ptBR from "@/i18n/messages/pt-BR/chatgpt.json";
+import zhCN from "@/i18n/messages/zh-CN/chatgpt.json";
+import { DEFAULT_LOCALE, LOCALES, type Locale } from "@/i18n/locales";
+import type { Messages } from "@/i18n/namespaces";
+
+// The widget is its own bundle with no Next provider, so it carries every
+// language's (small) chatgpt catalog and draws in the one ChatGPT names.
+const CATALOGS: Record<Locale, Messages["chatgpt"]> = {
+ en,
+ es: es as Messages["chatgpt"],
+ "pt-BR": ptBR as Messages["chatgpt"],
+ fr: fr as Messages["chatgpt"],
+ de: de as Messages["chatgpt"],
+ ja: ja as Messages["chatgpt"],
+ ko: ko as Messages["chatgpt"],
+ "zh-CN": zhCN as Messages["chatgpt"],
+};
+
+const MESSAGES = Object.fromEntries(
+ Object.entries(CATALOGS).map(([locale, chatgpt]) => [locale, { chatgpt }]),
+) as Record<Locale, Pick<Messages, "chatgpt">>;
+
+const SetLocale = createContext<(tag: string) => void>(() => {});
+
+// Each supported locale filled out to language-script-region once, so a tag
+// the host sends is matched with the browser's own Intl.Locale.
+const MAXIMIZED = LOCALES.map((locale) => [locale, new Intl.Locale(locale).maximize()] as const);
+
+/**
+ * The supported locale for one BCP 47 tag from the host: the same region
+ * first ("en-US" is en), then the same language and script ("pt-PT" is
+ * pt-BR, "zh-TW" is Traditional and falls to English). The site's
+ * Accept-Language matcher would add 46 KB to this bundle for one tag.
+ */
+function widgetLocale(tag: string): Locale {
+ let wanted: Intl.Locale;
+ try {
+ wanted = new Intl.Locale(tag).maximize();
+ } catch {
+ return DEFAULT_LOCALE;
+ }
+
+ const exact = MAXIMIZED.find(([, full]) => full.baseName === wanted.baseName);
+ if (exact) {
+ return exact[0];
+ }
+ const near = MAXIMIZED.find(([, full]) => full.language === wanted.language && full.script === wanted.script);
+ return near ? near[0] : DEFAULT_LOCALE;
+}
+
+/** ChatGPT sets window.openai before the widget runs; the MCP Apps host
+ * context names the locale again once the bridge connects. */
+function firstLocale(): Locale {
+ const openai = (window as { openai?: { locale?: unknown } }).openai;
+ return widgetLocale(typeof openai?.locale === "string" ? openai.locale : navigator.language);
+}
+
+export function WidgetIntl({ children }: { children: ReactNode }) {
+ const [locale, setLocale] = useState(firstLocale);
+
+ // The page's lang follows, so the host reads and speaks it right.
+ useEffect(() => {
+ document.documentElement.lang = locale;
+ }, [locale]);
+
+ const choose = useCallback((tag: string) => setLocale(widgetLocale(tag)), []);
+ return <SetLocale value={choose}>
+ <IntlProvider locale={locale} messages={MESSAGES[locale]}>{children}</IntlProvider>
+ </SetLocale>;
+}
+
+/** Switches the widget to a BCP 47 tag the host reports. */
+export function useSetWidgetLocale() {
+ return useContext(SetLocale);
+}
diff --git a/site/src/clients/chatgpt/ui/main.tsx b/site/src/clients/chatgpt/ui/main.tsx
index 5add2ec5..4d5105ea 100644
--- a/site/src/clients/chatgpt/ui/main.tsx
+++ b/site/src/clients/chatgpt/ui/main.tsx
@@ -1,4 +1,5 @@
import { createRoot } from "react-dom/client";
+import { WidgetIntl } from "./intl";
import { PreviewApp } from "./PreviewApp";
-createRoot(document.getElementById("root")!).render(<PreviewApp />);
+createRoot(document.getElementById("root")!).render(<WidgetIntl><PreviewApp /></WidgetIntl>);
diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.ts
index 00214b5c..0200f9a6 100644
--- a/site/src/clients/chatgpt/ui/useProjectApp.ts
+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts
@@ -1,5 +1,8 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { App } from "@modelcontextprotocol/ext-apps";
+import { useTranslations } from "use-intl";
+import type { Messages } from "@/i18n/namespaces";
+import { useSetWidgetLocale } from "./intl";
import { editorSchema, playbackSchema, viewSchema, type Editor, type Playback, type ProjectView } from "../contracts";
type ToolResult = { isError?: boolean; structuredContent?: unknown; _meta?: Record<string, unknown>; content?: unknown[] };
@@ -8,6 +11,17 @@ type ToolResult = { isError?: boolean; structuredContent?: unknown; _meta?: Reco
* the card makes gets a link minted for it. */
type Origin = "card" | "call";
+/** What went wrong, named by its message in the widget's catalog so the card
+ * draws it in whatever language the host speaks. */
+export type CardProblem = { key: keyof Messages["chatgpt"]["widget"]["problems"]; name?: string };
+
+/** A failure `receive` raises, carrying its problem to the caller's catch. */
+class CardError extends Error {
+ constructor(readonly problem: CardProblem["key"]) {
+ super(problem);
+ }
+}
+
/** The host carries authentication; the iframe only calls the MCP Apps bridge. */
export function useProjectApp() {
const appRef = useRef<App | null>(null);
@@ -21,22 +35,24 @@ export function useProjectApp() {
const [editorRequest, setEditorRequest] = useState<string | null>(null);
const requested = useRef<string | null>(null);
const reconnecting = useRef(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<CardProblem | null>(null);
+ const t = useTranslations("chatgpt.widget");
+ const setLocale = useSetWidgetLocale();
const [busy, setBusy] = useState(false);
const [visible, setVisible] = useState(!document.hidden);
const [pollMs, setPollMs] = useState(2000);
const recoveries = useRef(0);
const receive = useCallback((result: ToolResult, origin: Origin) => {
- if (result.isError) throw new Error("Donkey Cut could not complete this request. Try again.");
+ if (result.isError) throw new CardError("requestFailed");
const parsed = viewSchema.safeParse(result.structuredContent);
- if (!parsed.success) throw new Error("The preview response could not be read.");
+ if (!parsed.success) throw new CardError("unreadable");
// An editable project is the editor. Its link is good for one minute, so
// the card's own result counts it only inside that minute.
const editable = parsed.data.canEdit && parsed.data.project ? parsed.data.project.id : null;
const embed = editorSchema.safeParse(result._meta?.editor);
const link = embed.success && (origin !== "card" || embed.data.expiresAt > Date.now()) ? embed.data : null;
- if (origin === "call" && editable && !link) throw new Error("Donkey Cut could not open the editor. Try again.");
+ if (origin === "call" && editable && !link) throw new CardError("editorFailed");
const media = playbackSchema.safeParse(result._meta?.playback);
const interval = result._meta?.pollMs;
if (typeof interval === "number" && interval >= 1000 && interval <= 30000) setPollMs(interval);
@@ -56,7 +72,7 @@ export function useProjectApp() {
epoch.current++;
recoveries.current = 0;
setBusy(false);
- try { receive(result, "card"); } catch (e) { setError((e as Error).message); }
+ try { receive(result, "card"); } catch (e) { setError({ key: e instanceof CardError ? e.problem : "generic" }); }
};
// ChatGPT overlays its composer on the bottom of a fullscreen card and
// reports the covered band as a safe-area inset; the editor frame gets
@@ -64,6 +80,7 @@ export function useProjectApp() {
const applyContext = (context: ReturnType<App["getHostContext"]>) => {
if (!context) return;
if (context.theme) document.documentElement.dataset.theme = context.theme;
+ if (context.locale) setLocale(context.locale);
const full = context.displayMode === "fullscreen";
if (context.displayMode) setFullscreen(full);
// Measured from ChatGPT's desktop fullscreen when the host reports no inset.
@@ -76,7 +93,7 @@ export function useProjectApp() {
console.debug("[donkeycut] host context", context);
applyContext(context ?? { theme: "light" });
setReady(true);
- }).catch(() => { if (live) setError("Connect this preview from ChatGPT to continue."); });
+ }).catch(() => { if (live) setError({ key: "connect" }); });
const visibility = () => setVisible(!document.hidden);
document.addEventListener("visibilitychange", visibility);
return () => {
@@ -85,7 +102,7 @@ export function useProjectApp() {
document.removeEventListener("visibilitychange", visibility);
void app.close().catch(() => {});
};
- }, [receive]);
+ }, [receive, setLocale]);
const run = useCallback(async (name: string, args: Record<string, string>, manual = true, origin: Origin = "call") => {
const app = appRef.current;
@@ -98,7 +115,7 @@ export function useProjectApp() {
const result = await app.callServerTool({ name, arguments: args }).catch((): ToolResult => ({ isError: true }));
if (current === epoch.current && appRef.current === app) receive(result, origin);
} catch (e) {
- if (current === epoch.current && appRef.current === app) setError(e instanceof Error ? e.message : "Request failed.");
+ if (current === epoch.current && appRef.current === app) setError({ key: e instanceof CardError ? e.problem : "generic" });
} finally { if (current === epoch.current && appRef.current === app) setBusy(false); }
}, [ready, receive]);
@@ -120,21 +137,21 @@ export function useProjectApp() {
const playbackFailed = useCallback(() => {
if (!projectId || !jobId) return;
- if (recoveries.current++ >= 1) { setError("Video could not load. Try opening the project again."); return; }
+ if (recoveries.current++ >= 1) { setError({ key: "videoFailed" }); return; }
setPlayback(null);
void run("get_preview_status", { projectId, jobId }, false);
}, [projectId, jobId, run]);
- const openLink = async (url: string, failure: string) => {
+ const openLink = async (url: string) => {
if (!appRef.current) return;
- try { const result = await appRef.current.openLink({ url }); if (result.isError) setError(failure); }
- catch { setError(failure); }
+ try { const result = await appRef.current.openLink({ url }); if (result.isError) setError({ key: "openFailed" }); }
+ catch { setError({ key: "openFailed" }); }
};
- const openDonkey = () => { if (view?.project) void openLink(view.project.url, "Could not open Donkey Cut."); };
+ const openDonkey = () => { if (view?.project) void openLink(view.project.url); };
/** The framed editor asking for a tab: opening the project on donkeycut.com,
* and saving an export, which the card's sandbox blocks in the frame. */
const openFromFrame = useCallback((url: string) => {
- void openLink(url, "Could not open Donkey Cut.");
+ void openLink(url);
}, []);
/** A captions file made inside the frame: its bytes go with the request, so
* the host needs nothing from this origin to save it. */
@@ -145,8 +162,8 @@ export function useProjectApp() {
const result = await app.downloadFile({
contents: [{ type: "resource", resource: { uri: `file:///${name}`, mimeType, text } }],
});
- if (result.isError) setError(`Could not save ${name}.`);
- } catch { setError(`Could not save ${name}.`); }
+ if (result.isError) setError({ key: "saveFailed", name });
+ } catch { setError({ key: "saveFailed", name }); }
}, []);
useEffect(() => {
@@ -167,7 +184,7 @@ export function useProjectApp() {
/** The way forward from a project the account no longer has: a new cloud
* project, opened here in its place. Its result carries the editor link,
* so it opens like any other. */
- const createProject = () => { void run("create_project", { name: "Untitled" }); };
+ const createProject = () => { void run("create_project", { name: t("untitled") }); };
// The editor's own button asks for the whole window; the host grants what it supports.
const requestFullscreen = useCallback(async () => {
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 65eedf4f..7c03c2d3 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -15,6 +15,7 @@ import { PROJECT_PAGE_DEFAULT, PROJECT_PAGE_MAX } from "@/cut/lib/projectLink";
import { FIND_MEDIA_DEFAULT, FIND_MEDIA_MAX, FIND_MEDIA_SNAPSHOT_CAP } from "@/cut/lib/findMedia";
import { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "@/cut/lib/frameDiff";
import { EASE_IDS } from "@donkeycut/effects-kit";
+import { LOCALES, type Locale } from "@/i18n/locales";
import {
DETECT_CHANGES_MAX,
DETECT_CUTS_MAX,
@@ -59,6 +60,16 @@ const pictureArg = {
'Read inside this box of the source\'s frame, or "full" for the whole frame. Default: the picture box find_picture keeps on the source, else the whole frame. Every x, y, w, h the call takes and returns is a fraction of it.',
};
+/** A locale's language by its English name, the way the model reads it:
+ * "ko" → "Korean", "pt-BR" → "Brazilian Portuguese". */
+export function languageName(locale: Locale): string {
+ return new Intl.DisplayNames(["en"], { type: "language" }).of(locale) ?? locale;
+}
+
+/** The interface languages, as the prompt and set_interface_language list
+ * them: "en (English), es (Spanish), …". */
+export const INTERFACE_LANGUAGE_LIST = LOCALES.map((locale) => `${locale} (${languageName(locale)})`).join(", ");
+
export const AI_PANEL_TOOLS = [
{
name: "get_state",
@@ -468,6 +479,15 @@ export const AI_PANEL_TOOLS = [
["link", "asset_ids"]
),
},
+ {
+ name: "set_interface_language",
+ description:
+ `Change the language the editor's own interface shows — its menus, buttons and messages — for this account: ${INTERFACE_LANGUAGE_LIST}. Call it only when the person asks to change the interface language; a reply in another language needs no call. In the editor the change saves to the account and the page reloads in the new language as this reply finishes; a session with no editor page saves it to the account, and the editor opens in it next time. The result says which happened.`,
+ inputSchema: obj(
+ { locale: { type: "string", enum: [...LOCALES], description: "The interface language" } },
+ ["locale"]
+ ),
+ },
{
name: "list_skills",
description: "List the available skill documents about how this editor works.",
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 5828111e..f24c33c3 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -33,6 +33,7 @@ import {
X,
} from "lucide-react";
import Markdown, { type Components } from "react-markdown";
+import { useFormatter, useLocale, useTranslations } from "next-intl";
import { baseMarkdownComponents } from "./markdownComponents";
import { LiveElapsed } from "./Elapsed";
import { SceneCard } from "./SceneCard";
@@ -60,6 +61,7 @@ import {
deleteStoredThread,
isStoredThread,
loadProjectThreads,
+ flushThreadSaves,
readActiveChat,
readQueuedRows,
readRawThreads,
@@ -112,7 +114,7 @@ import { resolvePlayheadTokens, syncTimes, type TimeMark } from "@/cut/lib/timeM
import { productionDeps } from "@/cut/lib/pi/prodDeps";
import { withChatProject } from "@/cut/lib/projectChatTools";
import { runAiTool } from "@/cut/lib/aiTools";
-import { editorChatActive, holdEditorChat } from "@/cut/lib/editorWork";
+import { editorChatActive, flushEditorSave, holdEditorChat } from "@/cut/lib/editorWork";
import { nextSyncMs } from "@/cut/lib/syncCadence";
import { recoverSceneCall } from "@/cut/lib/chatRecovery";
import { countChunks, replayChatStream } from "@/cut/lib/chatReplay";
@@ -150,6 +152,12 @@ import { RECORD_RUNNING_TTL_MS, ToolOutputAssets } from "./ChatAssets";
import { attachedRefKeys, cardIsAttached } from "@/cut/lib/chatCards";
import { HostedErrorText, openCreditsWall } from "./hostedError";
import { useMicTranscription } from "@/cut/lib/micTranscribe";
+import { registerLanguageSink } from "@/cut/lib/interfaceLanguage";
+import { UserError } from "@/cut/lib/userError";
+import { useChatError } from "./chatError";
+import { switchLocale } from "@/i18n/localeCookie";
+import type { Locale } from "@/i18n/locales";
+import { useUpdateLocale } from "@/queries/accountProfile";
// Chat attachments are asset refs — anything in the project, the library, or
// the stock catalog. They arrive by drag (media cards, library clips, stock
@@ -170,6 +178,14 @@ interface EngineSend {
route: EngineRoute | undefined;
}
+/** A failure the engine coded for the reader: the English message it ended
+ * the stream with, and the code and values of its errors-catalog message. */
+interface ChatFailure {
+ message: string;
+ code: string;
+ params: Record<string, string | number>;
+}
+
/** A saved chat thread, persisted per project in localStorage. */
interface ChatThread {
id: string;
@@ -195,6 +211,10 @@ interface ChatThread {
const THREAD_LIMIT = 30;
+// The title older threads stored when their first message had no text; the
+// list words it, and an empty title, in the page's language.
+const UNTITLED_THREAD = "New chat";
+
// Which reply each thread has been read up to, per project: a small store
// over localStorage, so the panel reads it as a snapshot and any writer —
// this tab or another — updates every reader.
@@ -446,17 +466,27 @@ const PROVIDER_LABEL: Record<string, string> = {
claude: "Claude Code",
codex: "Codex",
gemini: "Gemini",
- test: "Testing",
};
+/** A provider's group name: product names as they are, the hermetic test
+ * provider in the page's language. */
+function providerLabel(id: string, t: ReturnType<typeof useTranslations<"chat.panel">>): string {
+ if (id === "test") {
+ return t("providerTesting");
+ }
+ return PROVIDER_LABEL[id] ?? id;
+}
+
+// The prompt chips on an empty thread, by message id (chat.panel.suggestions).
+// A chip sends its text in the page's language; the model reads any.
const SUGGESTIONS = [
- "What's in this video?",
- "Add transitions between clips",
- "Improve my title",
- "Watch and create subtitles",
- "Rewrite subtitles for social",
- "Write my post caption + tags",
-];
+ "whatsInVideo",
+ "addTransitions",
+ "improveTitle",
+ "createSubtitles",
+ "rewriteSubtitles",
+ "writeCaption",
+] as const;
export function AiPanel({
projectId,
@@ -469,6 +499,8 @@ export function AiPanel({
onClose: () => void;
onStatusChange: (projectId: string, status: ChatStatus) => void;
}) {
+ const t = useTranslations("chat.panel");
+ const format = useFormatter();
const [info, setInfo] = useState<ModelsInfo | null>(null);
const engineUp = useLocalCompute();
const readOnly = useEditor((s) => s.readOnly);
@@ -741,7 +773,7 @@ export function AiPanel({
const mergedInfo = useMemo<ModelsInfo | null>(() => {
const gemini =
signedIn === false
- ? { available: false, note: "sign in to Donkey to chat", installed: true }
+ ? { available: false, note: t("signInToChat"), installed: true }
: (info?.providers.gemini ?? { available: true, note: "", installed: true });
// With no engine on this Mac the CLI providers don't exist: their groups
// hide, and the saved-model fallback effect moves a CLI selection over to
@@ -753,7 +785,7 @@ export function AiPanel({
}
if (!info) return null;
return { ...info, providers: { ...info.providers, gemini } };
- }, [info, signedIn, engineUp]);
+ }, [info, signedIn, engineUp, t]);
return (
// A column beside the editor, as it has always been. Docking costs the
@@ -773,7 +805,7 @@ export function AiPanel({
variant="ghost"
size="sm"
className="ai-threads"
- title="Past threads"
+ title={t("pastThreads")}
aria-pressed={historyOpen}
onClick={toggleHistory}
>
@@ -789,13 +821,13 @@ export function AiPanel({
variant="ghost"
size="sm"
className="ai-new-thread"
- title="New chat"
+ title={t("newChat")}
onClick={newChat}
>
<Plus />
</Button>
)}
- <Button variant="ghost" size="sm" title="Close (⌘J)" onClick={onClose}>
+ <Button variant="ghost" size="sm" title={t("closeShortcut", { key: "⌘J" })} onClick={onClose}>
<X />
</Button>
</div>
@@ -817,20 +849,20 @@ export function AiPanel({
variant="ghost"
size="icon-sm"
className="hidden max-[620px]:inline-flex"
- aria-label="Back to chat"
- title="Back to chat"
+ aria-label={t("backToChat")}
+ title={t("backToChat")}
onClick={() => setHistoryOpen(false)}
>
<ChevronLeft />
</Button>
<span className="text-sm font-semibold tracking-tight">
- Threads
+ {t("threads")}
</span>
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
- title="Close"
+ title={t("close")}
className="max-[620px]:hidden"
onClick={() => setHistoryOpen(false)}
>
@@ -840,21 +872,21 @@ export function AiPanel({
<div className="ai-thread-items flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2">
{threads.length === 0 ? (
<p className="px-2 py-3 text-[11.5px] leading-relaxed text-muted-foreground">
- No past threads yet.
+ {t("noPastThreads")}
</p>
) : (
- threads.map((t) => (
+ threads.map((thread) => (
<button
- key={t.id}
+ key={thread.id}
className="group relative flex w-full items-center gap-2 rounded-lg py-2 pr-9 pl-2.5 text-left transition-colors hover:bg-muted"
- onClick={() => openThread(t)}
+ onClick={() => openThread(thread)}
>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate text-[12px] font-medium">
- {t.title}
+ {thread.title && thread.title !== UNTITLED_THREAD ? thread.title : t("newChat")}
</span>
<span className="text-[10.5px] text-muted-foreground">
- {new Date(t.updatedAt).toLocaleString([], {
+ {format.dateTime(new Date(thread.updatedAt), {
month: "short",
day: "numeric",
hour: "numeric",
@@ -863,16 +895,16 @@ export function AiPanel({
</span>
</span>
<span className="grid size-3.5 shrink-0 place-items-center">
- {runningThreads[t.id] ? (
+ {runningThreads[thread.id] ? (
<CircleDashed
role="img"
- aria-label="Working"
+ aria-label={t("working")}
className="size-3.5 animate-spin text-muted-foreground"
/>
- ) : unread(t) ? (
+ ) : unread(thread) ? (
<span
role="img"
- aria-label="Completed"
+ aria-label={t("completed")}
className="size-2 rounded-full bg-blue-500"
/>
) : null}
@@ -880,12 +912,12 @@ export function AiPanel({
{!readOnly && (
<span
role="button"
- aria-label="Delete thread"
- title="Delete thread"
+ aria-label={t("deleteThread")}
+ title={t("deleteThread")}
className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/10 hover:text-red-600"
onClick={(e) => {
e.stopPropagation();
- deleteThread(t.id);
+ deleteThread(thread.id);
}}
>
<Trash2 className="size-3.5" />
@@ -981,7 +1013,7 @@ function sessionChat(id: string, messages: UIMessage[] | undefined) {
type Bound = ChatEvents & { transport: ChatTransport<UIMessage> };
let bound: Bound | null = null;
const transport = () => {
- if (!bound) throw new Error("The chat is not ready yet.");
+ if (!bound) throw new UserError("chat_not_ready", "The chat is not ready yet.");
return bound.transport;
};
const chat = new Chat<UIMessage>({
@@ -1032,6 +1064,9 @@ function ChatSession({
/** What every running thread of the project is working on, by thread id. */
runningAsks: Record<string, string>;
}) {
+ const t = useTranslations("chat.panel");
+ const chatError = useChatError();
+ const locale = useLocale();
const [input, setInput] = useState("");
const composerRef = useRef<HTMLTextAreaElement>(null);
const caps = useCutCaps();
@@ -1118,6 +1153,12 @@ function ChatSession({
useEffect(() => {
attachmentsRef.current = attachments;
}, [attachments]);
+ // The intake outlives renders; it words its refusals through the newest
+ // translator.
+ const wordingRef = useRef({ t, chatError });
+ useEffect(() => {
+ wordingRef.current = { t, chatError };
+ });
useEffect(() => {
const el = composerBoxRef.current;
if (!el) return;
@@ -1129,12 +1170,10 @@ function ChatSession({
expect: setIncoming,
acceptFrame: () => {
if (attachmentsRef.current.filter(isFrame).length < cap) return true;
- showNotice(
- `Renders read up to ${cap} reference frames — remove one to add another.`,
- );
+ showNotice(wordingRef.current.t("frameCapacity", { count: cap }));
return false;
},
- notice: showNotice,
+ notice: (failure) => showNotice(wordingRef.current.chatError(failure)),
});
}, [readOnly, visible]);
const sessionKeyRef = useRef<string | null>(null);
@@ -1220,7 +1259,7 @@ function ChatSession({
res = await fetch(input, init);
if (res.ok) return res;
}
- throw new Error((await apiJson(res)).error ?? `The engine replied ${res.status}.`);
+ throw new Error((await apiJson(res)).error ?? t("engineReplied", { status: res.status }));
},
// The engine origin is discovered asynchronously; await it per request
// (not at mount) so an early send still targets the local engine rather
@@ -1246,6 +1285,7 @@ function ChatSession({
providerSession: sessionFor(currentModel()),
route,
handled: handledSince(messages),
+ locale,
},
};
},
@@ -1272,6 +1312,7 @@ function ChatSession({
threadId,
model: currentModel(),
messages: options.messages,
+ locale,
abortSignal: signal,
deps: productionDeps(projectId, signal),
});
@@ -1317,7 +1358,7 @@ function ChatSession({
return replay && countChunks(replay, (mark) => { streamed.current = mark; });
},
};
- }, [threadId, projectId, currentModel, sessionFor, setClientTools, prepareReplay, attachReplay, registerBrowserTurn, queryClient]);
+ }, [threadId, projectId, currentModel, sessionFor, setClientTools, prepareReplay, attachReplay, registerBrowserTurn, queryClient, locale, t]);
// The session owns its Chat so the thread's record can follow the chat's
// own state (recordThread, below) rather than this component's renders: a
@@ -1364,7 +1405,7 @@ function ChatSession({
const thread: ChatThread = {
...previous,
id: threadId,
- title: (firstUser ? messageText(firstUser) : "").slice(0, 80) || "New chat",
+ title: (firstUser ? messageText(firstUser) : "").slice(0, 80),
updatedAt: Date.now(),
completedMessageId: completedMessageId.current,
turnSettled: turnSettled.current,
@@ -1381,6 +1422,11 @@ function ChatSession({
}).catch(() => {});
},
onData: (part) => {
+ // A coded failure arrives ahead of the error that ends the stream, so
+ // the error line can read in the page's language.
+ if (part.type === "data-failure") {
+ setFailure(part.data as ChatFailure);
+ }
if (part.type === "data-session") {
const d = part.data as {
sessionKey?: string;
@@ -1488,14 +1534,16 @@ function ChatSession({
);
const browserRunning = useSyncExternalStore(watchBrowserChatTurns, () => browserChatRunning(projectId, threadId), () => false);
- const [sendError, setSendError] = useState<string | null>(null);
+ // A failed send, worded at render in the page's language.
+ const [sendError, setSendError] = useState<unknown>(null);
+ const [failure, setFailure] = useState<ChatFailure | null>(null);
const [requests] = useState(() => new ChatRequests());
const requestPending = useSyncExternalStore(requests.subscribe, requests.snapshot, () => false);
const dispatchChat = useCallback((request: () => Promise<void>) => {
void requests.run(request).catch((error: unknown) => {
- setSendError(error instanceof Error ? error.message : String(error));
+ setSendError(error);
});
- }, [requests]);
+ }, [requests, setSendError]);
const busy = requestPending || status === "submitted" || status === "streaming" || browserRunning;
useEffect(() => {
toolAbort.current = new AbortController();
@@ -1533,7 +1581,7 @@ function ChatSession({
// stands until a live session replaces it.
const thread: ChatThread = {
id: threadId,
- title: (firstUser ? messageText(firstUser) : "").slice(0, 80) || "New chat",
+ title: (firstUser ? messageText(firstUser) : "").slice(0, 80),
updatedAt: Date.now(),
messages: recoverSceneCall(live, threadId, useEditor.getState().genvideo),
sessions: { ...providerSessions.current },
@@ -1573,6 +1621,27 @@ function ChatSession({
recorder.current?.flush();
flushCloudThreadSaves();
}, [busy]);
+
+ // set_interface_language in this thread's turn: the language waits for the
+ // turn to settle, then the saves land, the account keeps it, and the page
+ // reloads in it.
+ const updateLocale = useUpdateLocale();
+ const pendingLocale = useRef<Locale | null>(null);
+ useEffect(() => registerLanguageSink(threadId, (next) => {
+ pendingLocale.current = next;
+ }), [threadId]);
+ useEffect(() => {
+ const next = pendingLocale.current;
+ if (busy || !next) {
+ return;
+ }
+ pendingLocale.current = null;
+ void (async () => {
+ await Promise.all([flushThreadSaves(), flushCloudThreadSaves(), flushEditorSave(projectId)]);
+ await updateLocale.mutateAsync(next);
+ switchLocale(next);
+ })().catch((error: unknown) => setSendError(error));
+ }, [busy, projectId, updateLocale]);
useEffect(() => {
const receive = () => {
if (chatThreadDeleted(projectId, threadId)) {
@@ -1856,9 +1925,10 @@ function ChatSession({
: true;
const unavailableMessage = (): string => {
const p = provider(model);
- if (p === "gemini") return "Sign in to your Donkey account to chat with Gemini.";
+ if (p === "gemini") return t("signInForGemini");
const note = info?.providers[p]?.note?.trim();
- return note ? `${PROVIDER_LABEL[p]}: ${note}` : `${PROVIDER_LABEL[p]} isn't available.`;
+ const name = providerLabel(p, t);
+ return note ? t("providerNote", { provider: name, note }) : t("providerUnavailable", { provider: name });
};
const send = (text: string) => {
// Inline @mentions attach their assets alongside the dropped chips. The
@@ -2141,18 +2211,16 @@ function ChatSession({
{messages.length === 0 && !hasSceneRun && (
<div className="flex flex-col gap-3 pt-6">
<p className="text-[12.5px] leading-relaxed text-muted-foreground">
- I can see your whole project — clips, titles, subtitles, publish
- metadata — and edit it for you. Select something and tell me
- what to change, or ask anything about the cut.
+ {t("intro")}
</p>
<div className="flex flex-wrap gap-1.5">
- {SUGGESTIONS.map((sug) => (
+ {SUGGESTIONS.map((id) => (
<button
- key={sug}
+ key={id}
className="ai-suggestion rounded-full border border-border px-2.5 py-1 text-[11.5px] text-muted-foreground transition-colors hover:border-input hover:text-foreground"
- onClick={() => send(sug)}
+ onClick={() => send(t(`suggestions.${id}`))}
>
- {sug}
+ {t(`suggestions.${id}`)}
</button>
))}
</div>
@@ -2168,18 +2236,21 @@ function ChatSession({
<ThreadRenders threadId={threadId} />
{busy && (
<div className="ai-busy mt-1 flex items-center gap-1.5 text-[11.5px] text-muted-foreground">
- <CircleDashed className="size-3 animate-spin" /> Working…{" "}
+ <CircleDashed className="size-3 animate-spin" /> {t("workingEllipsis")}{" "}
<LiveElapsed />
</div>
)}
- {((error && !retryDisconnect) || sendError) && (
+ {((error && !retryDisconnect) || sendError !== null) && (
<div className="ai-error mt-2 flex items-start gap-2 rounded-lg bg-red-50 px-2.5 py-2 text-[11.5px] leading-relaxed text-red-700">
<TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
<span className="min-w-0 break-words">
{error ? (
- <HostedErrorText error={error.message} link={false} />
+ <HostedErrorText
+ error={failure?.message === error.message ? chatError(new UserError(failure.code, failure.message, failure.params)) : error.message}
+ link={false}
+ />
) : (
- sendError
+ chatError(sendError)
)}
</span>
</div>
@@ -2214,8 +2285,9 @@ function ChatSession({
>
<TriangleAlert className="size-3 shrink-0" />
<span>
- Insufficient credits —{" "}
- <span className="font-medium underline">reload credits</span>
+ {t.rich("insufficientCredits", {
+ link: (chunks) => <span className="font-medium underline">{chunks}</span>,
+ })}
</span>
</button>
)}
@@ -2240,7 +2312,7 @@ function ChatSession({
)}
>
<TriangleAlert className="size-3 shrink-0" />
- <span>{saveFailure}</span>
+ <span>{chatError(saveFailure)}</span>
</div>
)}
{trayVisible && (
@@ -2318,7 +2390,7 @@ function ChatSession({
>
{dropActive && (
<div className="px-3 pt-2 text-[11.5px] font-medium text-[#0a84ff]">
- Drop to attach
+ {t("dropToAttach")}
</div>
)}
{mic.state === "idle" ? (
@@ -2344,7 +2416,7 @@ function ChatSession({
className="ai-input max-h-56 w-full resize-none overflow-y-auto bg-transparent px-3 pt-2 text-[12.5px] leading-relaxed outline-none placeholder:text-muted-foreground/70"
rows={5}
autoGrow
- placeholder="Ask about your video, or tell me what to change… @ references files, folders, and notes"
+ placeholder={t("composerPlaceholder")}
value={input}
onChange={setInput}
candidates={candidates}
@@ -2371,7 +2443,7 @@ function ChatSession({
variant="ghost"
size="sm"
className="ai-mic text-muted-foreground"
- title="Dictate"
+ title={t("dictate")}
disabled={busy}
onClick={() => void mic.start()}
>
@@ -2383,7 +2455,7 @@ function ChatSession({
variant="outline"
size="sm"
className="ai-stop"
- title="Stop"
+ title={t("stop")}
onClick={() => {
// stop() settles to 'ready', which the drain reads as
// a clean finish — park the queue here so it stays put
@@ -2393,7 +2465,7 @@ function ChatSession({
setQueuePaused(true);
userStopped.current = true;
toolAbort.current.abort();
- if (provider(model) !== "gemini") void cancelEngineChat(projectId, threadId).catch((error) => showNotice(String(error)));
+ if (provider(model) !== "gemini") void cancelEngineChat(projectId, threadId).catch((error) => showNotice(chatError(error)));
cancelBrowserChat(projectId, threadId);
void stop();
}}
@@ -2404,7 +2476,7 @@ function ChatSession({
<Button
size="sm"
className="ai-send"
- title="Send (Enter)"
+ title={t("sendShortcut", { key: "Enter" })}
disabled={!input.trim() && attachments.length === 0}
onClick={() => send(input)}
>
@@ -2420,7 +2492,7 @@ function ChatSession({
</div>
{mic.error && (
<p className="mt-1.5 px-1 text-[10.5px] leading-relaxed text-amber-700">
- {mic.error}
+ {chatError(mic.error)}
</p>
)}
</div>
@@ -2433,6 +2505,7 @@ function ChatSession({
* asset, double-click to expand, drag onto the timeline, "…" menu for more
* actions. */
function MessageAssetCard({ asset }: { asset: AssetRef }) {
+ const t = useTranslations("chat.panel");
// The reveal waits out the double-click window, so expanding doesn't also
// jump the side panel to the asset.
const clickTimer = useRef<number | undefined>(undefined);
@@ -2451,7 +2524,7 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {
>
<button
className="flex w-full flex-col gap-1 text-left"
- title={`${asset.name} — click to show · drag to the timeline`}
+ title={t("assetCardHint", { name: asset.name })}
draggable
onDragStart={(e) => {
// Project assets keep the timeline-placement payload; the ref rides
@@ -2484,7 +2557,7 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {
<DropdownMenuTrigger
render={
<button
- aria-label="Asset options"
+ aria-label={t("assetOptions")}
className="absolute top-1 right-1 grid size-5 place-items-center rounded-md bg-black/55 text-white opacity-0 transition-opacity group-hover/chip:opacity-100 hover:bg-black/75"
/>
}
@@ -2497,12 +2570,12 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {
useLightbox.getState().open(lightboxItemFromRef(asset))
}
>
- <Maximize2 /> Expand
+ <Maximize2 /> {t("expand")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => window.open(asset.url, "_blank", "noopener")}
>
- <ExternalLink /> Open file
+ <ExternalLink /> {t("openFile")}
</DropdownMenuItem>
{asset.scope === "project" && (
<DropdownMenuItem
@@ -2515,7 +2588,7 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {
});
}}
>
- <FolderPlus /> Add to Library
+ <FolderPlus /> {t("addToLibrary")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
@@ -2526,12 +2599,13 @@ function MessageAssetCard({ asset }: { asset: AssetRef }) {
/** Copy-to-clipboard affordance revealed on message hover. */
function MessageCopy({ text }: { text: string }) {
+ const t = useTranslations("chat.panel");
const [copied, setCopied] = useState(false);
if (!text) return null;
return (
<button
- aria-label="Copy message"
- title="Copy"
+ aria-label={t("copyMessage")}
+ title={t("copy")}
className={cn(
"ai-msg-copy",
cardIconButton,
@@ -2663,6 +2737,7 @@ function splitThoughtSegments(text: string): TextSegment[] {
/** A pulled post's own words, clamped to a few lines when the source ran
* long, with a chevron to unfold the full text in place. */
function SourceQuote({ text }: { text: string }) {
+ const t = useTranslations("chat.panel");
const [expanded, setExpanded] = useState(false);
const [clamped, setClamped] = useState(false);
const bodyRef = useRef<HTMLDivElement>(null);
@@ -2685,7 +2760,7 @@ function SourceQuote({ text }: { text: string }) {
{(clamped || expanded) && (
<button
type="button"
- aria-label={expanded ? "Collapse source text" : "Expand source text"}
+ aria-label={expanded ? t("collapseSource") : t("expandSource")}
onClick={() => setExpanded((v) => !v)}
className="mt-1 flex cursor-pointer items-center rounded text-muted-foreground/70 transition-colors hover:text-foreground"
>
@@ -2762,6 +2837,7 @@ function ToolChipGroup({ parts }: { parts: ToolPartView[] }) {
/** A run of 3+ settled tool chips folded behind one summary row. Opening it
* reveals the individual chips, each still expandable to its payload. */
function ToolRunGroup({ groups }: { groups: ToolPartView[][] }) {
+ const t = useTranslations("chat.panel");
const calls = groups.reduce((n, g) => n + g.length, 0);
// A failure the turn went back and made good is not a failure of the run: a
// tool that errored and then ran clean got where it was going, so the header
@@ -2785,7 +2861,7 @@ function ToolRunGroup({ groups }: { groups: ToolPartView[][] }) {
>
<Wrench className="size-3 shrink-0" />
<span>
- {calls} tool call{calls === 1 ? "" : "s"}
+ {t("toolCalls", { count: calls })}
</span>
{failed ? (
<TriangleAlert className="size-3" />
@@ -2805,11 +2881,12 @@ function ToolRunGroup({ groups }: { groups: ToolPartView[][] }) {
/** A collapsed disclosure for a reasoning block, styled like the tool row. */
function ThoughtBlock({ text }: { text: string }) {
+ const t = useTranslations("chat.panel");
return (
<details className="ai-thought group max-w-full">
<summary className="flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground transition-colors select-none hover:bg-muted/60 [&::-webkit-details-marker]:hidden">
<Brain className="size-3 shrink-0" />
- <span>Thought</span>
+ <span>{t("thought")}</span>
<ChevronDown className="ml-auto size-3 transition-transform group-open:rotate-180" />
</summary>
<div className="ai-md mt-1 max-w-full px-2 text-[12px] leading-relaxed text-muted-foreground">
@@ -2994,6 +3071,7 @@ const MessageView = memo(function MessageView({
* — the cards up-thread flip to their result, but this line is what says
* "something is still happening" without scrolling. */
function ThreadRenders({ threadId }: { threadId: string }) {
+ const t = useTranslations("chat.panel");
const jobs = useGenerate((s) => s.jobs);
const records = useEditor((s) => s.renders);
const live = jobs.filter(
@@ -3021,9 +3099,7 @@ function ThreadRenders({ threadId }: { threadId: string }) {
return (
<div className="ai-renders mt-1 flex items-center gap-1.5 text-[11.5px] text-muted-foreground">
<CircleDashed className="size-3 animate-spin" />
- Rendering {running.length === 1
- ? "a video"
- : `${running.length} videos`}…{" "}
+ {t("renderingVideos", { count: running.length })}{" "}
{elapsed && <span className="tabular-nums">{elapsed}</span>}
</div>
);
@@ -3038,6 +3114,9 @@ function ModelSelector({
model: string;
onSelect: (id: string) => void;
}) {
+ const t = useTranslations("chat.panel");
+ // Model names are product names; the hidden test model is described.
+ const modelLabel = (m: (typeof AI_MODELS)[number]) => (m.provider === "test" ? t("testModel") : m.label);
// Favorites follow the catalog: a retired id becomes its replacement, an
// unknown id drops, and one replacement standing in for two ids lists once.
const [favs, setFavs] = useState<string[]>(() => {
@@ -3078,7 +3157,8 @@ function ModelSelector({
// when the user sends.
.filter((group) => group.models.length > 0 && group.installed);
const flat = groups.flatMap((group) => group.models);
- const currentLabel = models.find((m) => m.id === model)?.label ?? model;
+ const current = models.find((m) => m.id === model);
+ const currentLabel = current ? modelLabel(current) : model;
const toggleFav = (id: string) => {
const next = favs.includes(id)
@@ -3108,7 +3188,7 @@ function ModelSelector({
<DropdownMenuGroup key={group.provider}>
{gi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel className="flex items-center gap-1.5 text-[10.5px] tracking-wider text-muted-foreground uppercase">
- <Sparkles className="size-3" /> {PROVIDER_LABEL[group.provider]}
+ <Sparkles className="size-3" /> {providerLabel(group.provider, t)}
</DropdownMenuLabel>
{group.models.map((m) => (
<DropdownMenuItem
@@ -3116,13 +3196,13 @@ function ModelSelector({
className="ai-model-item gap-2"
onClick={() => onSelect(m.id)}
>
- <span className="flex-1 text-[12px]">{m.label}</span>
+ <span className="flex-1 text-[12px]">{modelLabel(m)}</span>
{model === m.id && (
<Check className="size-3.5 text-[#0a84ff]" />
)}
<button
className="rounded p-0.5 hover:bg-muted"
- title={favs.includes(m.id) ? "Unfavorite" : "Favorite"}
+ title={favs.includes(m.id) ? t("unfavorite") : t("favorite")}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
diff --git a/site/src/cut/components/AnimationTiles.tsx b/site/src/cut/components/AnimationTiles.tsx
index 8b20bdd5..3a683a2a 100644
--- a/site/src/cut/components/AnimationTiles.tsx
+++ b/site/src/cut/components/AnimationTiles.tsx
@@ -1,6 +1,7 @@
"use client";
import { erodeMask } from "./textureCss";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import {
countText,
@@ -36,6 +37,8 @@ import { Tile } from "@/cut/components/PanelTile";
import { SectionTitle } from "@/cut/components/SectionTitle";
import { wordDrawCss } from "@/cut/lib/textRender";
import { fontStack } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
+import type { Messages } from "@/i18n/namespaces";
/**
* The animation picker: a grid of tiles, each playing its style on the style's
@@ -104,16 +107,32 @@ type Slot = "in" | "out" | "loop" | "move" | "words" | "hit";
* to play in — long enough to read a push, short enough to come round again. */
const MOVE_DEMO_SECONDS = 2.4;
-const labelOf = (slot: Slot, style: string) =>
- slot === "hit"
- ? (OVERLAY_HIT_STYLE_LABELS[style] ?? style)
- : slot === "words"
- ? (WORD_EFFECT_LABELS[style] ?? style)
- : slot === "move"
- ? (MOTION.holds[style]?.label ?? style)
- : slot === "loop"
- ? (OVERLAY_LOOP_STYLE_LABELS[style as OverlayLoopStyle] ?? style)
- : (OVERLAY_ANIM_STYLE_LABELS[style as OverlayAnimStyle] ?? style);
+type HoldId = keyof Messages["inspector"]["holds"];
+
+/** Names a slot's style in the page's language. The registries say which ids
+ * are known; an id none of them knows reads as itself. */
+function useSlotLabel(): (slot: Slot, style: string) => string {
+ const t = useTranslations("inspector.holds");
+ const hitLabel = useLabels("overlayHit");
+ const wordLabel = useLabels("wordEffect");
+ const loopLabel = useLabels("overlayLoop");
+ const animLabel = useLabels("overlayAnim");
+ return (slot, style) => {
+ if (slot === "hit") {
+ return style in OVERLAY_HIT_STYLE_LABELS ? hitLabel(style) : style;
+ }
+ if (slot === "words") {
+ return style in WORD_EFFECT_LABELS ? wordLabel(style) : style;
+ }
+ if (slot === "move") {
+ return MOTION.holds[style] ? t(style as HoldId) : style;
+ }
+ if (slot === "loop") {
+ return style in OVERLAY_LOOP_STYLE_LABELS ? loopLabel(style) : style;
+ }
+ return style in OVERLAY_ANIM_STYLE_LABELS ? animLabel(style) : style;
+ };
+}
function demoStateAt(
slot: Slot,
@@ -216,6 +235,7 @@ const splitsGlyphs = (slot: Slot, style: string) =>
/** The name standing still: what a card wears until the pointer reaches it,
* and what every tile falls back to when the reader asks for less motion. */
function FrozenName({ slot, style }: { slot: Slot; style: string }) {
+ const labelOf = useSlotLabel();
return (
<span className={`${WORD} text-foreground`} style={wordStyle()}>
{labelOf(slot, style)}
@@ -244,6 +264,7 @@ function LiveName({
index?: number;
}) {
const ref = useRef<HTMLSpanElement>(null);
+ const labelOf = useSlotLabel();
const label = labelOf(slot, style);
const typed = typesItsName(slot, style);
const counts = countsItsName(slot, style);
@@ -437,6 +458,7 @@ function WordName({
index?: number;
}) {
const ref = useRef<HTMLSpanElement>(null);
+ const labelOf = useSlotLabel();
const label = labelOf("words", style);
const cycle = WORD_DEMO_SECONDS + WORD_DEMO_HOLD;
const phase = index * PHASE_STEP * cycle;
@@ -591,6 +613,7 @@ function AnimTile({
}) {
const ref = useRef<HTMLButtonElement>(null);
const onScreen = useOnScreen(ref);
+ const labelOf = useSlotLabel();
return (
<Tile
ref={ref}
@@ -654,6 +677,7 @@ export function AnimationTiles({
accentDim?: number;
onPick: (style: string | null) => void;
}) {
+ const t = useTranslations("inspector.animationTiles");
const tile = (id: string, i: number) => (
<AnimTile
key={id}
@@ -672,10 +696,10 @@ export function AnimationTiles({
/>
);
const none = (
- <Tile selected={!value && !custom} onClick={() => onPick(null)} title="None" className="p-1">
+ <Tile selected={!value && !custom} onClick={() => onPick(null)} title={t("none")} className="p-1">
<span className={STAGE}>
<span className={`${WORD} text-muted-foreground/70`} style={wordStyle()}>
- None
+ {t("none")}
</span>
</span>
</Tile>
@@ -691,7 +715,7 @@ export function AnimationTiles({
<div className="grid grid-cols-2 gap-[9px]">{none}</div>
{WORD_FAMILIES.map((f) => (
<div key={f.id} className="flex flex-col gap-1.5">
- <SectionTitle>{f.label}</SectionTitle>
+ <SectionTitle>{t(`wordFamilies.${f.id}`)}</SectionTitle>
<div className="grid grid-cols-2 gap-[9px]">
{wordEffectIdsIn(f.id).map((id) => tile(id, n++))}
</div>
diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsx
index 9f9db705..fa2ef04c 100644
--- a/site/src/cut/components/AppSidebar.tsx
+++ b/site/src/cut/components/AppSidebar.tsx
@@ -3,6 +3,8 @@
import { DonkeyMark } from "@/components/DonkeyMark";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
+import { creatorNames } from "@/cut/lib/defaultNames";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Camera, Clapperboard, FolderOpen, Loader2, StickyNote } from "lucide-react";
@@ -27,18 +29,22 @@ import type { ProjectSummary } from "@/cut/lib/types";
import { newProjectAllowed } from "@/cut/lib/projectLimit";
import { cn } from "@/lib/utils";
-const NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [
- { tab: "projects", label: "Projects", icon: Clapperboard },
- { tab: "library", label: "Library", icon: FolderOpen },
- { tab: "notes", label: "Notes", icon: StickyNote },
+// Each tab's name is its key in the home catalog's tab names.
+type NavEntry = { tab: CutTab; label: "projects" | "library" | "notes" | "cameraRoll"; icon: typeof Clapperboard };
+
+const NAV: NavEntry[] = [
+ { tab: "projects", label: "projects", icon: Clapperboard },
+ { tab: "library", label: "library", icon: FolderOpen },
+ { tab: "notes", label: "notes", icon: StickyNote },
];
// Surfaces fed by the iOS app, listed only for accounts that use it.
-const PHONE_NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [
- { tab: "camera-roll", label: "Camera Roll", icon: Camera },
+const PHONE_NAV: NavEntry[] = [
+ { tab: "camera-roll", label: "cameraRoll", icon: Camera },
];
export function AppSidebar() {
+ const t = useTranslations("home");
const pathname = usePathname();
const router = useRouter();
const base = useCutBase();
@@ -60,7 +66,7 @@ export function AppSidebar() {
const res = await backendFor(r).fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: name.trim() || "Untitled" }),
+ body: JSON.stringify({ name: name.trim() || creatorNames().untitled }),
});
const project = (await res.json()) as ProjectSummary;
patchProjects(client, r, (s) => ({
@@ -117,7 +123,7 @@ export function AppSidebar() {
)}
>
<Icon className="size-4" />
- {label}
+ <span className="truncate">{t(`tabs.${label}`)}</span>
</Link>
);
})}
@@ -129,7 +135,7 @@ export function AppSidebar() {
<Dialog open={createIn !== null} onOpenChange={(o) => !o && setCreateIn(null)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>New project</DialogTitle>
+ <DialogTitle>{t("newProject.title")}</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
@@ -139,14 +145,14 @@ export function AppSidebar() {
>
<Input
autoFocus
- placeholder="Project name"
+ placeholder={t("newProject.placeholder")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<DialogFooter className="mt-4">
<Button type="submit" disabled={busy} className="w-full">
{busy && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Create project
+ {t("newProject.create")}
</Button>
</DialogFooter>
</form>
diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsx
index 9c1011b6..aa836f52 100644
--- a/site/src/cut/components/AssetRefs.tsx
+++ b/site/src/cut/components/AssetRefs.tsx
@@ -2,6 +2,7 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import Link from "next/link";
+import { useTranslations } from "next-intl";
import { CUT_APP_BASE, homeHref, projectHref } from "@/cut/lib/nav";
import { Check, Clock, Copy, FileText, X } from "lucide-react";
import {
@@ -177,13 +178,14 @@ export function CopyHandlePill({
name: string;
className?: string;
}) {
+ const t = useTranslations("chat.assetRefs");
const [copied, setCopied] = useState(false);
const token = handle ? `@${handle}` : mentionToken(name);
return (
<button
type="button"
- title="Copy reference"
- aria-label={`Copy reference ${token}`}
+ title={t("copyReference")}
+ aria-label={t("copyReferenceToken", { token })}
className={cn(
"absolute top-1 left-1 max-w-[calc(100%-0.5rem)] rounded-[5px] opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100",
className
@@ -200,7 +202,7 @@ export function CopyHandlePill({
.catch(() => {});
}}
>
- <RefHandlePill token={copied ? "Copied" : token} />
+ <RefHandlePill token={copied ? t("copied") : token} />
</button>
);
}
@@ -323,6 +325,7 @@ export function RefTokenChip({
onDark?: boolean;
peekSide?: "top" | "bottom";
}) {
+ const t = useTranslations("chat.assetRefs");
const [peek, setPeek] = useState(false);
// Entity refs have no media to peek at and no card to jump to — the pill
// itself, icon plus name, is the whole story.
@@ -355,7 +358,7 @@ export function RefTokenChip({
>
<button
type="button"
- title={`${item.name} — click to show`}
+ title={t("showHint", { name: item.name })}
className={cn(
"ref-token rounded-md px-1 font-mono text-[11px] transition-colors",
onDark
@@ -506,6 +509,7 @@ export function RefChips({
* row exactly when the arriving chip would. */
trailing?: ReactNode;
}) {
+ const t = useTranslations("chat.assetRefs");
const candidates = useRefCandidates();
if (refs.length === 0 && !trailing) return null;
return (
@@ -522,7 +526,7 @@ export function RefChips({
<span key={r.id} className="inline-flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-1 text-xs">
{entityGlyph(r, "size-3 shrink-0")}
<CollectionLink item={r} className="truncate">{r.name}</CollectionLink>
- <button type="button" aria-label={`Remove ${r.name}`} onClick={() => onRemove(r)}><X className="size-3" /></button>
+ <button type="button" aria-label={t("removeName", { name: r.name })} onClick={() => onRemove(r)}><X className="size-3" /></button>
</span>
);
return (
@@ -571,6 +575,7 @@ function RefChip({
peekSide: "top" | "bottom";
thumbClassName: string;
}) {
+ const t = useTranslations("chat.assetRefs");
const [hover, setHover] = useState(false);
// The moment card must survive interactions that take the pointer or focus
// off the chip — a slider/hot-text drag (pointer capture) and typing in the
@@ -632,7 +637,7 @@ function RefChip({
) : (
<button
type="button"
- title={`${item.name} — click to show`}
+ title={t("showHint", { name: item.name })}
className="block text-left"
onClick={() => revealRef(item)}
>
@@ -674,8 +679,8 @@ function RefChip({
hover && item.scope !== "entity" && <RefPeek item={item} side={peekSide} />
)}
<button
- aria-label={`Remove ${item.name}`}
- title="Remove"
+ aria-label={t("removeName", { name: item.name })}
+ title={t("remove")}
className="absolute -top-1.5 -right-1.5 grid size-4.5 place-items-center rounded-full bg-neutral-900 text-white shadow-sm transition-colors hover:bg-neutral-700"
onClick={() => onRemove(item)}
>
@@ -768,6 +773,7 @@ function MomentControls({
onChange: (ref: AssetRef) => void;
className?: string;
}) {
+ const tMoment = useTranslations("chat.assetRefs");
const { lo, hi } = momentBounds(item, dur);
const t = item.t ?? lo;
const apply = (next: number) =>
@@ -775,7 +781,7 @@ function MomentControls({
return (
<div className={cn("flex items-center gap-2", className)}>
<ValueSlider
- label="Pinned moment"
+ label={tMoment("pinnedMoment")}
sliderClassName="min-w-0 flex-1"
valueClassName="shrink-0 text-muted-foreground"
value={t}
@@ -923,14 +929,15 @@ function useCopied(): [boolean, (text: string) => void] {
/** Hover icon button that copies the asset's reference token (`@v2`, or the
* `@name` form when it has no short handle). */
export function CopyRefButton({ name, className }: { name: string; className?: string }) {
+ const t = useTranslations("chat.assetRefs");
const [copied, copy] = useCopied();
const ref = useRefFor(name);
const token = ref ? refToken(ref) : mentionToken(name);
return (
<span
role="button"
- aria-label={`Copy reference to ${name}`}
- title={`Copy ${token} to reference in prompts`}
+ aria-label={t("copyReferenceTo", { name })}
+ title={t("copyTokenHint", { token })}
className={cn(
"grid size-5 cursor-pointer place-items-center rounded-full bg-black/45 text-white hover:bg-black/65",
className
@@ -999,6 +1006,7 @@ export function CopyNameLabel({
* projects homes — show the name and nothing more. */
mention?: boolean;
}) {
+ const t = useTranslations("chat.assetRefs");
const [copied, copy] = useCopied();
const ref = useRefFor(name);
const token = ref ? refToken(ref) : mentionToken(name);
@@ -1009,7 +1017,7 @@ export function CopyNameLabel({
return (
<button
type="button"
- title={`Click to copy ${token} — paste it in any prompt to reference this asset`}
+ title={t("clickToCopyHint", { token })}
className={cn("flex min-w-0 items-center gap-1 cursor-copy text-left", className)}
onClick={(e) => {
e.stopPropagation();
@@ -1024,7 +1032,7 @@ export function CopyNameLabel({
)}
{copied ? (
<span className={cn("truncate", dark ? "text-white" : "text-emerald-600")}>
- Copied {token}
+ {t("copiedToken", { token })}
</span>
) : (
<TruncatedText text={shown} />
@@ -1143,6 +1151,7 @@ function MentionPill({
/** Select the whole token in the textarea. */
onSelectToken: () => void;
}) {
+ const t = useTranslations("chat.assetRefs");
const spanRef = useRef<HTMLSpanElement>(null);
const coverRef = useRef<HTMLSpanElement>(null);
const [wrapped, setWrapped] = useState(false);
@@ -1190,7 +1199,7 @@ function MentionPill({
pinnable && "pointer-events-auto cursor-pointer hover:bg-[#0a84ff]/25",
atomic && "pointer-events-auto cursor-default"
)}
- title={pinnable ? `${item.name} — click to pin the moment` : undefined}
+ title={pinnable ? t("pinHint", { name: item.name }) : undefined}
// mousedown, not click: preventDefault keeps focus in the textarea.
onMouseDown={
pinnable
@@ -1308,6 +1317,7 @@ export function MentionTextarea({
* the moment if the cut moves before the message goes out. */
onInsertTime?: (mark: TimeMark) => void;
}) {
+ const t = useTranslations("chat.assetRefs");
const taRef = useRef<HTMLTextAreaElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const backdropRef = useRef<HTMLDivElement>(null);
@@ -1616,7 +1626,7 @@ export function MentionTextarea({
<Clock className="size-4" />
</span>
<RefHandleBadge handle={PLAYHEAD_HANDLE} className="shrink-0" />
- <span className="min-w-0 flex-1 truncate text-[11.5px]">{PLAYHEAD_NAME}</span>
+ <span className="min-w-0 flex-1 truncate text-[11.5px]">{t("playhead")}</span>
<PlayheadRowTime />
</button>
)}
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index 718122a6..90201387 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -8,6 +8,7 @@ import {
useRef,
useState,
} from "react";
+import { useTranslations } from "next-intl";
import {
AudioLines,
Check,
@@ -65,18 +66,20 @@ import { GeneratedAssetMenu } from "@/cut/components/GeneratedAssetMenu";
import { cn } from "@/lib/utils";
import { scrimIconButton } from "@/cut/components/iconButton";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useDescribeError } from "@/i18n/describeError";
/** Starting points for the direction prompt — picking one fills the input so
- * it can be tweaked before generating. */
-const DIRECTION_PRESETS: { label: string; text: string }[] = [
- { label: "Warm", text: "Say warmly, like an old friend" },
- { label: "Energetic", text: "Say with high energy, like a hype announcer" },
- { label: "Documentary", text: "Narrate calmly and evenly, like a nature documentary" },
- { label: "Movie trailer", text: "Say dramatically, with gravity, like a movie trailer" },
- { label: "News anchor", text: "Read briskly and clearly, like a news anchor" },
- { label: "Whisper", text: "Whisper softly, close to the mic" },
- { label: "Bedtime story", text: "Read slowly and gently, like a bedtime story" },
-];
+ * it can be tweaked before generating. Each id names a label and a direction
+ * line in the panels catalog. */
+const DIRECTION_PRESETS = [
+ "warm",
+ "energetic",
+ "documentary",
+ "movieTrailer",
+ "newsAnchor",
+ "whisper",
+ "bedtimeStory",
+] as const;
/** The Audio tab: Voice generates an AI voiceover, Music an instrumental bed;
* each lists what it made as playable rows that drop onto the soundtrack at the
@@ -95,6 +98,7 @@ export function AudioPanel({
sub: "voice" | "music";
onSub: (v: "voice" | "music") => void;
}) {
+ const t = useTranslations("panels.audio");
const readOnly = useEditor((s) => s.readOnly);
// The app-wide preview player: starting a clip stops the last one, here or
// on a chat audio card. Leaving the tab silences only this panel's own
@@ -120,8 +124,8 @@ export function AudioPanel({
<div className="flex h-12 shrink-0 items-center pr-12 pl-3.5">
<SubTabs
tabs={[
- { id: "voice", label: "Voice" },
- { id: "music", label: "Music" },
+ { id: "voice", label: t("voiceTab") },
+ { id: "music", label: t("musicTab") },
]}
value={sub}
onChange={onSub}
@@ -155,6 +159,8 @@ export function AudioPanel({
* soundtrack. Mirrors VoiceGenerator's shape — several syntheses can run at
* once, so the button stays live and a status row counts them. */
function MusicGenerator({ projectId }: { projectId: string }) {
+ const t = useTranslations("panels.audio");
+ const describeError = useDescribeError();
// Prompt + vocals mode live in a store so a dragged/clicked sample can seed
// them for remixing (see musicGen.ts). Lyria sings by default; a bed under
// narration usually wants no vocals, so the toggle defaults to instrumental.
@@ -186,8 +192,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
return STOCK_MUSIC.find((s) => s.id === ref.id);
};
const [error, setError] = useState<{ text: string } | null>(null);
- const fail = (e: unknown, fallback: string) =>
- setError({ text: e instanceof Error ? e.message : fallback });
+ const fail = (e: unknown, fallback: string) => setError({ text: describeError(e, fallback) });
// Music runs on the user's Donkey account, like image/video/voiceover.
const signedOut = useSignedIn() === false;
@@ -217,7 +222,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
useEditor.getState().addAsset(asset);
void enrichAsset(asset);
} catch (e) {
- fail(e, "Music generation failed.");
+ fail(e, t("musicFailed"));
} finally {
settle();
}
@@ -225,7 +230,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
);
};
- const variantLabel = MUSIC_VARIANTS.find((v) => v.id === variant) ?? MUSIC_VARIANTS[0];
+ const variantId = (MUSIC_VARIANTS.find((v) => v.id === variant) ?? MUSIC_VARIANTS[0]).id;
// Every take renders a track at the length's flat price.
const cost = useGenerateCost((sheet) => musicMicros(sheet, variant, takes));
const button = generateButton(cost, () => void generate());
@@ -233,7 +238,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
return (
<div className="music-generator flex flex-col gap-3.5">
<div className="flex flex-col gap-2">
- <SectionTitle>Describe the music</SectionTitle>
+ <SectionTitle>{t("describeMusic")}</SectionTitle>
<div
className={cn(
"relative rounded-lg border border-input focus-within:border-ring",
@@ -258,7 +263,7 @@ function MusicGenerator({ projectId }: { projectId: string }) {
>
<textarea
className="music-prompt min-h-[88px] w-full resize-y rounded-lg bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
- placeholder="Warm acoustic guitar and soft piano, calm and hopeful — or describe a song to sing"
+ placeholder={t("musicPlaceholder")}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
@@ -271,33 +276,39 @@ function MusicGenerator({ projectId }: { projectId: string }) {
<div className="flex gap-2">
<PillSelect
className="h-7 flex-1"
- title="Length"
+ title={t("length")}
value={variant}
- display={variantLabel.label}
- options={MUSIC_VARIANTS.map((v) => ({ value: v.id, label: `${v.label} · ${v.hint}` }))}
+ display={t(`musicVariants.${variantId}.label`)}
+ options={MUSIC_VARIANTS.map((v) => ({
+ value: v.id,
+ label: t("variantOption", {
+ label: t(`musicVariants.${v.id}.label`),
+ hint: t(`musicVariants.${v.id}.hint`),
+ }),
+ }))}
onChange={setVariant}
/>
<PillSelect
className="h-7 flex-1"
- title="Takes"
+ title={t("takesTitle")}
value={String(takes)}
- display={`${takes} take${takes > 1 ? "s" : ""}`}
+ display={t("takes", { count: takes })}
options={[1, 2, 3, 4].map((n) => ({
value: String(n),
- label: `${n} take${n > 1 ? "s" : ""}`,
+ label: t("takes", { count: n }),
}))}
onChange={(v) => setTakes(Number(v))}
/>
</div>
<div className="flex rounded-lg bg-muted p-0.5 text-[11.5px]">
- {([["song", "Song"], ["instrumental", "Instrumental"]] as const).map(([val, label]) => {
+ {([["song", t("song")], ["instrumental", t("instrumental")]] as const).map(([val, label]) => {
const active = (val === "instrumental") === instrumental;
return (
<button
key={val}
type="button"
onClick={() => setInstrumental(val === "instrumental")}
- title={val === "song" ? "Let the model write and sing lyrics" : "No vocals — a background bed"}
+ title={val === "song" ? t("songHint") : t("instrumentalHint")}
className={cn(
"flex-1 rounded-md px-3 py-0.5 font-medium transition-colors",
active
@@ -313,16 +324,16 @@ function MusicGenerator({ projectId }: { projectId: string }) {
<Button
className="music-generate w-full"
disabled={!prompt.trim() || signedOut}
- title={!prompt.trim() ? "Describe the music above to generate" : undefined}
+ title={!prompt.trim() ? t("describeToGenerate") : undefined}
onClick={button.onClick}
>
<Music data-icon="inline-start" />
- Generate music
+ {t("generateMusic")}
</Button>
{pending > 0 && (
<div className="flex items-center gap-2 text-[11px] text-muted-foreground">
<Loader2 className="size-3.5 shrink-0 animate-spin" />
- {pending === 1 ? "Generating…" : `Generating ${pending}…`}
+ {t("generating", { count: pending })}
<LiveElapsed />
</div>
)}
@@ -330,11 +341,13 @@ function MusicGenerator({ projectId }: { projectId: string }) {
{signedOut ? (
<p className="music-signin text-[11px] leading-relaxed text-muted-foreground">
- Music runs on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("musicSignIn", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
) : (
error && (
@@ -348,6 +361,8 @@ function MusicGenerator({ projectId }: { projectId: string }) {
}
function VoiceGenerator({ projectId }: { projectId: string }) {
+ const t = useTranslations("panels.audio");
+ const describeError = useDescribeError();
const voice = useSpeakerVoice();
const language = useSpeechLanguage();
const [script, setScript] = useState("");
@@ -356,8 +371,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
// unmounting when the user changes tabs.
const pending = useActiveWork("audio", "voice");
const [error, setError] = useState<{ text: string } | null>(null);
- const fail = (e: unknown, fallback: string) =>
- setError({ text: e instanceof Error ? e.message : fallback });
+ const fail = (e: unknown, fallback: string) => setError({ text: describeError(e, fallback) });
const directionInput = useRef<HTMLTextAreaElement>(null);
// Voiceovers run on the user's Donkey account, like image/video generation.
const signedOut = useSignedIn() === false;
@@ -399,7 +413,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
});
void enrichAsset(asset);
} catch (e) {
- fail(e, "Voice generation failed.");
+ fail(e, t("voiceFailed"));
} finally {
settle();
}
@@ -410,23 +424,22 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
{/* Voice settings first — pick how the voice sounds, then script it. */}
<VoicePicker
direction={direction}
- onError={(e) => fail(e, "Could not play the sample.")}
+ onError={(e) => fail(e, t("sampleFailed"))}
/>
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-1">
- <SectionTitle>Voice direction</SectionTitle>
+ <SectionTitle>{t("voiceDirection")}</SectionTitle>
<TooltipProvider>
<Tooltip>
<TooltipTrigger
className="voice-direction-info grid size-4 place-items-center text-muted-foreground transition-colors hover:text-foreground"
- aria-label="About voice direction"
+ aria-label={t("aboutDirection")}
>
<Info className="size-3.5" />
</TooltipTrigger>
<TooltipContent side="right" className="max-w-60">
- Optional. Tell the voice how to deliver the lines — its tone, pace, and energy, or
- ask it to speak in another language.
+ {t("directionHint")}
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -436,27 +449,30 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
ref={directionInput}
rows={2}
className="voice-direction min-h-[52px] w-full resize-y rounded-lg border border-input bg-transparent py-2 pr-9 pl-2.5 text-[12.5px] leading-relaxed outline-none focus:border-ring"
- placeholder="Say warmly, like an old friend"
+ placeholder={t("directionPresets.warm.text")}
value={direction}
onChange={(e) => setDirection(e.target.value)}
/>
<DropdownMenu>
<DropdownMenuTrigger
className="voice-direction-presets absolute top-1.5 right-1 grid size-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- aria-label="Direction presets"
+ aria-label={t("directionPresetsLabel")}
>
<ChevronDown className="size-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
- {DIRECTION_PRESETS.map((p) => (
- <DropdownMenuItem key={p.label} onClick={() => setDirection(p.text)}>
- <div className="flex min-w-0 flex-1 flex-col">
- <span className="text-[12px] font-medium">{p.label}</span>
- <span className="truncate text-[11px] text-muted-foreground">{p.text}</span>
- </div>
- {direction === p.text && <Check className="size-3.5 shrink-0" />}
- </DropdownMenuItem>
- ))}
+ {DIRECTION_PRESETS.map((id) => {
+ const text = t(`directionPresets.${id}.text`);
+ return (
+ <DropdownMenuItem key={id} onClick={() => setDirection(text)}>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="text-[12px] font-medium">{t(`directionPresets.${id}.label`)}</span>
+ <span className="truncate text-[11px] text-muted-foreground">{text}</span>
+ </div>
+ {direction === text && <Check className="size-3.5 shrink-0" />}
+ </DropdownMenuItem>
+ );
+ })}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
@@ -465,7 +481,7 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
setTimeout(() => directionInput.current?.focus(), 0);
}}
>
- <span className="text-[12px] font-medium">Custom…</span>
+ <span className="text-[12px] font-medium">{t("custom")}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -477,11 +493,11 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
{/* The script and its generate button stay together so the button's job —
and why it's disabled until there's a script — is obvious. */}
<div className="flex flex-col gap-2">
- <SectionTitle>Script</SectionTitle>
+ <SectionTitle>{t("script")}</SectionTitle>
<div className="relative rounded-lg border border-input focus-within:border-ring">
<textarea
className="voice-script min-h-[88px] w-full resize-y rounded-lg bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
- placeholder="What should the voice say?"
+ placeholder={t("scriptPlaceholder")}
value={script}
onChange={(e) => setScript(e.target.value)}
/>
@@ -494,16 +510,16 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
<Button
className="voice-generate w-full"
disabled={!script.trim() || signedOut}
- title={!script.trim() ? "Write a script above to generate" : undefined}
+ title={!script.trim() ? t("writeScriptToGenerate") : undefined}
onClick={() => void generate()}
>
<AudioLines data-icon="inline-start" />
- Generate audio
+ {t("generateAudio")}
</Button>
{pending > 0 && (
<div className="flex items-center gap-2 text-[11px] text-muted-foreground">
<Loader2 className="size-3.5 shrink-0 animate-spin" />
- {pending === 1 ? "Generating…" : `Generating ${pending}…`}
+ {t("generating", { count: pending })}
<LiveElapsed />
</div>
)}
@@ -511,11 +527,13 @@ function VoiceGenerator({ projectId }: { projectId: string }) {
{signedOut ? (
<p className="voice-signin text-[11px] leading-relaxed text-muted-foreground">
- Voiceovers run on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("voiceSignIn", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
) : (
error && (
@@ -631,6 +649,7 @@ export function AudioCardFace({
* take its corner). */
durationClassName?: string | false;
}) {
+ const t = useTranslations("panels.audio");
const playing = usePreviewAudio((s) => s.url) === url;
useEffect(() => () => usePreviewAudio.getState().stop(url), [url]);
return (
@@ -641,8 +660,8 @@ export function AudioCardFace({
/>
<button
type="button"
- title={playing ? "Pause" : "Play"}
- aria-label={playing ? "Pause" : "Play"}
+ title={playing ? t("pause") : t("play")}
+ aria-label={playing ? t("pause") : t("play")}
className="absolute bottom-2 left-2 grid size-8 place-items-center rounded-full bg-[#e3f2e8] text-[#0F6E56] shadow transition-transform hover:scale-105"
onClick={(e) => {
e.stopPropagation();
@@ -746,6 +765,7 @@ export function AudioRow({
}) {
// A row inside a registered card (the chat's audio cards) registers
// nothing of its own, so the card's copy still answers over it.
+ const t = useTranslations("panels.audio");
const copyRef = useRefCopy(refs ?? NO_REFS);
return (
<AudioPillSurface
@@ -769,7 +789,7 @@ export function AudioRow({
})
}
onDragEnd={onDragStart ? clearAssetDrag : undefined}
- title={onDragStart ? "Drag onto the timeline, or click + to add" : undefined}
+ title={onDragStart ? t("dragOrAdd") : undefined}
>
{/* Scrim so the name reads over the white waveform, not just the text-shadow. */}
<div
@@ -788,8 +808,8 @@ export function AudioRow({
"absolute top-1/2 left-1.5 grid size-6 shrink-0 -translate-y-1/2 place-items-center rounded-full transition-colors",
playing ? "bg-white text-emerald-600" : "bg-black/30 text-white hover:bg-black/50"
)}
- title={playing ? "Pause" : "Play"}
- aria-label={playing ? "Pause" : "Play"}
+ title={playing ? t("pause") : t("play")}
+ aria-label={playing ? t("pause") : t("play")}
onClick={() => onTogglePlay(url)}
>
{playing ? <Pause className="size-3" /> : <Play className="size-3" />}
@@ -803,8 +823,8 @@ export function AudioRow({
{menu}
<button
type="button"
- title="Add at the playhead"
- aria-label="Add at the playhead"
+ title={t("addAtPlayhead")}
+ aria-label={t("addAtPlayhead")}
className={scrimIconButton}
onClick={onAdd}
>
@@ -834,12 +854,13 @@ function ProjectAudio({
const assets = useEditor((s) => s.assets);
const audio = assets.filter((a) => a.type === "audio" && a.origin === "voiceover");
const pulsing = useGenNotify((s) => s.pulsing.audio);
+ const t = useTranslations("panels.audio");
return (
<div className="flex flex-col gap-1.5">
- <SectionTitle>Generated audio</SectionTitle>
+ <SectionTitle>{t("generatedAudio")}</SectionTitle>
{audio.length === 0 && !importing && (
<p className="text-[11px] leading-relaxed text-muted-foreground">
- No generated audio yet — write a script above and generate one.
+ {t("noGeneratedAudio")}
</p>
)}
<div className="flex flex-col gap-1.5">
@@ -865,7 +886,7 @@ function ProjectAudio({
variant="destructive"
onClick={() => useEditor.getState().removeAsset(a.id)}
>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
}
/>
@@ -875,7 +896,7 @@ function ProjectAudio({
))}
{importing && (
<div className="flex items-center gap-2 rounded-lg border border-dashed border-input px-2.5 py-2 text-[11px] text-muted-foreground">
- <Loader2 className="size-3.5 animate-spin" /> Importing… <LiveElapsed />
+ <Loader2 className="size-3.5 animate-spin" /> {t("importing")} <LiveElapsed />
</div>
)}
</div>
@@ -897,12 +918,13 @@ function ProjectMusic({
// non-null origin keeps them out of the Media panel.
const audio = assets.filter((a) => a.type === "audio" && a.origin === "generated");
const pulsing = useGenNotify((s) => s.pulsing.audio);
+ const t = useTranslations("panels.audio");
return (
<div className="flex flex-col gap-1.5">
- <SectionTitle>Generated music</SectionTitle>
+ <SectionTitle>{t("generatedMusic")}</SectionTitle>
{audio.length === 0 && (
<p className="text-[11px] leading-relaxed text-muted-foreground">
- No generated music yet — describe a mood above and generate one.
+ {t("noGeneratedMusic")}
</p>
)}
<div className="flex flex-col gap-1.5">
@@ -928,7 +950,7 @@ function ProjectMusic({
variant="destructive"
onClick={() => useEditor.getState().removeAsset(a.id)}
>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
}
/>
diff --git a/site/src/cut/components/CameraCardSection.tsx b/site/src/cut/components/CameraCardSection.tsx
index 34975f97..e3b9bb65 100644
--- a/site/src/cut/components/CameraCardSection.tsx
+++ b/site/src/cut/components/CameraCardSection.tsx
@@ -1,5 +1,7 @@
"use client";
+import { useTranslations } from "next-intl";
+
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -28,10 +30,10 @@ import { frameOf, rectOf, type VideoClip } from "@/cut/lib/types";
import { ResetButton, Row, Section, useSliderCheckpoint } from "@/cut/components/panelBits";
import { parseNumberInput, parsePercentInput, ScrubValue } from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
+import { useDescribeError } from "@/i18n/describeError";
const formatPercent = (v: number) => `${Math.round(v * 100)}%`;
const formatPx = (v: number) => String(Math.round(v));
-const SIDE_LABELS: Record<CardSide, string> = { bottom: "Bottom", left: "Left", right: "Right" };
/**
* The camera card: the talking-head split layout on one clip, in any frame
@@ -43,6 +45,8 @@ const SIDE_LABELS: Record<CardSide, string> = { bottom: "Bottom", left: "Left",
* through the transient updater under one checkpoint per gesture.
*/
export function CameraCardSection({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("editor.cameraCard");
+ const describeError = useDescribeError();
const card = clip.card;
const st = () => useEditor.getState();
const ck = useSliderCheckpoint();
@@ -68,10 +72,10 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
min: number,
max: number,
snap?: number[],
- reset?: { show: boolean; onClick: () => void }
+ reset?: { show: boolean; onClick: () => void; title: string }
) => (
<Row label={label}>
- {reset && <ResetButton title={`Reset ${label.toLowerCase()}`} show={reset.show} onClick={reset.onClick} />}
+ {reset && <ResetButton title={reset.title} show={reset.show} onClick={reset.onClick} />}
<ValueSlider
label={label}
sliderClassName="data-horizontal:w-24"
@@ -117,31 +121,37 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
const shape = card
? resolveCardShape(card, rect.w * fr.w, rect.h * fr.h, asset?.width ?? 0, asset?.height ?? 0)
: null;
+ // The side names, keyed by side; auto names the side it resolved to.
+ const sideLabels: Record<CardSide, string> = {
+ bottom: t("side.bottom"),
+ left: t("side.left"),
+ right: t("side.right"),
+ };
const sideItems = {
- auto: `Auto (${SIDE_LABELS[shape?.side ?? "bottom"]})`,
- ...SIDE_LABELS,
+ auto: t("side.auto", { side: sideLabels[shape?.side ?? "bottom"] }),
+ ...sideLabels,
};
const matteLine = !card?.popOut
? null
: card.matte
- ? "Person matte ready"
+ ? t("matteReady")
: job?.status === "running"
- ? `Person matte baking ${Math.round(job.progress * 100)}%`
+ ? t("matteBaking", { progress: job.progress })
: job?.status === "error"
- ? (job.error ?? "The person matte could not be baked.")
- : "Person matte starting";
+ ? describeError(job, t("matteFailed"))
+ : t("matteStarting");
return (
<Section
- title="Camera card"
- info="The speaker shows through a rounded card at the edge of the frame, and their head pops out above it. Auto puts the card across the bottom of a portrait frame and up the right side of a square or landscape one. Put the graphic on a lower track. The card places the footage and draws its own corners and shadow, so framing zoom, pan, border and shadow stand aside while it is on. Lengths are design pixels."
+ title={t("title")}
+ info={t("info")}
enabled={!!card}
onEnabledChange={(v) => st().updateClip(clip.id, { card: v ? newCard() : undefined })}
>
{card && shape && (
<>
- <Row label="Side">
+ <Row label={t("sideLabel")}>
<Select
value={card.side ?? "auto"}
items={sideItems}
@@ -168,32 +178,34 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
</SelectContent>
</Select>
</Row>
- {slider("Top", "top", shape.top, CARD_TOP_MIN, CARD_TOP_MAX, undefined, {
+ {slider(t("top"), "top", shape.top, CARD_TOP_MIN, CARD_TOP_MAX, undefined, {
+ title: t("resetTop"),
show: card.top !== undefined,
onClick: () => st().updateClip(clip.id, { card: { ...card, top: undefined } }),
})}
{shape.side !== "bottom" &&
- slider("Width", "width", shape.width, CARD_WIDTH_MIN, CARD_WIDTH_MAX, undefined, {
+ slider(t("width"), "width", shape.width, CARD_WIDTH_MIN, CARD_WIDTH_MAX, undefined, {
+ title: t("resetWidth"),
show: card.width !== undefined,
onClick: () => st().updateClip(clip.id, { card: { ...card, width: undefined } }),
})}
- <Row label="Radius">
- {scrub("Card radius", "radius", card.radius, 0, CARD_RADIUS_MAX, 1, formatPx, parseNumberInput)}
+ <Row label={t("radius")}>
+ {scrub(t("cardRadius"), "radius", card.radius, 0, CARD_RADIUS_MAX, 1, formatPx, parseNumberInput)}
</Row>
- <Row label="Side bleed">
- {scrub("Card side bleed", "sideBleed", card.sideBleed, 0, CARD_BLEED_MAX, 1, formatPx, parseNumberInput)}
+ <Row label={t("sideBleed")}>
+ {scrub(t("cardSideBleed"), "sideBleed", card.sideBleed, 0, CARD_BLEED_MAX, 1, formatPx, parseNumberInput)}
</Row>
- {slider("Shadow", "shadow", card.shadow, 0, 1)}
- <Row label="Pop out">
+ {slider(t("shadow"), "shadow", card.shadow, 0, 1)}
+ <Row label={t("popOut")}>
<Switch
- aria-label="Pop out"
+ aria-label={t("popOut")}
checked={card.popOut}
onCheckedChange={(popOut) => st().updateClip(clip.id, { card: { ...card, popOut } })}
/>
</Row>
{card.popOut && (
- <Row label="Feather">
- {scrub("Pop out feather", "feather", card.feather, 0, CARD_FEATHER_MAX, 1, formatPx, parseNumberInput)}
+ <Row label={t("feather")}>
+ {scrub(t("popOutFeather"), "feather", card.feather, 0, CARD_FEATHER_MAX, 1, formatPx, parseNumberInput)}
</Row>
)}
{matteLine && (
@@ -201,13 +213,13 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
<span className="truncate">{matteLine}</span>
{job?.status === "error" && (
<Button size="sm" variant="outline" onClick={() => retryCardMatte(clip.id)}>
- Retry
+ {t("retry")}
</Button>
)}
</div>
)}
- {slider("Footage size", "scale", card.scale ?? 1, CARD_SCALE_MIN, CARD_SCALE_MAX, [1])}
- <Row label="Footage offset">
+ {slider(t("footageSize"), "scale", card.scale ?? 1, CARD_SCALE_MIN, CARD_SCALE_MAX, [1])}
+ <Row label={t("footageOffset")}>
{(
[
["X", "offsetX", card.offsetX ?? 0],
@@ -216,7 +228,7 @@ export function CameraCardSection({ clip }: { clip: VideoClip }) {
).map(([axis, key, value]) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
- {scrub(`Footage ${axis} offset`, key, value, -CARD_OFFSET_MAX, CARD_OFFSET_MAX, 0.01, formatPercent, parsePercentInput)}
+ {scrub(t("footageAxisOffset", { axis }), key, value, -CARD_OFFSET_MAX, CARD_OFFSET_MAX, 0.01, formatPercent, parsePercentInput)}
</span>
))}
</Row>
diff --git a/site/src/cut/components/CameraRollView.tsx b/site/src/cut/components/CameraRollView.tsx
index 300abcef..3735301b 100644
--- a/site/src/cut/components/CameraRollView.tsx
+++ b/site/src/cut/components/CameraRollView.tsx
@@ -3,6 +3,7 @@
import { useCallback, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Camera, Loader2, Trash2 } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { useDeleteKey } from "@/cut/hooks/useDeleteKey";
import { useTabTitle } from "@/cut/hooks/useTabTitle";
@@ -16,7 +17,7 @@ import { formatDate } from "@/cut/lib/time";
import { shapeBand } from "@/cut/lib/types";
import { Marquee, useTilePicks } from "./desktopFolders";
import { Lightbox } from "./Lightbox";
-import { DeleteConfirm, SelectionMenu, pickLabel, useSelectionMenu } from "./selectionMenu";
+import { DeleteConfirm, SelectionMenu, usePickWords, useSelectionMenu } from "./selectionMenu";
import { LibraryCard } from "@/cut/components/LibraryCard";
/** The phone's recordings, synced up from the iOS app: every cloud library
@@ -27,6 +28,9 @@ import { LibraryCard } from "@/cut/components/LibraryCard";
* itself off what is said in it. Pruning picks the way every tile grid does:
* click, ⌘ and ⇧ clicks, a sweep, then ⌫ or the right-click menu. */
export function CameraRollView() {
+ const t = useTranslations("home");
+ const locale = useLocale();
+ const { pickLabel } = usePickWords();
const client = useQueryClient();
// The phone fills this page, so it re-reads on a timer and whenever the
// window comes back to the front: a clip finishes uploading and takes its
@@ -41,7 +45,7 @@ export function CameraRollView() {
[client]
);
useClipTitles(clips, patch);
- useTabTitle("Camera Roll");
+ useTabTitle(t("tabs.cameraRoll"));
const remove = async (set: LibraryAsset[]) => {
setDeleting(null);
@@ -89,7 +93,7 @@ export function CameraRollView() {
onContextMenu={ctx.onContextMenu}
>
<div className="mb-5 flex items-center justify-between gap-4">
- <h1 className="text-lg font-semibold tracking-tight">Camera Roll</h1>
+ <h1 className="text-lg font-semibold tracking-tight">{t("tabs.cameraRoll")}</h1>
</div>
{!library.data && library.isPending ? (
@@ -100,9 +104,9 @@ export function CameraRollView() {
<div className="grid w-full place-items-center rounded-2xl py-24">
<div className="flex flex-col items-center gap-3 text-center">
<Camera className="size-8 text-muted-foreground" />
- <div className="text-base font-medium">Nothing from your phone yet.</div>
+ <div className="text-base font-medium">{t("cameraRoll.emptyTitle")}</div>
<p className="text-sm text-muted-foreground">
- Clips you record in the Donkey Cut iOS app sync here automatically.
+ {t("cameraRoll.emptyHint")}
</p>
</div>
</div>
@@ -119,7 +123,7 @@ export function CameraRollView() {
key={a.id}
asset={a}
area={TILE_AREA}
- caption={formatDate(a.addedAt)}
+ caption={formatDate(a.addedAt, locale, t("justNow"))}
selected={selected.has(a.id)}
dragGroup={pick}
onClick={(e) => {
@@ -140,7 +144,7 @@ export function CameraRollView() {
<SelectionMenu menu={ctxSet.length > 0 ? ctx.menu : null} onClose={ctx.close}>
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
- <Trash2 /> Delete
+ <Trash2 /> {t("cameraRoll.delete")}
</DropdownMenuItem>
</SelectionMenu>
@@ -148,14 +152,10 @@ export function CameraRollView() {
open={!!deleting}
title={
deleting
- ? `Delete ${pickLabel([], deleting.map((a) => ({ name: a.title || a.name })), ["clip", "clips"], 0)}?`
+ ? t("cameraRoll.deleteTitle", { what: pickLabel([], deleting.map((a) => ({ name: a.title || a.name })), "clip", 0) })
: ""
}
- description={
- deleting?.length === 1
- ? "The clip leaves your cloud Camera Roll and the phone it was shot on. Projects that already use it keep their own copy."
- : "The clips leave your cloud Camera Roll and the phone they were shot on. Projects that already use them keep their own copy."
- }
+ description={t("cameraRoll.deleteBody", { count: deleting?.length ?? 0 })}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && void remove(deleting)}
/>
diff --git a/site/src/cut/components/CardActionsMenu.tsx b/site/src/cut/components/CardActionsMenu.tsx
index c02a8ba0..f1465760 100644
--- a/site/src/cut/components/CardActionsMenu.tsx
+++ b/site/src/cut/components/CardActionsMenu.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from "react";
import { Download, Ellipsis, ExternalLink, Pencil, Plus, Share2, Trash2 } from "lucide-react";
+import { useTranslations } from "next-intl";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
@@ -10,12 +11,12 @@ import { cn } from "@/lib/utils";
* readable behind it. Each action shows when its handler is given, always in
* the same order. */
export function CardActionsMenu({
- label = "More actions",
+ label,
icon,
sheet = false,
className,
onUse,
- useTitle = "Add to timeline",
+ useTitle,
onShare,
shareDisabled,
onRename,
@@ -46,12 +47,13 @@ export function CardActionsMenu({
extra?: ReactNode;
onDelete?: () => void;
}) {
+ const t = useTranslations("home.cardMenu");
const middle = !!(onShare || onRename || onDownload || downloadHref || onOpenOriginal || extra);
if (!onUse && !middle && !onDelete) return null;
return (
<DropdownMenu>
<DropdownMenuTrigger
- aria-label={label}
+ aria-label={label ?? t("moreActions")}
className={cn(
"grid size-6 place-items-center rounded-full text-white opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
sheet ? "bg-white/10 hover:bg-white/20" : "bg-black/40 hover:bg-black/60",
@@ -70,35 +72,35 @@ export function CardActionsMenu({
{onUse && (
<>
<DropdownMenuItem onClick={onUse}>
- <Plus /> {useTitle}
+ <Plus /> {useTitle ?? t("addToTimeline")}
</DropdownMenuItem>
{(middle || onDelete) && <DropdownMenuSeparator />}
</>
)}
{onShare && (
<DropdownMenuItem disabled={shareDisabled} onClick={onShare}>
- <Share2 /> Share
+ <Share2 /> {t("share")}
</DropdownMenuItem>
)}
{onRename && (
<DropdownMenuItem onClick={onRename}>
- <Pencil /> Rename
+ <Pencil /> {t("rename")}
</DropdownMenuItem>
)}
{downloadHref ? (
<DropdownMenuItem render={<a href={downloadHref} />}>
- <Download /> Download
+ <Download /> {t("download")}
</DropdownMenuItem>
) : onDownload ? (
<DropdownMenuItem disabled={downloadDisabled} onClick={onDownload}>
- <Download /> Download
+ <Download /> {t("download")}
</DropdownMenuItem>
) : null}
{onOpenOriginal && (
// An imported clip keeps the link it came from, so the post it was
// cut out of is one click away.
<DropdownMenuItem onClick={onOpenOriginal}>
- <ExternalLink /> Open original
+ <ExternalLink /> {t("openOriginal")}
</DropdownMenuItem>
)}
{extra}
@@ -106,7 +108,7 @@ export function CardActionsMenu({
<>
{middle && <DropdownMenuSeparator />}
<DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
</>
)}
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsx
index d8070c48..82dcca89 100644
--- a/site/src/cut/components/ChatAssets.tsx
+++ b/site/src/cut/components/ChatAssets.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState, type ReactNode } from "react";
import type React from "react";
+import { useTranslations } from "next-intl";
import { Copy, ExternalLink, FileText, Film, Loader2, Maximize2, Plus } from "lucide-react";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
@@ -132,6 +133,7 @@ type RenderView = Pick<GenerateJob, "status" | "prompt" | "startedAt" | "error"
* job store covers this browser; the doc-mirrored record carries the same
* card to every other browser and machine. */
export function ChatVideoJobCard({ jobId }: { jobId: string }) {
+ const t = useTranslations("chat.chatAssets");
const job = useGenerate((s) => s.jobs.find((j) => j.id === jobId));
const record = useEditor((s) => s.renders.find((r) => r.id === jobId));
const readOnly = useEditor((s) => s.readOnly);
@@ -142,7 +144,7 @@ export function ChatVideoJobCard({ jobId }: { jobId: string }) {
job ??
(record &&
(record.status === "running" && now - record.startedAt > RECORD_RUNNING_TTL_MS
- ? { ...record, status: "error" as const, error: "The render was interrupted." }
+ ? { ...record, status: "error" as const, error: t("renderInterrupted") }
: record));
const elapsed = useElapsed(view?.status === "running" ? view.startedAt : null);
if (!view) return null;
@@ -167,11 +169,11 @@ export function ChatVideoJobCard({ jobId }: { jobId: string }) {
>
{view.status === "running" ? (
<>
- Rendering…{" "}
+ {t("rendering")}{" "}
{elapsed && <span className="tabular-nums text-muted-foreground/80">{elapsed}</span>}
</>
) : (
- <HostedErrorText error={view.error} link={false} />
+ <HostedErrorText error={view} link={false} />
)}
</div>
{/* Retry needs the job's stored ladder, which lives in this browser's
@@ -183,7 +185,7 @@ export function ChatVideoJobCard({ jobId }: { jobId: string }) {
className="self-start text-[10.5px] font-medium underline underline-offset-2 hover:no-underline"
onClick={() => useGenerate.getState().retry(job.id)}
>
- Retry
+ {t("retry")}
</button>
)}
</div>
@@ -215,6 +217,7 @@ const dragProps = (item: AssetRef, asset?: MediaAsset) => ({
/** The chat card's "…" menu: timeline/expand/reference actions around the
* shared move-to-Media/Library pair. Project assets only. */
function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerClassName: string }) {
+ const t = useTranslations("chat.chatAssets");
const projectId = useEditor((s) => s.projectId);
if (!projectId) return null;
return (
@@ -227,21 +230,21 @@ function ChatCardMenu({ asset, triggerClassName }: { asset: MediaAsset; triggerC
<DropdownMenuItem
onClick={() => useEditor.getState().addAssetAtPlayhead(asset.id)}
>
- <Plus /> Add to timeline
+ <Plus /> {t("addToTimeline")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => expandRef(refFromAsset(asset))}>
- <Maximize2 /> Expand
+ <Maximize2 /> {t("expand")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => copyRefs([refFromAsset(asset)])}
>
- <Copy /> Copy reference
+ <Copy /> {t("copyReference")}
</DropdownMenuItem>
</>
}
after={
<DropdownMenuItem onClick={() => window.open(asset.url, "_blank", "noopener")}>
- <ExternalLink /> Open file
+ <ExternalLink /> {t("openFile")}
</DropdownMenuItem>
}
/>
@@ -253,6 +256,7 @@ const scrimButton = scrimIconButton;
/** Image / video tile: the preview fills the card at the media's own aspect,
* sized so portrait and landscape both sit comfortably in the chat column. */
function MediaCard({ item, asset }: ChatCardProps) {
+ const t = useTranslations("chat.chatAssets");
const { ref: videoRef, handlers: hoverPlay } = useHoverPlay();
// Chat scrollback holds every card ever made; media loads only once the
// card actually scrolls into view.
@@ -278,7 +282,7 @@ function MediaCard({ item, asset }: ChatCardProps) {
onClick={(e) => {
if (!(e.target as Element).closest("button")) pick();
}}
- title={`${ref.name} — double-click to expand · drag to the timeline`}
+ title={t("mediaHint", { name: ref.name })}
{...dragProps(item, asset)}
onDoubleClick={() => expandRef(item, asset)}
{...(item.kind === "video" ? hoverPlay : {})}
@@ -307,7 +311,7 @@ function MediaCard({ item, asset }: ChatCardProps) {
<span className="block truncate text-[10.5px] font-medium text-white">{ref.name}</span>
</div>
<div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover/card:opacity-100 has-data-popup-open:opacity-100">
- <button title="Expand" className={scrimButton} onClick={() => expandRef(item, asset)}>
+ <button title={t("expand")} className={scrimButton} onClick={() => expandRef(item, asset)}>
<Maximize2 className="size-3" />
</button>
{asset && <ChatCardMenu asset={asset} triggerClassName={scrimButton} />}
@@ -361,6 +365,7 @@ const DOC_PREVIEW_CHARS = 1200;
/** A text file (markdown, CSV, plain) as a clipped document card. */
function DocCard({ item, asset }: ChatCardProps) {
+ const t = useTranslations("chat.chatAssets");
const { text, failed } = useDocText(item.url);
const clipped = text !== null && text.length > DOC_PREVIEW_CHARS;
const { picked, pick } = useAssetPick(item.id);
@@ -375,7 +380,7 @@ function DocCard({ item, asset }: ChatCardProps) {
onClick={(e) => {
if (!(e.target as Element).closest("button")) pick();
}}
- title={`${item.name} — double-click to expand`}
+ title={t("docHint", { name: item.name })}
{...dragProps(item, asset)}
onDoubleClick={() => expandRef(item, asset)}
>
@@ -383,7 +388,7 @@ function DocCard({ item, asset }: ChatCardProps) {
<FileText className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-[11px] font-medium">{item.name}</span>
<button
- title="Expand"
+ title={t("expand")}
className={cn(scrimButton, "opacity-0 transition-opacity group-hover/card:opacity-100")}
onClick={() => expandRef(item, asset)}
>
@@ -392,7 +397,7 @@ function DocCard({ item, asset }: ChatCardProps) {
</div>
<div className="relative max-h-44 overflow-hidden px-2.5 py-2 text-[11px] leading-relaxed">
{failed ? (
- <p className="text-muted-foreground">Could not read the file.</p>
+ <p className="text-muted-foreground">{t("readFailed")}</p>
) : text === null ? (
<Loader2 className="size-3.5 animate-spin text-muted-foreground" />
) : (
diff --git a/site/src/cut/components/ChatStatusBadge.tsx b/site/src/cut/components/ChatStatusBadge.tsx
index 6bccc710..e54f4620 100644
--- a/site/src/cut/components/ChatStatusBadge.tsx
+++ b/site/src/cut/components/ChatStatusBadge.tsx
@@ -1,4 +1,5 @@
import { CircleDashed } from "lucide-react";
+import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
@@ -7,6 +8,7 @@ export type ChatStatus = "working" | "unread" | null;
/** The corner mark on whatever opens the chat. `className` carries the surface
* it sits on, so the halo behind the dot matches the button's background. */
export function ChatStatusBadge({ status, className }: { status: ChatStatus; className?: string }) {
+ const t = useTranslations("chat.statusBadge");
if (!status) return null;
return (
<span
@@ -16,9 +18,9 @@ export function ChatStatusBadge({ status, className }: { status: ChatStatus; cla
)}
>
{status === "working" ? (
- <CircleDashed role="img" aria-label="Chat working" className="size-3! animate-spin text-muted-foreground" />
+ <CircleDashed role="img" aria-label={t("working")} className="size-3! animate-spin text-muted-foreground" />
) : (
- <span role="img" aria-label="Unread chat reply" className="size-2 rounded-full bg-blue-500" />
+ <span role="img" aria-label={t("unread")} className="size-2 rounded-full bg-blue-500" />
)}
</span>
);
diff --git a/site/src/cut/components/ClaimCreditsDialog.tsx b/site/src/cut/components/ClaimCreditsDialog.tsx
index 98cc3ec8..2b89aba2 100644
--- a/site/src/cut/components/ClaimCreditsDialog.tsx
+++ b/site/src/cut/components/ClaimCreditsDialog.tsx
@@ -12,11 +12,12 @@
// the press starts the Pro checkout, which carries the offer to the webhook.
import { useSearchParams } from "next/navigation";
import { Loader2 } from "lucide-react";
+import { useFormatter, useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
-import { claimOfferCopy, OfferButton, OfferDialog, OfferDismiss, subscribeOfferCopy } from "@/cut/components/OfferDialog";
+import { OfferButton, OfferDialog, OfferDismiss, useOfferCopy } from "@/cut/components/OfferDialog";
import { useEngineUser } from "@/cut/lib/backend/hooks";
import { track } from "@/lib/analytics";
-import { formatCreditExpiry } from "@/lib/credits/top-up";
+import { formatCredits } from "@/lib/credits/format-credits";
import { ApiError } from "@/queries/apiClient";
import { useStartCheckout } from "@/queries/billing";
import { useClaimCreditOffer, useCreditOffer } from "@/queries/credits";
@@ -55,6 +56,10 @@ function AddressedDialog() {
}
function OpenDialog({ token, onClose }: { token: string; onClose: () => void }) {
+ const t = useTranslations("billing");
+ const format = useFormatter();
+ const locale = useLocale();
+ const { claimOfferCopy, subscribeOfferCopy } = useOfferCopy();
const offer = useCreditOffer(token);
const claim = useClaimCreditOffer();
const checkout = useStartCheckout();
@@ -78,64 +83,72 @@ function OpenDialog({ token, onClose }: { token: string; onClose: () => void })
let body: React.ReactNode;
let terms: React.ReactNode = null;
let cta: React.ReactNode;
- let secondary: React.ReactNode = <OfferDismiss onClick={onClose}>Not now</OfferDismiss>;
+ let secondary: React.ReactNode = <OfferDismiss onClick={onClose}>{t("notNow")}</OfferDismiss>;
+ // The amount in the page's language, from the offer's dollars.
+ const credits = offer.data ? formatCredits(offer.data.dollars, locale) : "";
if (offer.isError) {
const status = offer.error instanceof ApiError ? offer.error.status : null;
title =
- status === 410 ? "This offer has expired" : status === 409 ? "You already have Pro" : "This link is no longer valid";
+ status === 410
+ ? t("claim.expiredTitle")
+ : status === 409
+ ? t("claim.alreadyProTitle")
+ : t("claim.invalidTitle");
body =
status === 403
- ? "This offer belongs to a different account. Sign in with the address the email was sent to."
+ ? t("claim.wrongAccount")
: status === 410
- ? "The claim window for this offer has closed."
+ ? t("claim.windowClosed")
: status === 409
- ? "This offer is for accounts without a Pro subscription."
- : "The offer it pointed to is gone.";
- cta = <OfferButton onClick={onClose}>OK</OfferButton>;
+ ? t("claim.proOnly")
+ : t("claim.gone");
+ cta = <OfferButton onClick={onClose}>{t("ok")}</OfferButton>;
secondary = null;
} else if (done) {
- title = `${offer.data.credits} added to your account`;
- body = `They’re ready to spend.${
- done.expiresAt ? ` They expire ${formatCreditExpiry(new Date(done.expiresAt))}.` : ""
- }`;
- cta = <OfferButton onClick={onClose}>Start editing</OfferButton>;
+ title = t("claim.addedTitle", { credits });
+ body = done.expiresAt
+ ? t("claim.readyExpires", {
+ date: format.dateTime(new Date(done.expiresAt), { day: "numeric", month: "long", year: "numeric" }),
+ })
+ : t("claim.ready");
+ cta = <OfferButton onClick={onClose}>{t("claim.startEditing")}</OfferButton>;
secondary = null;
} else if (offer.data.claim === "subscribe") {
- title = `Get ${offer.data.credits} with Pro`;
+ title = t("claim.withProTitle", { credits });
({ body, terms } = subscribeOfferCopy({
- credits: offer.data.credits,
+ credits,
expiresAt: null,
lifetimeDays: offer.data.lifetimeDays,
}));
cta = (
<OfferButton disabled={checkout.isPending} onClick={subscribe}>
{checkout.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Subscribe to Pro
+ {t("subscribeToPro")}
</OfferButton>
);
} else {
- title = `${offer.data.credits} are waiting`;
+ title = t("claim.waitingTitle", { credits });
({ body, terms } = claimOfferCopy({
- credits: offer.data.credits,
+ credits,
closesAt: offer.data.closesAt,
lifetimeDays: offer.data.lifetimeDays,
}));
cta = (
<OfferButton disabled={claim.isPending} onClick={() => claim.mutate(token)}>
{claim.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Claim {offer.data.credits}
+ {t("claim.claimButton", { credits })}
</OfferButton>
);
}
const error = checkout.isError
- ? "Billing is unavailable right now."
+ ? t("billingUnavailable")
: claim.isError
? claim.error instanceof ApiError && claim.error.status === 403
- ? "This offer belongs to a different account. Sign in with the address the email was sent to."
+ ? t("claim.wrongAccount")
: claim.error instanceof ApiError && claim.error.status === 410
- ? "The claim window for this offer has closed."
- : "That didn’t go through. Try again."
+ ? t("claim.windowClosed")
+ : t("claim.failed")
: null;
return (
diff --git a/site/src/cut/components/ClipEffectsSection.tsx b/site/src/cut/components/ClipEffectsSection.tsx
index 13f22e38..8f96cb89 100644
--- a/site/src/cut/components/ClipEffectsSection.tsx
+++ b/site/src/cut/components/ClipEffectsSection.tsx
@@ -1,11 +1,11 @@
"use client";
import { X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Fragment } from "react";
import {
AMOUNTLESS_EFFECTS,
CLIP_EFFECT_IDS,
- EFFECT_LABELS,
type ClipEffect,
type ClipEffectId,
} from "@donkeycut/effects-kit";
@@ -17,6 +17,7 @@ import { parsePercentInput } from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
import { useEditor } from "@/cut/lib/store";
import type { VideoClip } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
/**
* The effects a clip wears: each treats this clip's picture alone, inside its
@@ -25,6 +26,8 @@ import type { VideoClip } from "@/cut/lib/types";
* writes.
*/
export function ClipEffectsSection({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.clipEffects");
+ const effectLabel = useLabels("effect");
const ck = useSliderCheckpoint();
const list = clip.effects ?? [];
const st = () => useEditor.getState();
@@ -52,24 +55,24 @@ export function ClipEffectsSection({ clip }: { clip: VideoClip }) {
return (
<Section
- title="Effects"
- info="Each effect treats this clip's picture alone, inside its mask, for the clip's whole length. An effect from the Effects tab treats the whole frame under its window."
+ title={t("title")}
+ info={t("info")}
aside={
free.length > 0 && (
<Select
value={null}
- items={Object.fromEntries(free.map((id) => [id, EFFECT_LABELS[id]]))}
+ items={Object.fromEntries(free.map((id) => [id, effectLabel(id)]))}
onValueChange={(v) => {
if (v) write([...list, { effect: v as ClipEffectId }]);
}}
>
<SelectTrigger className="h-7 w-28 text-[12px]">
- <SelectValue placeholder="Add effect" />
+ <SelectValue placeholder={t("add")} />
</SelectTrigger>
<SelectContent>
{free.map((id) => (
<SelectItem key={id} value={id} className="text-[12px]">
- {EFFECT_LABELS[id]}
+ {effectLabel(id)}
</SelectItem>
))}
</SelectContent>
@@ -79,10 +82,10 @@ export function ClipEffectsSection({ clip }: { clip: VideoClip }) {
>
{list.map((e, i) => (
<Fragment key={e.effect}>
- <Row label={EFFECT_LABELS[e.effect]}>
+ <Row label={effectLabel(e.effect)}>
{!AMOUNTLESS_EFFECTS.includes(e.effect) && (
<ValueSlider
- label={`${EFFECT_LABELS[e.effect]} amount`}
+ label={t("amount", { effect: effectLabel(e.effect) })}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={e.amount ?? 0.5}
@@ -101,13 +104,13 @@ export function ClipEffectsSection({ clip }: { clip: VideoClip }) {
)}
<Tooltip>
<TooltipTrigger
- aria-label={`Remove ${EFFECT_LABELS[e.effect]}`}
+ aria-label={t("removeEffect", { effect: effectLabel(e.effect) })}
className="grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={() => write(list.filter((_, j) => j !== i))}
>
<X className="size-3.5" />
</TooltipTrigger>
- <TooltipContent>Remove</TooltipContent>
+ <TooltipContent>{t("remove")}</TooltipContent>
</Tooltip>
</Row>
{e.effect === "flash" && <FlashPulseRows pulse={e} write={(patch, how) => setPulse(i, patch, how)} />}
diff --git a/site/src/cut/components/ColorField.tsx b/site/src/cut/components/ColorField.tsx
index 5f81d037..feea612d 100644
--- a/site/src/cut/components/ColorField.tsx
+++ b/site/src/cut/components/ColorField.tsx
@@ -1,24 +1,28 @@
"use client";
+import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { Check, Pipette } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { parsePercentInput, ScrubValue } from "@/cut/components/ScrubValue";
import { cn } from "@/lib/utils";
-/** The named colors every color field offers. */
-export const COLOR_PRESETS: { hex: string; name: string }[] = [
- { hex: "#FFFFFF", name: "White" },
- { hex: "#111114", name: "Black" },
- { hex: "#8E8E93", name: "Grey" },
- { hex: "#FF375F", name: "Red" },
- { hex: "#FF9F0A", name: "Orange" },
- { hex: "#FFD60A", name: "Yellow" },
- { hex: "#30D158", name: "Green" },
- { hex: "#0A84FF", name: "Blue" },
- { hex: "#BF5AF2", name: "Purple" },
+/** The named colors every color field offers. The UI names each by `id`
+ * under `inspector.colorField.presets`. */
+export const COLOR_PRESETS: { id: ColorPresetId; hex: string; name: string }[] = [
+ { id: "white", hex: "#FFFFFF", name: "White" },
+ { id: "black", hex: "#111114", name: "Black" },
+ { id: "grey", hex: "#8E8E93", name: "Grey" },
+ { id: "red", hex: "#FF375F", name: "Red" },
+ { id: "orange", hex: "#FF9F0A", name: "Orange" },
+ { id: "yellow", hex: "#FFD60A", name: "Yellow" },
+ { id: "green", hex: "#30D158", name: "Green" },
+ { id: "blue", hex: "#0A84FF", name: "Blue" },
+ { id: "purple", hex: "#BF5AF2", name: "Purple" },
];
+type ColorPresetId = "white" | "black" | "grey" | "red" | "orange" | "yellow" | "green" | "blue" | "purple";
+
/** Colors the user picked by hand, newest first. */
const RECENT_COLORS_KEY = "cut-recent-colors";
const RECENT_LIMIT = 8;
@@ -107,7 +111,7 @@ export function ColorField({
onLive,
onCommit,
opacity,
- label = "Color",
+ label: labelProp,
className,
mixed,
}: {
@@ -129,6 +133,8 @@ export function ColorField({
* wheel and the readout "Mixed"; a pick lands one color on all of them. */
mixed?: boolean;
}) {
+ const t = useTranslations("inspector.colorField");
+ const label = labelProp ?? t("color");
const [pickerOpen, setPickerOpen] = useState(false);
const [listOpen, setListOpen] = useState(false);
const hex = safeHex(value);
@@ -149,8 +155,8 @@ export function ColorField({
>
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
<PopoverTrigger
- aria-label={`${label} — open the picker`}
- title="Pick a color"
+ aria-label={t("openPicker", { label })}
+ title={t("pickColor")}
className="color-field-swatch size-5 shrink-0 rounded-[5px] shadow-xs ring-1 ring-border transition-transform outline-none hover:scale-105 focus-visible:ring-2 focus-visible:ring-primary/60"
style={{ background: mixed ? "conic-gradient(#f43f5e, #f59e0b, #22c55e, #3b82f6, #a855f7, #f43f5e)" : hex }}
/>
@@ -160,10 +166,10 @@ export function ColorField({
</Popover>
<Popover open={listOpen} onOpenChange={setListOpen}>
<PopoverTrigger
- aria-label={`${label} — open the list`}
+ aria-label={t("openList", { label })}
className="color-field-value w-[7ch] shrink-0 rounded-sm text-left font-mono text-[11.5px] tabular-nums text-foreground uppercase outline-none focus-visible:ring-2 focus-visible:ring-primary/60"
>
- {mixed ? <span className="font-sans italic normal-case">Mixed</span> : hex.slice(1)}
+ {mixed ? <span className="font-sans italic normal-case">{t("mixed")}</span> : hex.slice(1)}
</PopoverTrigger>
<PopoverContent side="bottom" align="end" sideOffset={6} className="w-56 p-1">
<ColorList
@@ -212,6 +218,7 @@ export function ColorPicker({
const [pad, setPad] = useState(() => ({ hex: value, hsv: hexToHsv(value) }));
if (pad.hex !== value) setPad({ hex: value, hsv: hexToHsv(value) });
const hsv = pad.hsv;
+ const t = useTranslations("inspector.colorField");
const push = (next: Hsv) => {
const hex = hsvToHex(next);
@@ -224,7 +231,7 @@ export function ColorPicker({
return (
<div className="flex flex-col gap-2.5">
<DragArea
- label="Saturation and brightness"
+ label={t("saturationBrightness")}
className="relative h-28 w-full cursor-crosshair rounded-md ring-1 ring-border"
style={{
background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, ${hueCss})`,
@@ -236,7 +243,7 @@ export function ColorPicker({
<Handle color={value} left={hsv.s} top={1 - hsv.v} />
</DragArea>
<DragArea
- label="Hue"
+ label={t("hue")}
className="relative h-3 w-full cursor-ew-resize rounded-full ring-1 ring-border"
style={{
background:
@@ -327,9 +334,10 @@ function DragArea({
/** The presets and the user's recent picks, current value checked. */
function ColorList({ value, onPick }: { value: string; onPick: (hex: string) => void }) {
+ const t = useTranslations("inspector.colorField");
const [recents] = useState(readRecentColors);
const items = [
- ...COLOR_PRESETS,
+ ...COLOR_PRESETS.map((p) => ({ hex: p.hex, name: t(`presets.${p.id}`) })),
...recents.filter((r) => !COLOR_PRESETS.some((p) => p.hex === r)).map((hex) => ({ hex, name: hex.slice(1) })),
];
@@ -369,6 +377,7 @@ function HexInput({
autoFocus?: boolean;
className?: string;
}) {
+ const t = useTranslations("inspector.colorField");
const [entry, setEntry] = useState({ hex: value, draft: value.slice(1) });
if (entry.hex !== value) setEntry({ hex: value, draft: value.slice(1) });
const setDraft = (draft: string) => setEntry({ hex: value, draft });
@@ -391,7 +400,7 @@ function HexInput({
style={{ background: value }}
/>
<input
- aria-label="Hex color"
+ aria-label={t("hexColor")}
autoFocus={autoFocus}
value={entry.draft}
spellCheck={false}
@@ -416,13 +425,14 @@ type EyeDropperCtor = new () => { open(): Promise<{ sRGBHex: string }> };
/** Screen sampling, on the browsers that carry the EyeDropper API. */
function Eyedropper({ onPick }: { onPick: (hex: string) => void }) {
+ const t = useTranslations("inspector.colorField");
const [supported] = useState(() => typeof window !== "undefined" && "EyeDropper" in window);
if (!supported) return null;
return (
<button
type="button"
- aria-label="Sample a color from the screen"
- title="Sample a color from the screen"
+ aria-label={t("sampleScreen")}
+ title={t("sampleScreen")}
className="grid size-7 shrink-0 place-items-center rounded-md bg-secondary/60 text-muted-foreground transition-colors hover:text-foreground"
onClick={async () => {
const Ctor = (window as unknown as { EyeDropper: EyeDropperCtor }).EyeDropper;
diff --git a/site/src/cut/components/ColorPanel.tsx b/site/src/cut/components/ColorPanel.tsx
index e681647a..88ae2b23 100644
--- a/site/src/cut/components/ColorPanel.tsx
+++ b/site/src/cut/components/ColorPanel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ChevronLeft, Loader2, RotateCcw, SlidersHorizontal, Trash2, Wand2, X } from "lucide-react";
@@ -12,6 +13,7 @@ import {
GRADE_HUE_MAX,
GRADE_MAX,
GRADE_PRESET_CATEGORIES,
+ GRADE_PRESETS,
gradeCssApprox,
gradeKey,
gradePresetsInCategory,
@@ -20,7 +22,6 @@ import {
normalizeGrade,
OUTPUT_SPACES,
SOURCE_PROFILES,
- WHEEL_LABELS,
WHEEL_ZONES,
type ColorGrade,
type GradeLut,
@@ -42,6 +43,7 @@ import { usePanelState, useRememberedScroll } from "@/cut/lib/panelState";
import type { MediaAsset, VideoClip } from "@/cut/lib/types";
import { useProxyJobs } from "@/cut/lib/mediaProxy";
import {
+ builtinLutOf,
cachedLut,
libraryLutId,
listLutChoices,
@@ -76,6 +78,9 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useDescribeError } from "@/i18n/describeError";
+import { useLabels } from "@/i18n/labels";
+import type { Messages } from "@/i18n/namespaces";
/**
* The clip panel's Color subview, two levels deep. The first level is the
@@ -102,17 +107,43 @@ export function ColorPanel({ clip, peers }: { clip: VideoClip; peers?: readonly
}
/** The tools of the Adjust view; `dirty` feeds each tab's marker dot. The
- * Basic tab owns the Detail group too. */
-const TOOLS = [
- { id: "basic", label: "Basic" },
- { id: "curves", label: "Curves" },
- { id: "wheels", label: "Wheels" },
- { id: "hsl", label: "HSL" },
- { id: "lut", label: "LUT" },
-] as const;
+ * Basic tab owns the Detail group too. Each names itself under
+ * `inspector.color.tools`. */
+const TOOLS = [{ id: "basic" }, { id: "curves" }, { id: "wheels" }, { id: "hsl" }, { id: "lut" }] as const;
type Tool = (typeof TOOLS)[number]["id"];
+type ColorMessages = Messages["inspector"]["color"];
+
+/**
+ * Names the color registries in the page's language: the shipped presets,
+ * the built-in LUTs and the source and delivery spaces, keyed by id. A saved
+ * grade and a Library LUT keep the name the person gave them.
+ */
+function useColorNames() {
+ const t = useTranslations("inspector.color");
+ const lutName = (l: { id: string; label: string }) => {
+ const builtin = builtinLutOf(l.id);
+ return builtin ? t(`builtinLuts.${builtin.id as keyof ColorMessages["builtinLuts"]}`) : l.label;
+ };
+ const presetName = (p: GradePreset | SavedTile | LutTile) => {
+ if ("saved" in p) {
+ return p.label;
+ }
+ if ("lutId" in p) {
+ return lutName({ id: p.lutId, label: p.label });
+ }
+ return GRADE_PRESETS[p.id] ? t(`gradePresets.${p.id as keyof ColorMessages["gradePresets"]}`) : p.label;
+ };
+ return {
+ lutName,
+ presetName,
+ category: (id: GradePresetCategory) => t(`categories.${id}`),
+ source: (id: SourceProfile) => t(`sourceProfiles.${id}`),
+ output: (id: OutputSpace) => t(`outputSpaces.${id}`),
+ };
+}
+
const toolDirty = (g: ColorGrade | undefined, tool: Tool) =>
tool === "basic" ? gradeToolDirty(g, "basic") || gradeToolDirty(g, "detail") : gradeToolDirty(g, tool);
@@ -159,6 +190,8 @@ function useGradeWriter(clip: VideoClip, peers?: readonly VideoClip[]) {
/** What the clip's code values mean. The header's reading is the default;
* picking another profile writes the override onto the asset, with undo. */
function SourceColorRow({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.color");
+ const names = useColorNames();
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;
const detected: SourceProfile = asset.color?.detected ?? "rec709";
@@ -166,11 +199,11 @@ function SourceColorRow({ clip }: { clip: VideoClip }) {
// The menu sets what the file said, and what Rec.709 means here, as a
// small line under the name; the button carries the name alone.
const noteOf = (id: SourceProfile) =>
- [id === detected && "Detected", id === "rec709" && "No conversion"].filter(Boolean).join(" · ");
- const items = Object.fromEntries(SOURCE_PROFILES.map((p) => [p.id, p.label]));
+ [id === detected && t("detected"), id === "rec709" && t("noConversion")].filter(Boolean).join(" · ");
+ const items = Object.fromEntries(SOURCE_PROFILES.map((p) => [p.id, names.source(p.id)]));
return (
<div className="px-3.5">
- <Row label="Source color">
+ <Row label={t("sourceColor")}>
<Select
value={value}
items={items}
@@ -189,7 +222,7 @@ function SourceColorRow({ clip }: { clip: VideoClip }) {
return (
<SelectItem key={p.id} value={p.id} className="text-[12px]">
<span className="flex flex-col">
- {p.label}
+ {names.source(p.id)}
{note && <span className="text-[10px] leading-tight text-muted-foreground">{note}</span>}
</span>
</SelectItem>
@@ -207,27 +240,31 @@ function SourceColorRow({ clip }: { clip: VideoClip }) {
* the master itself when no proxy could be made here. Silent once the proxy
* is in place, and for every file no proxy was asked for. */
function ProxyLine({ asset }: { asset: MediaAsset }) {
+ const t = useTranslations("inspector.color");
+ const describeError = useDescribeError();
const job = useProxyJobs((s) => s.jobs[asset.id]);
// A job only exists for a file that needed a proxy where it was asked.
if (!job) return null;
- const master = asset.color?.codec?.startsWith("ap") ? "the ProRes master" : "the original file";
+ const master = asset.color?.codec?.startsWith("ap") ? "prores" : "original";
const text =
job.kind === "making"
- ? `Preview proxy: ${Math.round(job.progress * 100)}%`
+ ? t("proxyMaking", { percent: Math.round(job.progress * 100) })
: job.kind === "none"
- ? `No preview proxy on this browser. The preview plays ${master}.`
- : `Preview proxy failed: ${job.error}`;
+ ? t("proxyNone", { master })
+ : t("proxyFailed", { error: describeError(job) });
return <p className="pb-2 text-[11px] leading-snug text-muted-foreground">{text}</p>;
}
/** The project's delivery space: what every clip converts to, what the
* export writes, and what the stage shows on an HDR display. */
function ProjectColorRow() {
+ const t = useTranslations("inspector.color");
+ const names = useColorNames();
const colorSpace = useEditor((s) => s.colorSpace);
- const items = Object.fromEntries(OUTPUT_SPACES.map((o) => [o.id, o.label]));
+ const items = Object.fromEntries(OUTPUT_SPACES.map((o) => [o.id, names.output(o.id)]));
return (
<div className="px-3.5">
- <Row label="Project color">
+ <Row label={t("projectColor")}>
<Select
value={colorSpace}
items={items}
@@ -239,7 +276,7 @@ function ProjectColorRow() {
<SelectContent>
{OUTPUT_SPACES.map((o) => (
<SelectItem key={o.id} value={o.id} className="text-[12px]">
- {o.label}
+ {names.output(o.id)}
</SelectItem>
))}
</SelectContent>
@@ -257,6 +294,7 @@ function ProjectColorRow() {
* selected clips or on every clip, as one undo step; or keep it on the shelf
* under a name. */
function GradeFooter({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.color");
const ck = useSliderCheckpoint();
const client = useQueryClient();
const others = useEditor((s) =>
@@ -303,7 +341,7 @@ function GradeFooter({ clip }: { clip: VideoClip }) {
return (
<div className="flex shrink-0 items-center gap-3 border-t border-border bg-card px-3.5 py-2">
<button type="button" className={cn("clip-grade-save-preset", link)} disabled={!grade} onClick={() => setNaming(true)}>
- Save Preset
+ {t("savePresetButton")}
</button>
<span className="ml-auto" />
<button
@@ -312,15 +350,15 @@ function GradeFooter({ clip }: { clip: VideoClip }) {
disabled={others === 0}
onClick={applySelected}
>
- Apply Selected
+ {t("applySelected")}
</button>
<button type="button" className={cn("clip-grade-apply-all", link)} onClick={applyAll}>
- Apply to All
+ {t("applyAll")}
</button>
<Dialog open={naming} onOpenChange={(o) => !o && setNaming(false)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>Save color preset</DialogTitle>
+ <DialogTitle>{t("saveDialogTitle")}</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
@@ -328,11 +366,11 @@ function GradeFooter({ clip }: { clip: VideoClip }) {
void save();
}}
>
- <Input autoFocus placeholder="Preset name" value={name} onChange={(e) => setName(e.target.value)} />
+ <Input autoFocus placeholder={t("presetName")} value={name} onChange={(e) => setName(e.target.value)} />
<DialogFooter className="mt-4">
<Button type="submit" disabled={busy || !name.trim()} className="w-full">
{busy && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Save preset
+ {t("savePreset")}
</Button>
</DialogFooter>
</form>
@@ -387,6 +425,8 @@ function withLutToggled(grade: ColorGrade | undefined, lutId: string): ColorGrad
}
function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readonly VideoClip[]; onAdjust: () => void }) {
+ const t = useTranslations("inspector.color");
+ const names = useColorNames();
const [category, setCategory] = usePanelState<Category>(clip.id, "colorPresetCategory", "all");
const gridScroll = useRememberedScroll(clip.id, `color-presets:${category}`);
// The clip's own frame, ungraded: a swatch shows what its preset does to the
@@ -410,7 +450,7 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
const active = clip.grade?.preset;
const lut = clip.grade?.lut;
const lutView = category === LUTS;
- const manualDirty = TOOLS.some((t) => toolDirty(clip.grade, t.id));
+ const manualDirty = TOOLS.some((tool) => toolDirty(clip.grade, tool.id));
const presets: (GradePreset | SavedTile | LutTile)[] =
category === "all"
? GRADE_PRESET_CATEGORIES.flatMap((c) => gradePresetsInCategory(c.id))
@@ -455,17 +495,17 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
<div className="flex min-h-0 flex-1 flex-col">
<div className="shrink-0 bg-card pb-2">
<div className="flex h-10 shrink-0 items-center gap-1 px-3.5 text-sm font-semibold tracking-tight">
- Color
- <Tip label="Adjust">
+ {t("title")}
+ <Tip label={t("adjust")}>
<button
type="button"
- aria-label="Adjust"
+ aria-label={t("adjust")}
className="clip-color-adjust relative ml-auto grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={onAdjust}
>
<SlidersHorizontal className="size-4" />
{manualDirty && (
- <span className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />
+ <span className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-violet-500" aria-label={t("adjusted")} />
)}
</button>
</Tip>
@@ -474,11 +514,11 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
<ProjectColorRow />
<div className="mt-2 flex min-w-0 flex-wrap gap-1 px-3.5">
<button type="button" className={chip(category === "all")} onClick={() => setCategory("all")}>
- All
+ {t("all")}
</button>
{GRADE_PRESET_CATEGORIES.map((c) => (
<button key={c.id} type="button" className={chip(category === c.id)} onClick={() => setCategory(c.id)}>
- {c.label}
+ {names.category(c.id)}
</button>
))}
<button
@@ -486,14 +526,14 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
className={cn("clip-grade-category-luts", chip(category === LUTS))}
onClick={() => setCategory(LUTS)}
>
- LUTs
+ {t("luts")}
</button>
<button
type="button"
className={cn("clip-grade-category-saved", chip(category === SAVED))}
onClick={() => setCategory(SAVED)}
>
- Saved
+ {t("saved")}
</button>
</div>
</div>
@@ -511,6 +551,7 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
<PresetTile
key={`${clip.id}:${p.id}`}
preset={p}
+ label={names.presetName(p)}
frame={frame}
profile={profile}
selected={
@@ -522,14 +563,14 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
))}
{category === SAVED && presets.length === 0 && (
<p className="col-span-2 py-6 text-center text-[12px] text-muted-foreground">
- Grades you save land here.
+ {t("savedEmpty")}
</p>
)}
</ScrollArea>
<div className="shrink-0 border-t border-border bg-card px-3.5 py-1">
- <Row label="Intensity">
+ <Row label={t("intensity")}>
<ValueSlider
- label="Intensity"
+ label={t("intensity")}
sliderClassName="clip-grade-preset-amount data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={Math.round(((lutView ? lut?.amount : active?.amount) ?? 1) * 100)}
@@ -551,7 +592,7 @@ function PresetView({ clip, peers, onAdjust }: { clip: VideoClip; peers?: readon
}}
/>
</Row>
- <Row label="Protect skin tones">
+ <Row label={t("protectSkin")}>
<Switch
size="sm"
className="clip-grade-protect-skin"
@@ -597,6 +638,7 @@ const presetNeedsLutThumb = (p: GradePreset) => !!(p.grade.curves || p.grade.whe
function PresetTile({
preset,
+ label,
frame,
profile,
selected,
@@ -604,12 +646,15 @@ function PresetTile({
onRemove,
}: {
preset: GradePreset;
+ /** The tile's name in the page's language. */
+ label: string;
frame: string | null;
profile: SourceProfile;
selected: boolean;
onPick: () => void;
onRemove?: () => void;
}) {
+ const t = useTranslations("inspector.color");
const converted = profile !== "rec709" && profile !== "srgb";
const needsLut = presetNeedsLutThumb(preset) || converted;
const approx = useMemo(() => gradeCssApprox(preset.grade), [preset]);
@@ -711,13 +756,13 @@ function PresetTile({
<StandInScene filter={approx.filter} tint={approx.tint} />
)}
</span>
- <span className="max-w-full truncate">{preset.label}</span>
+ <span className="max-w-full truncate">{label}</span>
</button>
{onRemove && (
- <Tip label="Delete preset">
+ <Tip label={t("deletePreset")}>
<button
type="button"
- aria-label={`Delete ${preset.label}`}
+ aria-label={t("deleteNamed", { name: label })}
className="absolute top-2 right-2 grid size-6 place-items-center rounded-full bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"
onClick={onRemove}
>
@@ -747,13 +792,14 @@ function StandInScene({ filter, tint }: { filter: string; tint: string | null })
/* ------------------------------------------------------------------ */
function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonly VideoClip[]; onBack: () => void }) {
+ const t = useTranslations("inspector.color");
// The picked tool holds for the session, the same way the open level does.
const [tool, setTool] = usePanelState<Tool>(clip.id, "colorTool", "basic");
const toolScroll = useRememberedScroll(clip.id, `color-adjust:${tool}`);
const { draft, commit } = useGradeWriter(clip, peers);
const grade = clip.grade;
// Manual adjustments only — reset-all keeps the preset layer.
- const manualDirty = TOOLS.some((t) => toolDirty(grade, t.id));
+ const manualDirty = TOOLS.some((item) => toolDirty(grade, item.id));
// Fit a starting grade from the clip's code values rendered through its
// own recipe (never the graded preview, which would fold the current grade
// back into the fit); the sliders show the result and stay fully
@@ -775,25 +821,25 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonly
<div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">
<button
type="button"
- aria-label="Back"
+ aria-label={t("back")}
className="clip-color-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={onBack}
>
<ChevronLeft className="size-4" />
</button>
- Adjust
+ {t("adjust")}
<button
type="button"
className="clip-grade-auto ml-auto flex items-center gap-1 rounded-md border border-input px-2 py-0.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
onClick={autoGrade}
>
<Wand2 className="size-3" />
- Auto
+ {t("auto")}
</button>
- <Tip label="Reset all adjustments">
+ <Tip label={t("resetAll")}>
<button
type="button"
- aria-label="Reset all adjustments"
+ aria-label={t("resetAll")}
className={cn(
"clip-grade-reset grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground",
!manualDirty && "invisible"
@@ -805,21 +851,21 @@ function AdjustView({ clip, peers, onBack }: { clip: VideoClip; peers?: readonly
</Tip>
</div>
<div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
- {TOOLS.map((t) => (
+ {TOOLS.map((item) => (
<button
- key={t.id}
+ key={item.id}
type="button"
className={cn(
- `clip-grade-tab-${t.id} relative flex-1 rounded-md px-1 py-1 transition-colors`,
- tool === t.id ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"
+ `clip-grade-tab-${item.id} relative flex-1 rounded-md px-1 py-1 transition-colors`,
+ tool === item.id ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"
)}
- onClick={() => setTool(t.id)}
+ onClick={() => setTool(item.id)}
>
- {t.label}
- {toolDirty(grade, t.id) && (
+ {t(`tools.${item.id}`)}
+ {toolDirty(grade, item.id) && (
<span
- className={cn("absolute top-1 right-1 size-1 rounded-full", tool === t.id ? "bg-white/80" : "bg-violet-500")}
- aria-label={`${t.label} adjusted`}
+ className={cn("absolute top-1 right-1 size-1 rounded-full", tool === item.id ? "bg-white/80" : "bg-violet-500")}
+ aria-label={t("toolAdjusted", { tool: t(`tools.${item.id}`) })}
/>
)}
</button>
@@ -859,17 +905,18 @@ type GradeWrite = {
const formatSigned = (v: number) => (v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`);
+type GradeFieldKey = keyof ColorMessages["fields"];
+
function BasicTool({ grade, draft, commit }: GradeWrite) {
+ const t = useTranslations("inspector.color");
// Legacy fields keep rendering and stay editable on clips that carry them;
// fresh grades never surface the rows.
- const legacy: { key: "brightness" | "hue"; label: string; min: number; max: number }[] = [];
- if (grade?.brightness) legacy.push({ key: "brightness", label: "Brightness", min: -GRADE_MAX, max: GRADE_MAX });
- if (grade?.hue) legacy.push({ key: "hue", label: "Hue", min: -GRADE_HUE_MAX, max: GRADE_HUE_MAX });
- const groups = [
- { id: "light" as const, label: "Light" },
- { id: "color" as const, label: "Color" },
- ];
- const sliderRow = (key: keyof ColorGrade & string, label: string, min: number, max: number) => {
+ const legacy: { key: "brightness" | "hue"; min: number; max: number }[] = [];
+ if (grade?.brightness) legacy.push({ key: "brightness", min: -GRADE_MAX, max: GRADE_MAX });
+ if (grade?.hue) legacy.push({ key: "hue", min: -GRADE_HUE_MAX, max: GRADE_HUE_MAX });
+ const groups = [{ id: "light" as const }, { id: "color" as const }];
+ const sliderRow = (key: GradeFieldKey, min: number, max: number) => {
+ const label = t(`fields.${key}`);
const value = (grade?.[key] as number | undefined) ?? 0;
// A one-sided slider reads as a plain amount; a centred one carries its sign.
const format = (v: number) => (key === "hue" ? `${Math.round(v)}°` : min < 0 ? formatSigned(v) : `${Math.round(v)}`);
@@ -889,7 +936,7 @@ function BasicTool({ grade, draft, commit }: GradeWrite) {
onDraft={(v) => draft({ ...grade, [key]: v })}
onCommit={(v) => commit({ ...grade, [key]: v })}
/>
- <ResetButton title={`Reset ${label.toLowerCase()}`} show={value !== 0} onClick={() => commit({ ...grade, [key]: 0 })} />
+ <ResetButton title={t(`resetField.${key}`)} show={value !== 0} onClick={() => commit({ ...grade, [key]: 0 })} />
</Row>
);
};
@@ -897,18 +944,18 @@ function BasicTool({ grade, draft, commit }: GradeWrite) {
<>
{groups.map((g) => (
<div key={g.id} className="flex flex-col gap-1">
- <span className="mt-1 text-xs font-semibold text-muted-foreground">{g.label}</span>
- {GRADE_BASIC_FIELDS.filter((f) => f.group === g.id).map((f) => sliderRow(f.key, f.label, f.min, GRADE_MAX))}
+ <span className="mt-1 text-xs font-semibold text-muted-foreground">{t(`groups.${g.id}`)}</span>
+ {GRADE_BASIC_FIELDS.filter((f) => f.group === g.id).map((f) => sliderRow(f.key, f.min, GRADE_MAX))}
</div>
))}
<div className="flex flex-col gap-1">
- <span className="mt-1 text-xs font-semibold text-muted-foreground">Detail</span>
- {GRADE_DETAIL_FIELDS.map((f) => sliderRow(f.key, f.label, f.min, GRADE_MAX))}
+ <span className="mt-1 text-xs font-semibold text-muted-foreground">{t("groups.detail")}</span>
+ {GRADE_DETAIL_FIELDS.map((f) => sliderRow(f.key, f.min, GRADE_MAX))}
</div>
{legacy.length > 0 && (
<div className="flex flex-col gap-1">
- <span className="mt-1 text-xs font-semibold text-muted-foreground">Legacy</span>
- {legacy.map((f) => sliderRow(f.key, f.label, f.min, f.max))}
+ <span className="mt-1 text-xs font-semibold text-muted-foreground">{t("groups.legacy")}</span>
+ {legacy.map((f) => sliderRow(f.key, f.min, f.max))}
</div>
)}
</>
@@ -916,6 +963,8 @@ function BasicTool({ grade, draft, commit }: GradeWrite) {
}
function WheelsTool({ grade, draft, commit }: GradeWrite) {
+ const t = useTranslations("inspector.color");
+ const wheelLabel = useLabels("wheel");
const wheels = grade?.wheels;
const tuple = (z: WheelZone): WheelTuple => wheels?.[z] ?? [0, 0, 0];
const write = (to: (g: ColorGrade) => void, z: WheelZone, next: WheelTuple) =>
@@ -928,7 +977,7 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {
return (
<div key={z} className={`clip-grade-wheel-${z}`}>
<ColorWheel
- label={WHEEL_LABELS[z]}
+ label={wheelLabel(z)}
value={[dx, dy]}
onDraft={([nx, ny]) => write(draft, z, [nx, ny, lum])}
onCommit={([nx, ny]) => write(commit, z, [nx, ny, lum])}
@@ -937,14 +986,14 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {
);
})}
</div>
- <span className="mt-2 text-xs font-semibold text-muted-foreground">Luminance</span>
+ <span className="mt-2 text-xs font-semibold text-muted-foreground">{t("luminance")}</span>
{WHEEL_ZONES.map((z) => {
const [dx, dy, lum] = tuple(z);
- const label = WHEEL_LABELS[z];
+ const label = wheelLabel(z);
return (
<Row key={z} label={label}>
<ValueSlider
- label={`${label} luminance`}
+ label={t("wheelLuminance", { wheel: label })}
sliderClassName={`clip-grade-wheel-${z}-luma data-horizontal:w-24`}
valueClassName="w-9 text-muted-foreground"
value={lum}
@@ -958,7 +1007,7 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {
onCommit={(v) => write(commit, z, [dx, dy, v])}
/>
<ResetButton
- title={`Reset ${label.toLowerCase()} wheel`}
+ title={t(`resetWheel.${z}`)}
show={dx !== 0 || dy !== 0 || lum !== 0}
onClick={() => write(commit, z, [0, 0, 0])}
/>
@@ -969,13 +1018,16 @@ function WheelsTool({ grade, draft, commit }: GradeWrite) {
);
}
+/** The three sliders of a hue band; each names itself under
+ * `inspector.color.hslAxes`. */
const HSL_AXES = [
- { index: 0, label: "Hue" },
- { index: 1, label: "Saturation" },
- { index: 2, label: "Luminance" },
+ { index: 0, id: "hue" },
+ { index: 1, id: "saturation" },
+ { index: 2, id: "luminance" },
] as const;
function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string }) {
+ const t = useTranslations("inspector.color");
const [band, setBand] = usePanelState<HslBand>(clipId, "hslBand", "orange");
const active = HSL_BANDS.find((b) => b.id === band)!;
const tuple: HslTuple = grade?.hsl?.[band] ?? [0, 0, 0];
@@ -984,10 +1036,10 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string
<>
<div className="mt-1 flex flex-wrap gap-1.5">
{HSL_BANDS.map((b) => (
- <Tip key={b.id} label={b.label}>
+ <Tip key={b.id} label={t(`hslBands.${b.id}`)}>
<button
type="button"
- aria-label={b.label}
+ aria-label={t(`hslBands.${b.id}`)}
aria-pressed={band === b.id}
className={cn(
`clip-grade-hsl-${b.id} relative size-7 rounded-full border-2 transition-transform`,
@@ -1002,13 +1054,16 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string
))}
</div>
<div className="mt-1 text-[12px] text-muted-foreground">
- Adjusting <span className="font-semibold text-foreground">{active.label}</span>
+ {t.rich("adjustingBand", {
+ band: t(`hslBands.${active.id}`),
+ b: (chunks) => <span className="font-semibold text-foreground">{chunks}</span>,
+ })}
</div>
{HSL_AXES.map((axis) => (
- <Row key={axis.label} label={axis.label}>
+ <Row key={axis.id} label={t(`hslAxes.${axis.id}`)}>
<ValueSlider
- label={`${active.label} ${axis.label.toLowerCase()}`}
- sliderClassName={`clip-grade-hsl-${axis.label.toLowerCase()} data-horizontal:w-24`}
+ label={t(`bandAxis.${axis.id}`, { band: t(`hslBands.${active.id}`) })}
+ sliderClassName={`clip-grade-hsl-${axis.id} data-horizontal:w-24`}
valueClassName="w-9 text-muted-foreground"
value={tuple[axis.index]}
min={-GRADE_MAX}
@@ -1029,7 +1084,7 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string
}}
/>
<ResetButton
- title={`Reset ${axis.label.toLowerCase()}`}
+ title={t(`resetField.${axis.id}`)}
show={tuple[axis.index] !== 0}
onClick={() => {
const next = [...tuple] as HslTuple;
@@ -1050,7 +1105,9 @@ function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string
/** The label of a built-in or Library LUT, re-read as the Library changes. */
function useLutLabel(id: string | null): string | undefined {
const choices = useLutChoices();
- return id ? choices.find((c) => c.id === id)?.label : undefined;
+ const names = useColorNames();
+ const choice = id ? choices.find((c) => c.id === id) : undefined;
+ return choice ? names.lutName(choice) : undefined;
}
/** The LUT tool: the applied table as a chip with its intensity, over every
@@ -1059,6 +1116,8 @@ function useLutLabel(id: string | null): string | undefined {
* LUT sits under the grade — the picture after the source conversion goes
* through it, and the sliders work on what comes out. */
function LutTool({ clip, grade, draft, commit }: GradeWrite & { clip: VideoClip }) {
+ const t = useTranslations("inspector.color");
+ const names = useColorNames();
const [over, setOver] = useState(false);
const tiles = useLutTiles();
// The clip's own frame, ungraded, so each tile shows what its LUT does.
@@ -1096,11 +1155,11 @@ function LutTool({ clip, grade, draft, commit }: GradeWrite & { clip: VideoClip
<div className="clip-grade-lut-chip mt-1 flex items-center gap-2 rounded-md bg-muted px-2 py-1.5 text-[12px]">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={LUT_MARK_ICON} alt="" aria-hidden className="size-5 shrink-0" />
- <span className="min-w-0 flex-1 truncate font-medium">{label ?? "LUT not in the library"}</span>
- <Tip label="Remove LUT">
+ <span className="min-w-0 flex-1 truncate font-medium">{label ?? t("lutMissing")}</span>
+ <Tip label={t("removeLut")}>
<button
type="button"
- aria-label="Remove LUT"
+ aria-label={t("removeLut")}
className="clip-grade-lut-remove grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={remove}
>
@@ -1110,12 +1169,12 @@ function LutTool({ clip, grade, draft, commit }: GradeWrite & { clip: VideoClip
</div>
) : (
<p className="clip-grade-lut-empty mt-1 rounded-md border border-dashed border-input py-3 text-center text-[12px] text-muted-foreground">
- Drag a LUT from the Library
+ {t("lutEmpty")}
</p>
)}
- <Row label="Intensity">
+ <Row label={t("intensity")}>
<ValueSlider
- label="LUT intensity"
+ label={t("lutIntensity")}
sliderClassName="clip-grade-lut-amount data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={amount}
@@ -1130,14 +1189,15 @@ function LutTool({ clip, grade, draft, commit }: GradeWrite & { clip: VideoClip
/>
</Row>
<div className="clip-grade-lut-grid mt-1 grid grid-cols-2 gap-2 pt-1">
- {tiles.map((t) => (
+ {tiles.map((tile) => (
<PresetTile
- key={`${clip.id}:${t.id}`}
- preset={t}
+ key={`${clip.id}:${tile.id}`}
+ preset={tile}
+ label={names.presetName(tile)}
frame={frame}
profile={profile}
- selected={applied === t.lutId}
- onPick={() => commit(withLutToggled(grade, t.lutId))}
+ selected={applied === tile.lutId}
+ onPick={() => commit(withLutToggled(grade, tile.lutId))}
/>
))}
</div>
diff --git a/site/src/cut/components/ColorWheel.tsx b/site/src/cut/components/ColorWheel.tsx
index 115b3b27..fdbed77f 100644
--- a/site/src/cut/components/ColorWheel.tsx
+++ b/site/src/cut/components/ColorWheel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useRef } from "react";
import { GRADE_MAX } from "@donkeycut/effects-kit";
@@ -23,6 +24,7 @@ export function ColorWheel({
onCommit: (v: [number, number]) => void;
className?: string;
}) {
+ const t = useTranslations("inspector.controls");
const ref = useRef<HTMLDivElement>(null);
const dragging = useRef(false);
const last = useRef<[number, number]>(value);
@@ -45,7 +47,7 @@ export function ColorWheel({
<div
ref={ref}
role="slider"
- aria-label={`${label} color`}
+ aria-label={t("wheelColor", { label })}
aria-valuemin={0}
aria-valuemax={GRADE_MAX}
aria-valuenow={Math.round(Math.hypot(value[0], value[1]))}
diff --git a/site/src/cut/components/ComposerQueue.tsx b/site/src/cut/components/ComposerQueue.tsx
index 8a5b4009..d06d4898 100644
--- a/site/src/cut/components/ComposerQueue.tsx
+++ b/site/src/cut/components/ComposerQueue.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import {
ArrowUpRight,
Check,
@@ -76,6 +77,7 @@ export function ComposerQueue({
onReorder: (ids: string[]) => void;
onTogglePaused: () => void;
}) {
+ const t = useTranslations("chat.composerQueue");
const [open, setOpen] = useState(true);
const frozen = editingId !== null;
const waiting = items.filter((m) => m.status === "queued" || m.status === "folding");
@@ -126,16 +128,14 @@ export function ComposerQueue({
>
<span className="shrink-0 text-[11px] font-medium text-muted-foreground">
{waiting.length === 1
- ? "1 up next"
+ ? t("upNext")
: waiting.length > 1
- ? `${waiting.length} in queue`
- : spawned.length === 1
- ? "1 in another chat"
- : `${spawned.length} in other chats`}
+ ? t("inQueue", { count: waiting.length })
+ : t("inOtherChats", { count: spawned.length })}
</span>
{paused && (
<span className="truncate text-[11px] text-muted-foreground/60">
- Paused
+ {t("paused")}
</span>
)}
</button>
@@ -143,7 +143,7 @@ export function ComposerQueue({
<button
type="button"
className={queueIconButton}
- title={paused ? "Resume the queue" : "Pause the queue"}
+ title={paused ? t("resume") : t("pause")}
onClick={onTogglePaused}
>
{paused ? <Play className="size-3" /> : <Pause className="size-3" />}
@@ -151,7 +151,7 @@ export function ComposerQueue({
<button
type="button"
className={queueIconButton}
- title={open ? "Collapse" : "Expand"}
+ title={open ? t("collapse") : t("expand")}
onClick={() => setOpen(!open)}
>
<ChevronDown
@@ -261,7 +261,7 @@ export function ComposerQueue({
</div>
{shown === "spawned" && (
<div className="mt-0.5 text-[10.5px] text-muted-foreground/60">
- Running in another chat
+ {t("runningElsewhere")}
</div>
)}
<UnmentionedRefPills text={it.text} refs={it.attachments} className="mt-1 text-xs" />
@@ -292,7 +292,7 @@ export function ComposerQueue({
<button
type="button"
className={queueIconButton}
- title="Open that chat"
+ title={t("openChat")}
onClick={() => it.threadId && onOpen(it.threadId)}
>
<ArrowUpRight className="size-3" />
@@ -301,7 +301,7 @@ export function ComposerQueue({
<button
type="button"
className={queueIconButton}
- title="Edit this message"
+ title={t("edit")}
onClick={() => onEditingChange(it.id)}
>
<Pencil className="size-3" />
@@ -310,7 +310,7 @@ export function ComposerQueue({
<button
type="button"
className={queueIconButton}
- title="Remove from the queue"
+ title={t("remove")}
onClick={() => onRemove(it.id)}
>
<Trash2 className="size-3" />
@@ -336,6 +336,7 @@ function QueueEditBox({
onCancel: () => void;
onSave: (text: string) => void;
}) {
+ const t = useTranslations("chat.composerQueue");
const [value, setValue] = useState(initial);
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
@@ -370,14 +371,14 @@ function QueueEditBox({
className="inline-flex h-6 items-center gap-1 rounded-md bg-primary px-2 text-[11px] font-medium text-primary-foreground transition-colors hover:bg-primary/85"
onClick={() => onSave(value)}
>
- <Check className="size-3" /> Save
+ <Check className="size-3" /> {t("save")}
</button>
<button
type="button"
className="h-6 rounded-md px-2 text-[11px] text-muted-foreground transition-colors hover:bg-muted-foreground/10"
onClick={onCancel}
>
- Cancel
+ {t("cancel")}
</button>
</div>
</div>
diff --git a/site/src/cut/components/ConnectGate.tsx b/site/src/cut/components/ConnectGate.tsx
index 382df412..fe0d265e 100644
--- a/site/src/cut/components/ConnectGate.tsx
+++ b/site/src/cut/components/ConnectGate.tsx
@@ -4,6 +4,7 @@ import Image from "next/image";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Loader2, X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { DONKEY_DOWNLOAD_URL } from "@/app/_components/landing/data";
import { track } from "@/lib/analytics";
@@ -72,6 +73,7 @@ async function permissionState(): Promise<PermissionState | null> {
}
export function ConnectGate({ children }: { children: ReactNode }) {
+ const t = useTranslations("editor.connectGate");
// Settings pages (billing, usage, feature flags) never touch the engine, so
// they skip the probe and the banner.
const onSettings = (usePathname() ?? "").split("/").includes("settings");
@@ -155,10 +157,10 @@ export function ConnectGate({ children }: { children: ReactNode }) {
// be undone in site settings.
useEffect(() => {
if (reached !== false || needsAsk || blocked || forcedGate()) return;
- const t = setInterval(() => {
+ const timer = setInterval(() => {
engineProbe().then(bindEngine, () => {});
}, 3000);
- return () => clearInterval(t);
+ return () => clearInterval(timer);
}, [reached, needsAsk, blocked, bindEngine]);
// The engine stopped answering mid-session: fall back to the cloud and raise
@@ -213,21 +215,18 @@ export function ConnectGate({ children }: { children: ReactNode }) {
{banner && (
<div className="relative flex h-8 shrink-0 items-center justify-center gap-3 bg-red-600 px-10 text-xs font-medium text-white">
<span className="min-w-0 truncate">
- This project is stored on this Mac, and{" "}
- {blocked
- ? "your browser is blocking this page from reaching the Donkey app."
- : "Donkey Cut can’t reach the Donkey app."}
+ {blocked ? t("bannerBlocked") : t("bannerUnreachable")}
</span>
<button
className="shrink-0 underline underline-offset-2"
onClick={() => setHowOpen(true)}
type="button"
>
- How to fix this
+ {t("howToFix")}
</button>
<button
- aria-label="Dismiss"
- title="Dismiss"
+ aria-label={t("dismiss")}
+ title={t("dismiss")}
className="absolute right-2 grid size-5 place-items-center rounded-full text-white/80 hover:bg-white/20 hover:text-white"
onClick={() => setDismissed(true)}
type="button"
@@ -242,41 +241,24 @@ export function ConnectGate({ children }: { children: ReactNode }) {
<DialogHeader>
<DialogTitle>
{blocked
- ? "Connection blocked"
+ ? t("titleBlocked")
: needsAsk
- ? "Connect to the Donkey app"
- : "This project is stored on this Mac"}
+ ? t("titleAsk")
+ : t("titleStored")}
</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{blocked ? (
- <>
- This is a local project — its video and its edits live on this
- Mac, and your browser is blocking this page from reaching the
- Donkey app that opens them. Open the site settings from the icon
- next to the address bar, turn on{" "}
- <span className="font-medium text-foreground">Apps on device</span>,
- then try again.
- </>
+ t.rich("bodyBlocked", { em: (chunks) => <span className="font-medium text-foreground">{chunks}</span> })
) : needsAsk ? (
- <>
- This is a local project — it lives in the Donkey app on this
- Mac. Your browser will ask for permission to connect to apps on
- this device — choose{" "}
- <span className="font-medium text-foreground">Allow</span>.
- </>
+ t.rich("bodyAsk", { em: (chunks) => <span className="font-medium text-foreground">{chunks}</span> })
) : (
- <>
- This is a local project: its video and its edits live on this
- Mac, and the Donkey app is what opens them. Install Donkey, or
- open it if it&rsquo;s already installed — this page connects
- automatically.
- </>
+ t("bodyInstall")
)}
</p>
{blocked && (
<Image
- alt="Chrome's site settings open over the address bar, with the Apps on device toggle"
+ alt={t("siteSettingsAlt")}
className="w-full rounded-xl border shadow-sm"
height={660}
src="/cut/connect-site-settings.png"
@@ -293,12 +275,12 @@ export function ConnectGate({ children }: { children: ReactNode }) {
window.location.href = DONKEY_DOWNLOAD_URL;
}}
>
- Download for Mac
+ {t("download")}
</Button>
)}
<Button onClick={() => void connect()} disabled={connecting}>
{connecting && <Loader2 className="animate-spin" data-icon="inline-start" />}
- {connecting ? "Connecting…" : needsAsk ? "Connect" : "Try again"}
+ {connecting ? t("connecting") : needsAsk ? t("connect") : t("tryAgain")}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/site/src/cut/components/CreditsPill.tsx b/site/src/cut/components/CreditsPill.tsx
index af90b9e8..22e3a251 100644
--- a/site/src/cut/components/CreditsPill.tsx
+++ b/site/src/cut/components/CreditsPill.tsx
@@ -8,6 +8,7 @@ import { useEffect } from "react";
import Link from "next/link";
import { useQueryClient } from "@tanstack/react-query";
import { Loader2, Zap } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useEngineUser } from "@/cut/lib/backend/hooks";
@@ -55,6 +56,8 @@ export function useLiveCreditBalance() {
}
function BalancePill() {
+ const t = useTranslations("billing.creditsPill");
+ const locale = useLocale();
const queryClient = useQueryClient();
const balance = useCreditBalance();
useLiveCreditBalance();
@@ -79,14 +82,14 @@ function BalancePill() {
return (
<Popover>
<PopoverTrigger
- aria-label={`Credits: ${formatCredits(balance.data.balance)}`}
+ aria-label={t("label", { credits: formatCredits(balance.data.balance, locale) })}
onClick={() =>
track("cut_credits_pill_clicked", { credits: creditsFromDollars(balance.data.balance, "down"), dollars })
}
className={PILL}
>
<Zap className="size-3.5" />
- {compactCredits(balance.data.balance)}
+ {compactCredits(balance.data.balance, locale)}
</PopoverTrigger>
<PopoverContent side="bottom" align="end" sideOffset={6} className="w-64 p-0">
<PlanCard balance={balance.data.balance} />
@@ -99,6 +102,8 @@ function BalancePill() {
// free account is sold Pro; a Pro account already pays, so its button goes to
// billing, where credits are bought.
function PlanCard({ balance }: { balance: string }) {
+ const t = useTranslations("billing");
+ const locale = useLocale();
const base = useCutBase();
const pro = useProSubscription();
const upgrade = useUpgradeToPro();
@@ -106,24 +111,24 @@ function PlanCard({ balance }: { balance: string }) {
return (
<div className="text-sm">
<div className="flex items-center justify-between gap-3 px-4 py-3">
- <span className="font-semibold">{isPro ? "Pro" : "Free"}</span>
+ <span className="font-semibold">{isPro ? "Pro" : t("creditsPill.free")}</span>
{pro.data &&
(isPro ? (
<Button size="sm" render={<Link href={`${base}/settings`} />}>
- Buy credits
+ {t("buyCredits")}
</Button>
) : (
<Button size="sm" disabled={upgrade.isPending} onClick={upgrade.start}>
{upgrade.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Upgrade
+ {t("creditsPill.upgrade")}
</Button>
))}
</div>
<div className="flex items-center gap-2.5 border-t border-border px-4 py-3">
<Zap className="size-4 text-muted-foreground" />
- <span className="flex-1 text-muted-foreground">Credits</span>
+ <span className="flex-1 text-muted-foreground">{t("creditsPill.credits")}</span>
<span className="font-medium tabular-nums">
- {formatCreditCount(creditsFromDollars(balance, "down"))}
+ {formatCreditCount(creditsFromDollars(balance, "down"), locale)}
</span>
</div>
</div>
diff --git a/site/src/cut/components/CurveEditor.tsx b/site/src/cut/components/CurveEditor.tsx
index ad6bb22e..8df64348 100644
--- a/site/src/cut/components/CurveEditor.tsx
+++ b/site/src/cut/components/CurveEditor.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { curveLut, type CurvePoint, type GradeCurves } from "@donkeycut/effects-kit";
import { cn } from "@/lib/utils";
@@ -15,11 +16,11 @@ import { cn } from "@/lib/utils";
type Channel = "m" | "r" | "g" | "b";
-const CHANNELS: { id: Channel; label: string; color: string }[] = [
- { id: "m", label: "Master", color: "var(--foreground)" },
- { id: "r", label: "Red", color: "#ff453a" },
- { id: "g", label: "Green", color: "#32d74b" },
- { id: "b", label: "Blue", color: "#0a84ff" },
+const CHANNELS: { id: Channel; color: string }[] = [
+ { id: "m", color: "var(--foreground)" },
+ { id: "r", color: "#ff453a" },
+ { id: "g", color: "#32d74b" },
+ { id: "b", color: "#0a84ff" },
];
const IDENTITY: CurvePoint[] = [
@@ -38,6 +39,7 @@ export function CurveEditor({
onDraft: (curves: GradeCurves) => void;
onCommit: (curves: GradeCurves) => void;
}) {
+ const t = useTranslations("timeline.curves");
const [channel, setChannel] = useState<Channel>("m");
const svgRef = useRef<SVGSVGElement>(null);
const drag = useRef<{ index: number; points: CurvePoint[] } | null>(null);
@@ -128,7 +130,7 @@ export function CurveEditor({
key={c.id}
type="button"
className={cn(
- "flex-1 rounded-md px-1 py-0.5 text-[11.5px] font-medium transition-colors",
+ "min-w-0 flex-1 truncate rounded-md px-1 py-0.5 text-[11.5px] font-medium transition-colors",
channel === c.id
? "bg-secondary text-foreground"
: "text-muted-foreground hover:text-foreground",
@@ -136,7 +138,7 @@ export function CurveEditor({
)}
onClick={() => setChannel(c.id)}
>
- {c.label}
+ {t(`channels.${c.id}`)}
</button>
))}
</div>
diff --git a/site/src/cut/components/DocText.tsx b/site/src/cut/components/DocText.tsx
index 7e1c065e..0308f6b8 100644
--- a/site/src/cut/components/DocText.tsx
+++ b/site/src/cut/components/DocText.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import Markdown from "react-markdown";
+import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
import { baseMarkdownComponents } from "./markdownComponents";
@@ -101,8 +102,9 @@ function parseRows(text: string, delim: string): string[][] {
const CSV_ROW_CAP = 200;
function CsvTable({ text, delim }: { text: string; delim: string }) {
+ const t = useTranslations("home.docText");
const rows = parseRows(text, delim);
- if (rows.length === 0) return <p className="text-muted-foreground">Empty file.</p>;
+ if (rows.length === 0) return <p className="text-muted-foreground">{t("empty")}</p>;
const [head, ...body] = rows;
const shown = body.slice(0, CSV_ROW_CAP);
return (
@@ -130,7 +132,7 @@ function CsvTable({ text, delim }: { text: string; delim: string }) {
</tbody>
</table>
{body.length > shown.length && (
- <p className="mt-1.5 text-muted-foreground">+{body.length - shown.length} more rows</p>
+ <p className="mt-1.5 text-muted-foreground">{t("moreRows", { count: body.length - shown.length })}</p>
)}
</div>
);
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 357e8647..2c0ca0ea 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -10,6 +10,8 @@ import { useEnvironment } from "@/cut/lib/environment";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Clapperboard, Laptop, Loader2, X } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { useDescribeError } from "@/i18n/describeError";
import { Button } from "@/components/ui/button";
import {
apiFetch,
@@ -114,6 +116,8 @@ export function Editor({
* the store in read-only mode before mounting. */
viewer?: boolean;
}) {
+ const t = useTranslations("editor.editor");
+ const describeError = useDescribeError();
const [chatActivity, setChatActivity] = useState<{ projectId: string; status: ChatStatus } | null>(null);
const onChatStatusChange = useCallback((id: string, status: ChatStatus) => {
setChatActivity((current) => current?.projectId === id && current.status === status
@@ -152,7 +156,7 @@ export function Editor({
}, []);
const back = backTarget(useCutBase(), from, folder);
const loaded = useEditor((s) => s.loaded);
- const loadError = useEditor((s) => s.loadError);
+ const loadError = useEditor((s) => s.loadFailure ?? s.loadError);
// The tab is the open project, so it wears the project's name — through
// renames too.
useTabTitle(useEditor((s) => s.projectName));
@@ -1172,7 +1176,7 @@ export function Editor({
e.preventDefault();
s.toggleGuidesShown();
} else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey && !e.altKey) {
- s.addOverlay();
+ s.addOverlay({ text: t("defaultText") });
} else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {
e.preventDefault();
// While playing, arrows skip in 1s jumps and playback rolls on (seek
@@ -1186,7 +1190,7 @@ export function Editor({
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [importFiles]);
+ }, [importFiles, t]);
// Takes shot on a paired phone land in this project's media as they arrive.
usePhoneInbox(importFiles);
@@ -1200,7 +1204,7 @@ export function Editor({
<Button
variant="outline"
nativeButton={false}
- render={<Link href={back.href}>Back to {back.tab}</Link>}
+ render={<Link href={back.href}>{t("backTo", { tab: back.tab })}</Link>}
/>
);
@@ -1213,8 +1217,7 @@ export function Editor({
<div className="flex max-w-sm flex-col items-center gap-3 text-center">
<Laptop className="size-7 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
- This is a local project — it lives on this Mac. Open the Donkey app and it opens
- here.
+ {t("needsApp")}
</p>
{leave}
</div>
@@ -1227,7 +1230,7 @@ export function Editor({
<div className="grid h-full place-items-center">
<div className="flex flex-col items-center gap-3 text-center">
<Clapperboard className="size-7 text-muted-foreground" />
- <p className="text-sm text-muted-foreground">{loadError}</p>
+ <p className="text-sm text-muted-foreground">{describeError(loadError)}</p>
{leave}
</div>
</div>
@@ -1302,16 +1305,16 @@ export function Editor({
{exportOpen && <ExportDialog />}
{shareGone && (
<div className="fixed top-14 left-1/2 z-50 max-w-[calc(100%-2rem)] -translate-x-1/2 rounded-full bg-foreground/90 px-3.5 py-1.5 text-center text-xs font-medium text-background shadow-lg">
- This share is no longer available.
+ {t("shareGone")}
</div>
)}
{conflictReloaded && (
<div className="fixed top-14 left-1/2 z-50 flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground/90 py-1.5 pr-1.5 pl-3.5 text-background shadow-lg">
- <span className="text-xs font-medium">Reloaded a newer version saved elsewhere.</span>
+ <span className="text-xs font-medium">{t("conflictReloaded")}</span>
<Button
variant="ghost"
size="icon-sm"
- aria-label="Dismiss"
+ aria-label={t("dismiss")}
className="rounded-full text-background hover:bg-background/15 hover:text-background"
onClick={() => setConflictReloaded(false)}
>
diff --git a/site/src/cut/components/EffectsPanel.tsx b/site/src/cut/components/EffectsPanel.tsx
index 43efa688..ba65d9df 100644
--- a/site/src/cut/components/EffectsPanel.tsx
+++ b/site/src/cut/components/EffectsPanel.tsx
@@ -1,11 +1,11 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import {
ALL_EFFECT_IDS,
AUDIO_EFFECT_IDS,
audioFxBars,
- EFFECT_LABELS,
effectPreviewState,
grainTileUrl,
isAudioEffect,
@@ -31,12 +31,13 @@ import { usePlayheadFrame } from "@/cut/components/usePlayheadFrame";
import { STOCK_SFX_CATEGORIES, stockTitle, type StockSfx, type StockSfxCategory } from "@/cut/lib/stock";
import { STOCK_SFX } from "@/cut/lib/stockSfxManifest";
import { useEditor } from "@/cut/lib/store";
-import { isEffectOverlay, TRANSITION_STYLE_LABELS, type EffectOverlay } from "@/cut/lib/types";
+import { isEffectOverlay, type EffectOverlay } from "@/cut/lib/types";
import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { useLabels } from "@/i18n/labels";
import "./grain.css";
import { LightbarCanvas } from "./LightbarCanvas";
@@ -73,13 +74,10 @@ type EffectGroup = "moving" | "filters" | "audio";
* rather than the Transitions tab: what it does, it does to the sound. */
const CROSS_DISSOLVE = "audiocross" as const;
-const GROUPS = [
- { id: "moving", label: "Moving" },
- { id: "filters", label: "Filters" },
- // "Sound", because the rail's own Audio tab is where music and voiceover
- // live; this family is the treatments over whatever is already audible.
- { id: "audio", label: "Sound" },
-] as const;
+// "Sound" names the audio family, because the rail's own Audio tab is where
+// music and voiceover live; this family is the treatments over whatever is
+// already audible.
+const GROUPS = ["moving", "filters", "audio"] as const;
const MOVING: EffectId[] = ["zoom", "grain", "vhs", "glitch", "lightleak", "lightbars", "flash", "shake", "huecycle"];
@@ -87,13 +85,14 @@ const groupOf = (id: EffectId): EffectGroup =>
isAudioEffect(id) ? "audio" : MOVING.includes(id) ? "moving" : "filters";
export function EffectsPanel() {
+ const t = useTranslations("panels.effects");
const live = useEditor((s) => {
if (s.selection?.kind !== "overlay") return null;
const o = s.overlays.find((x) => x.id === s.selection!.id);
return o && isEffectOverlay(o) ? o : null;
});
const [group, setGroup] = useLocalPref<EffectGroup>("cut-effects-group", "moving", (v) =>
- GROUPS.some((g) => g.id === v)
+ GROUPS.some((g) => g === v)
);
// The Sound family drills down: the root lists the sound groups, and an
// open group replaces the segmented control with a back header. Kept across
@@ -142,12 +141,18 @@ export function EffectsPanel() {
className="flex h-8 items-center gap-0.5 rounded-full pr-2.5 pl-1.5 text-[13px] font-medium text-muted-foreground hover:bg-muted hover:text-foreground"
>
<ChevronLeft className="size-4" />
- Sounds
+ {t("sounds")}
</button>
- <span className="truncate text-[13px] font-semibold tracking-tight">{soundGroup}</span>
+ <span className="truncate text-[13px] font-semibold tracking-tight">
+ {soundGroupLabel(t, soundGroup)}
+ </span>
</div>
) : (
- <SubTabs tabs={GROUPS} value={group} onChange={setGroup} />
+ <SubTabs
+ tabs={GROUPS.map((id) => ({ id, label: t(`groups.${id}`) }))}
+ value={group}
+ onChange={setGroup}
+ />
)}
</div>
@@ -182,6 +187,7 @@ function EffectTile({
live: EffectOverlay | null;
frame: string | null;
}) {
+ const effectLabel = useLabels("effect");
const { picked, pick } = useAssetPick(`effect:${id}`);
const [hover, setHover] = useState(false);
// A moving effect's whole point is its motion, so its swatch always plays,
@@ -230,7 +236,7 @@ function EffectTile({
frame={frame}
className={cn("w-full rounded-lg border border-border", marked && PICKED_RING)}
/>
- <span className="leading-none">{EFFECT_LABELS[id]}</span>
+ <span className="leading-none">{effectLabel(id)}</span>
</button>
);
return tile;
@@ -252,6 +258,7 @@ function SoundTile({
live: EffectOverlay | null;
index: number;
}) {
+ const effectLabel = useLabels("effect");
const { picked, pick } = useAssetPick(`effect:${id}`);
const t = useSoundClock(index);
const ref = useRef<HTMLDivElement | null>(null);
@@ -271,7 +278,7 @@ function SoundTile({
ref.current = el;
}}
pickId={`effect:${id}`}
- label={EFFECT_LABELS[id]}
+ label={effectLabel(id)}
marked={marked}
onChoose={choose}
onDragStart={(e) => {
@@ -294,13 +301,14 @@ function SoundTile({
* because what it does is done to the sound.
*/
function CrossDissolveTile({ index }: { index: number }) {
+ const transitionLabel = useLabels("transition");
const { picked, pick } = useAssetPick(`transition:${CROSS_DISSOLVE}`);
const t = useSoundClock(index);
const playing = useFxAudition((s) => s.effect === CROSS_DISSOLVE);
return (
<SoundCard
pickId={`transition:${CROSS_DISSOLVE}`}
- label={TRANSITION_STYLE_LABELS[CROSS_DISSOLVE]}
+ label={transitionLabel(CROSS_DISSOLVE)}
marked={picked}
onChoose={pick}
onDragStart={(e) => {
@@ -357,6 +365,7 @@ function SoundCard({
* before it. */
trailing?: React.ReactNode;
}) {
+ const t = useTranslations("panels.effects");
const nameRef = useRef<HTMLSpanElement>(null);
const [nameHint, setNameHint] = useState(false);
return (
@@ -417,7 +426,7 @@ function SoundCard({
</div>
<button
type="button"
- aria-label={`${playing ? "Stop" : "Play"} ${label}`}
+ aria-label={playing ? t("stopSound", { name: label }) : t("playSound", { name: label })}
onClick={onTogglePlay}
className={cn(
"absolute top-1.5 left-1.5 grid size-6 place-items-center rounded-full bg-background text-foreground shadow-sm ring-1 ring-border transition-opacity hover:scale-105 focus-visible:opacity-100",
@@ -448,6 +457,18 @@ const FAVORITES = "Favorites";
const TREATMENTS = "Treatments";
type SoundGroup = typeof FAVORITES | typeof TREATMENTS | StockSfxCategory;
+/** A sound group's name in the page's language. The group ids stay English:
+ * the open group is saved by id. */
+function soundGroupLabel(t: ReturnType<typeof useTranslations<"panels.effects">>, group: SoundGroup): string {
+ if (group === FAVORITES) {
+ return t("favorites");
+ }
+ if (group === TREATMENTS) {
+ return t("treatments");
+ }
+ return t(`sfxCategories.${group}`);
+}
+
/**
* The Sound family's shelf. The root is a search box over a list of groups —
* the starred sounds, the treatments, then every sound family with its count
@@ -465,6 +486,9 @@ function SoundShelf({
open: SoundGroup | null;
onOpen: (g: SoundGroup | null) => void;
}) {
+ const t = useTranslations("panels.effects");
+ const effectLabel = useLabels("effect");
+ const transitionLabel = useLabels("transition");
const [query, setQuery] = useState("");
const favoriteIds = useSoundFavorites((s) => s.ids);
const families = STOCK_SFX_CATEGORIES.filter((c) => STOCK_SFX.some((x) => x.category === c));
@@ -502,7 +526,7 @@ function SoundShelf({
soundGrid(items, true)
) : (
<div className="py-2 text-[12px] text-muted-foreground">
- Star a sound to keep it here.
+ {t("noFavorites")}
</div>
)}
</ScrollArea>
@@ -525,8 +549,8 @@ function SoundShelf({
let body: React.ReactNode;
if (words.length > 0) {
- const ids = AUDIO_EFFECT_IDS.filter((id) => matchesWords(EFFECT_LABELS[id].toLowerCase()));
- const dissolve = matchesWords(TRANSITION_STYLE_LABELS[CROSS_DISSOLVE].toLowerCase());
+ const ids = AUDIO_EFFECT_IDS.filter((id) => matchesWords(effectLabel(id).toLowerCase()));
+ const dissolve = matchesWords(transitionLabel(CROSS_DISSOLVE).toLowerCase());
const hits = STOCK_SFX.filter((x) =>
matchesWords([x.id, x.category, x.prompt, ...x.tags].join(" ").toLowerCase())
).slice(0, SFX_SEARCH_LIMIT);
@@ -535,14 +559,14 @@ function SoundShelf({
.filter(({ items }) => items.length > 0);
body =
ids.length === 0 && !dissolve && hits.length === 0 ? (
- <div className="py-2 text-[12px] text-muted-foreground">No sounds match.</div>
+ <div className="py-2 text-[12px] text-muted-foreground">{t("noMatches")}</div>
) : (
<>
{(ids.length > 0 || dissolve) && (
- <Section title={TREATMENTS}>{treatmentGrid(ids, dissolve)}</Section>
+ <Section title={t("treatments")}>{treatmentGrid(ids, dissolve)}</Section>
)}
{sections.map(({ c, items }) => (
- <Section key={c} title={c}>
+ <Section key={c} title={soundGroupLabel(t, c)}>
{soundGrid(items)}
</Section>
))}
@@ -565,7 +589,7 @@ function SoundShelf({
// search field's left edge and the chevron on its right.
className="-mx-2 flex h-9 items-center gap-2 rounded-lg px-2 text-[12.5px] font-medium hover:bg-muted"
>
- <span className="flex-1 truncate text-left">{r.group}</span>
+ <span className="flex-1 truncate text-left">{soundGroupLabel(t, r.group)}</span>
<span className="font-mono text-[10px] text-muted-foreground tabular-nums">{r.count}</span>
<ChevronRight className="size-3.5 text-muted-foreground" />
</button>
@@ -582,8 +606,8 @@ function SoundShelf({
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search sounds"
- aria-label="Search sounds"
+ placeholder={t("searchSounds")}
+ aria-label={t("searchSounds")}
className="h-8 pl-8 text-[12px]"
/>
</div>
@@ -610,6 +634,7 @@ function Section({ title, children }: { title: string; children: React.ReactNode
* a sound plays it — by click or by arrowing onto it — so a run through the
* list is heard; picking it again stops it. */
function SfxCard({ sound, fullName = false }: { sound: StockSfx; fullName?: boolean }) {
+ const t = useTranslations("panels.effects");
const pickId = `stock:${sound.id}`;
const { picked, pick } = useAssetPick(pickId);
const projectId = useEditor((s) => s.projectId);
@@ -659,7 +684,7 @@ function SfxCard({ sound, fullName = false }: { sound: StockSfx; fullName?: bool
<>
<button
type="button"
- aria-label={`Add ${label} at the playhead`}
+ aria-label={t("addAtPlayhead", { name: label })}
onClick={add}
className="absolute right-1.5 bottom-1.5 grid size-6 place-items-center rounded-full bg-background text-foreground opacity-0 shadow-sm ring-1 ring-border transition-opacity group-hover:opacity-100 hover:scale-105"
>
@@ -669,7 +694,7 @@ function SfxCard({ sound, fullName = false }: { sound: StockSfx; fullName?: bool
that is not a favorite reads clean. */}
<button
type="button"
- aria-label={`${starred ? "Remove" : "Add"} ${label} ${starred ? "from" : "to"} favorites`}
+ aria-label={starred ? t("removeFavorite", { name: label }) : t("addFavorite", { name: label })}
aria-pressed={starred}
onClick={() => useSoundFavorites.getState().toggle(sound.id)}
className={cn(
diff --git a/site/src/cut/components/ElementsPanel.tsx b/site/src/cut/components/ElementsPanel.tsx
index 470e4832..4ab68e1c 100644
--- a/site/src/cut/components/ElementsPanel.tsx
+++ b/site/src/cut/components/ElementsPanel.tsx
@@ -1,12 +1,14 @@
"use client";
+import { useTranslations } from "next-intl";
import { dealsMarks, lineLikeShape, shapePathD } from "@donkeycut/effects-kit";
import { SubTabs } from "@/cut/components/SubTabs";
import { clearElementDrag, setElementDragData, setObjectDragImage } from "@/cut/lib/assetDrag";
import { PICKED_RING, pickGridNav, useAssetPick } from "@/cut/lib/assetPick";
import { useEnvironment } from "@/cut/lib/environment";
import { useEditor } from "@/cut/lib/store";
-import { SHAPE_LABELS, type ShapeKind } from "@/cut/lib/types";
+import type { ShapeKind } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
import { SHAPE_KINDS } from "@/cut/components/ElementsPanel.tools";
import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
@@ -22,17 +24,17 @@ import { ScrollArea } from "@/components/ui/scroll-area";
type Category = "stickers" | "shapes";
-const CATEGORIES = [
- { id: "stickers", label: "Stickers" },
- { id: "shapes", label: "Shapes" },
-] as const;
+const CATEGORIES = [{ id: "stickers" }, { id: "shapes" }] as const;
export function ElementsPanel({ projectId }: { projectId: string }) {
+ const t = useTranslations("media.elements");
const readOnly = useEditor((s) => s.readOnly);
const { chatgpt } = useEnvironment();
// Inside ChatGPT the card shows no credits, so Stickers, a generation
// surface, leaves the panel.
- const categories = chatgpt ? CATEGORIES.filter((c) => c.id !== "stickers") : CATEGORIES;
+ const categories = (chatgpt ? CATEGORIES.filter((c) => c.id !== "stickers") : CATEGORIES).map(
+ (c) => ({ id: c.id, label: t(c.id) })
+ );
const [viewPref, setView] = useLocalPref<Category>("cut-elements-view", "stickers", (v) =>
CATEGORIES.some((c) => c.id === v)
);
@@ -68,7 +70,7 @@ export function ElementsPanel({ projectId }: { projectId: string }) {
</div>
) : (
<p className="px-2 py-6 text-center text-xs leading-relaxed text-balance text-muted-foreground">
- Stickers you make land here, cut out and ready to place.
+ {t("stickersEmpty")}
</p>
)}
</>
@@ -90,6 +92,7 @@ export function ElementsPanel({ projectId }: { projectId: string }) {
* with its name under it. A click picks it, a drag onto the timeline places
* it. */
function ShapeTile({ shape }: { shape: ShapeKind }) {
+ const shapeLabel = useLabels("shape");
const { picked, pick } = useAssetPick(`shape:${shape}`);
return (
<button
@@ -113,7 +116,7 @@ function ShapeTile({ shape }: { shape: ShapeKind }) {
>
<ShapeSwatch shape={shape} className="size-16" />
</span>
- <span className="leading-none">{SHAPE_LABELS[shape]}</span>
+ <span className="leading-none">{shapeLabel(shape)}</span>
</button>
);
}
diff --git a/site/src/cut/components/EmbeddedNewProject.tsx b/site/src/cut/components/EmbeddedNewProject.tsx
index 19fc169a..02b44acc 100644
--- a/site/src/cut/components/EmbeddedNewProject.tsx
+++ b/site/src/cut/components/EmbeddedNewProject.tsx
@@ -3,6 +3,8 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
+import { creatorNames } from "@/cut/lib/defaultNames";
import { Button } from "@/components/ui/button";
import { cloudBackend } from "@/cut/lib/backend/cloud";
@@ -12,12 +14,16 @@ import { projectHref, useCutBase } from "@/cut/lib/nav";
import { newProjectAllowed } from "@/cut/lib/projectLimit";
import { lastChosenAspect } from "@/cut/lib/store";
import type { ProjectSummary } from "@/cut/lib/types";
+import { errorFromBody } from "@/cut/lib/userError";
+import { useDescribeError } from "@/i18n/describeError";
import { track } from "@/lib/analytics";
// The card's way forward when the project it was opened on can't be shown.
// The card is the whole surface, so there is no projects home to go back to:
// a new cloud project is made and opened here in its place.
export function EmbeddedNewProject() {
+ const t = useTranslations("home.embeddedNewProject");
+ const describeError = useDescribeError();
const router = useRouter();
const base = useCutBase();
const client = useQueryClient();
@@ -30,21 +36,21 @@ export function EmbeddedNewProject() {
try {
// The card carries no upgrade wall, so the limit is said here.
if (!(await newProjectAllowed(client))) {
- throw new Error("This account is at its free project limit. Upgrade to Pro in Donkey Cut to make more.");
+ throw new Error(t("limit"));
}
const aspect = lastChosenAspect() ?? undefined;
const res = await cloudBackend.fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: "Untitled", folderId: null, aspect }),
+ body: JSON.stringify({ name: creatorNames().untitled, folderId: null, aspect }),
});
- if (!res.ok) throw new Error("Could not create the project.");
+ if (!res.ok) throw errorFromBody(await res.json().catch(() => null), t("failed"));
const project = (await res.json()) as ProjectSummary;
seedNewProjectDoc(project.id, project.name, "cloud", aspect);
track("project_created", { source: "chatgpt_card" });
router.replace(framedHref(projectHref(base, project.id, "projects")));
} catch (e) {
- setError(e instanceof Error && e.message ? e.message : "Could not create the project.");
+ setError(describeError(e, t("failed")));
setBusy(false);
}
};
@@ -52,7 +58,7 @@ export function EmbeddedNewProject() {
return (
<>
<Button variant="outline" disabled={busy} onClick={() => void create()}>
- Create New Project
+ {t("create")}
</Button>
{error && <p className="text-xs text-destructive">{error}</p>}
</>
diff --git a/site/src/cut/components/EmbeddedSignInFallback.tsx b/site/src/cut/components/EmbeddedSignInFallback.tsx
index 8d96041d..af7a00ab 100644
--- a/site/src/cut/components/EmbeddedSignInFallback.tsx
+++ b/site/src/cut/components/EmbeddedSignInFallback.tsx
@@ -1,15 +1,18 @@
"use client";
+import { useTranslations } from "next-intl";
+
import { reconnectThroughHost, useHostReady } from "@/cut/lib/hostBridge";
export function EmbeddedSignInFallback() {
+ const t = useTranslations("editor.embeddedSignIn");
useHostReady(true);
return (
<div className="fixed inset-0 z-[60] grid place-items-center bg-background p-6 text-center">
<div className="max-w-sm space-y-3">
- <p className="text-sm text-muted-foreground">Reconnect to continue editing here.</p>
+ <p className="text-sm text-muted-foreground">{t("message")}</p>
<button type="button" className="rounded-md border px-3 py-2 text-sm" onClick={reconnectThroughHost}>
- Reconnect
+ {t("reconnect")}
</button>
</div>
</div>
diff --git a/site/src/cut/components/EmojiPicker.tsx b/site/src/cut/components/EmojiPicker.tsx
index 0fbb4657..ec31bcdf 100644
--- a/site/src/cut/components/EmojiPicker.tsx
+++ b/site/src/cut/components/EmojiPicker.tsx
@@ -4,6 +4,8 @@ import { type ReactElement, useMemo, useRef, useState } from "react";
import { Search } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
+import { useTranslations } from "next-intl";
+import type { Messages } from "@/i18n/namespaces";
import { EMOJI_CATEGORIES, type EmojiEntry } from "@/cut/lib/emoji";
// One glyph per category for the jump bar along the bottom.
@@ -18,6 +20,10 @@ const CATEGORY_GLYPH: Record<string, string> = {
Flags: "🏳️",
};
+// The catalog key that names a category in the page's language; the category
+// names are the Unicode groups, e.g. "Food & Drink".
+type CategoryKey = keyof Messages["media"]["emoji"]["category"];
+
/**
* iPhone-style emoji picker: a search field over the full Unicode set, category
* sections you can jump between, and a scrolling grid. Picking inserts without
@@ -30,6 +36,7 @@ export function EmojiPicker({
trigger: ReactElement;
onPick: (emoji: string) => void;
}) {
+ const t = useTranslations("media.emoji");
const [query, setQuery] = useState("");
const sections = useRef<Record<string, HTMLDivElement | null>>({});
@@ -60,7 +67,7 @@ export function EmojiPicker({
autoFocus
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search emoji"
+ placeholder={t("search")}
className="h-8 pl-8"
/>
</div>
@@ -72,7 +79,7 @@ export function EmojiPicker({
<Grid emoji={results} onPick={onPick} />
) : (
<p className="py-10 text-center text-sm text-muted-foreground">
- No emoji found
+ {t("noResults")}
</p>
)
) : (
@@ -85,7 +92,7 @@ export function EmojiPicker({
style={{ contentVisibility: "auto", containIntrinsicSize: "auto 260px" }}
>
<div className="sticky top-0 z-10 bg-popover/95 py-1 text-xs font-medium text-muted-foreground backdrop-blur-sm">
- {cat.name}
+ {t(`category.${cat.name as CategoryKey}`)}
</div>
<Grid emoji={cat.emoji} onPick={onPick} />
</div>
@@ -99,8 +106,8 @@ export function EmojiPicker({
<button
key={cat.name}
type="button"
- title={cat.name}
- aria-label={cat.name}
+ title={t(`category.${cat.name as CategoryKey}`)}
+ aria-label={t(`category.${cat.name as CategoryKey}`)}
className="grid size-7 place-items-center rounded text-base hover:bg-accent"
onClick={() =>
sections.current[cat.name]?.scrollIntoView({ block: "start" })
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index 470975ba..3d243bd3 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -2,6 +2,7 @@
import { useEffect, useMemo, useState } from "react";
import { ChevronDown } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
@@ -46,7 +47,7 @@ import { useExports } from "@/cut/lib/exportStore";
import { projectDuration, useEditor } from "@/cut/lib/store";
import { subtitleFiles } from "@/cut/lib/subtitleFile";
import { formatTime } from "@/cut/lib/time";
-import { CUT_LOUDNESS, LOUDNESS_CHOICES, loudnessLabel, loudnessSettings, type LoudnessId } from "@/cut/lib/loudnessSettings";
+import { CUT_LOUDNESS, LOUDNESS_CHOICES, loudnessSettings, type LoudnessId } from "@/cut/lib/loudnessSettings";
import { planStems } from "@/cut/lib/stems";
import { cn } from "@/lib/utils";
@@ -58,7 +59,6 @@ const FORMATS = EXPORT_CONTAINERS.flatMap((c) =>
container: c.id as ExportContainer,
codec: k.id as ExportCodec,
label: `${c.label} (${k.label})`,
- detail: k.detail,
}))
);
@@ -70,6 +70,8 @@ const QUALITY_RUNGS = [...EXPORT_QUALITIES].reverse();
// finished file — is tracked in the app-wide exports dock, so starting one
// never blocks starting another.
export function ExportDialog() {
+ const t = useTranslations("editor.exportDialog");
+ const locale = useLocale();
const setExportOpen = useEditor((s) => s.setExportOpen);
const aspect = useEditor((s) => s.aspect);
const clips = useEditor((s) => s.clips);
@@ -228,7 +230,18 @@ export function ExportDialog() {
setExportOpen(false); // the dock takes it from here
};
- const sizeEstimate = formatSizeEstimate(estimateExportBytes(settings, span));
+ const sizeEstimate = formatSizeEstimate(estimateExportBytes(settings, span), locale);
+ // The rung names: the source frame reads in the page's language, the fixed
+ // sizes ("4K", "1080p") read as they are.
+ const rungLabel = (r: { id: string; label: string }) => (r.id === "source" ? t("source") : r.label);
+ // A loudness target by name, with its level beside it ("Social · −14 LUFS").
+ const loudnessName = (id: LoudnessId) =>
+ id === "off"
+ ? t(`loudness.${id}`)
+ : t("loudnessTarget", {
+ name: t(`loudness.${id}`),
+ lufs: String(CUT_LOUDNESS.targets[id]).replace("-", "−"),
+ });
// ProRes encodes at one rate per profile, so the quality scale and the
// typed bitrate have nothing to act on.
const prores = fixedRate(settings.codec);
@@ -244,17 +257,17 @@ export function ExportDialog() {
<Dialog open onOpenChange={(o) => !o && setExportOpen(false)}>
<DialogContent className="gap-0 p-0 sm:max-w-lg">
<DialogHeader className="px-6 pt-6 pb-4">
- <DialogTitle className="text-xl">Export</DialogTitle>
+ <DialogTitle className="text-xl">{t("title")}</DialogTitle>
</DialogHeader>
<DialogBody className="mx-0 my-0 flex flex-col gap-6 px-6 pt-1 pb-6">
- <div className="grid grid-cols-6 gap-1.5 max-sm:grid-cols-3" role="radiogroup" aria-label="Export preset">
+ <div className="grid grid-cols-6 gap-1.5 max-sm:grid-cols-3" role="radiogroup" aria-label={t("presetGroup")}>
{EXPORT_QUICK_PRESETS.map((p) => (
<PresetTile
key={p.id}
checked={preset === p.id}
- label={p.label}
- title={p.detail}
+ label={t(`quickPresets.${p.id}.label`)}
+ title={t(`quickPresets.${p.id}.detail`)}
onClick={() => {
setMbpsText("");
setCustomPicked(false);
@@ -264,30 +277,36 @@ export function ExportDialog() {
))}
<PresetTile
checked={preset === null}
- label="Custom"
- title="Set every option yourself"
+ label={t("custom")}
+ title={t("customHint")}
onClick={() => setCustomPicked(true)}
/>
</div>
<Scale
- label="Resolution"
- value={`${settings.width} × ${settings.height}${resolution.upscale ? " · upscaled" : ""}`}
+ label={t("resolution")}
+ value={
+ resolution.upscale
+ ? t("sizeUpscaled", { width: settings.width, height: settings.height })
+ : t("size", { width: settings.width, height: settings.height })
+ }
index={rungIndex}
stops={rungs.map((r) => ({
- label: r.label,
- title: `${r.width} × ${r.height}${r.upscale ? " · upscaled from the source" : ""}`,
+ label: rungLabel(r),
+ title: r.upscale
+ ? t("sizeUpscaledFromSource", { width: r.width, height: r.height })
+ : t("size", { width: r.width, height: r.height }),
}))}
onIndex={(i) => set({ resolution: rungs[i]!.id })}
/>
{/* ProRes fixes its own bitrate, so the scale stays put and greys out. */}
<Scale
- label="Quality"
- value={customRate ? `${choice.bitrateMbps} Mbps · ${sizeEstimate}` : sizeEstimate}
+ label={t("quality")}
+ value={customRate ? t("customRateValue", { mbps: choice.bitrateMbps ?? 0, size: sizeEstimate }) : sizeEstimate}
index={customRate ? null : qualityIndex}
disabled={prores}
- stops={QUALITY_RUNGS.map((q) => ({ label: q.label, title: q.detail }))}
+ stops={QUALITY_RUNGS.map((q) => ({ label: t(`qualities.${q.id}.label`), title: t(`qualities.${q.id}.detail`) }))}
onIndex={(i) => {
setMbpsText("");
set({ quality: QUALITY_RUNGS[i]!.id, bitrateMbps: undefined });
@@ -295,9 +314,9 @@ export function ExportDialog() {
/>
<div className="flex flex-col gap-3">
- <Field label="File name">
+ <Field label={t("fileName")}>
<Input
- aria-label="File name"
+ aria-label={t("fileName")}
className="h-8 w-48 text-sm"
value={name}
placeholder={projectName}
@@ -305,44 +324,46 @@ export function ExportDialog() {
/>
</Field>
{selection && (
- <Field label="Range">
+ <Field label={t("range")}>
<Select value={rangeMode} onValueChange={(v) => setRangeMode(v as "all" | "selection")}>
- <SelectTrigger className="w-fit min-w-32" aria-label="Range">
+ <SelectTrigger className="w-fit min-w-32" aria-label={t("range")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
- <SelectItem value="all">Whole video</SelectItem>
+ <SelectItem value="all">{t("wholeVideo")}</SelectItem>
<SelectItem
value="selection"
- title="From the first selected item's start to the last one's end, every row included"
+ title={t("selectionHint")}
>
- Selection · {formatTime(selection.start)}–{formatTime(selection.end)}
+ {t("selectionRange", { start: formatTime(selection.start), end: formatTime(selection.end) })}
</SelectItem>
</SelectContent>
</Select>
</Field>
)}
- <Field label="Frame rate">
+ <Field label={t("frameRate")}>
<Select
value={String(choice.fps)}
onValueChange={(v) => set({ fps: v === "source" ? "source" : Number(v) })}
>
- <SelectTrigger className="w-fit min-w-32" aria-label="Frame rate">
+ <SelectTrigger className="w-fit min-w-32" aria-label={t("frameRate")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
- <SelectItem value="source" title="The rate the footage plays at">
- {probing ? "Source · reading…" : `Source · ${Number((sourceFps ?? DEFAULT_EXPORT_FPS).toFixed(3))} fps`}
+ <SelectItem value="source" title={t("sourceRateHint")}>
+ {probing
+ ? t("sourceReading")
+ : t("sourceRate", { fps: Number((sourceFps ?? DEFAULT_EXPORT_FPS).toFixed(3)) })}
</SelectItem>
{EXPORT_FRAME_RATES.map((f) => (
<SelectItem key={f} value={String(f)}>
- {f} fps
+ {t("fps", { fps: f })}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
- <Field label="Format">
+ <Field label={t("format")}>
<Select
value={formatId}
onValueChange={(v) => {
@@ -359,34 +380,34 @@ export function ExportDialog() {
});
}}
>
- <SelectTrigger className="w-fit min-w-32" aria-label="Format">
+ <SelectTrigger className="w-fit min-w-32" aria-label={t("format")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{FORMATS.map((f) => (
- <SelectItem key={f.id} value={f.id} title={f.detail} disabled={hdr && f.codec === "h264"}>
+ <SelectItem key={f.id} value={f.id} title={t(`codecs.${f.codec}`)} disabled={hdr && f.codec === "h264"}>
{f.label}
- {hdr && f.codec === "h264" ? " · 8-bit" : ""}
+ {hdr && f.codec === "h264" ? ` · ${t("eightBit")}` : ""}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
- <Field label="Color">
+ <Field label={t("color")}>
<Select value={colorSpace} onValueChange={(v) => setColorSpace(v as OutputSpace)}>
- <SelectTrigger className="w-fit min-w-32" aria-label="Color">
+ <SelectTrigger className="w-fit min-w-32" aria-label={t("color")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{OUTPUT_SPACES.map((o) => (
<SelectItem key={o.id} value={o.id}>
- {o.label}
+ {t(`colorSpaces.${o.id}`)}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
- <Field label="Audio">
+ <Field label={t("audio")}>
<Select
value={choice.audioCodec}
onValueChange={(v) =>
@@ -396,12 +417,12 @@ export function ExportDialog() {
})
}
>
- <SelectTrigger className="w-32" aria-label="Audio">
+ <SelectTrigger className="w-32" aria-label={t("audio")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{EXPORT_AUDIO.map((a) => (
- <SelectItem key={a.id} value={a.id} title={a.detail}>
+ <SelectItem key={a.id} value={a.id} title={t(`audioCodecs.${a.id}`)}>
{a.label}
</SelectItem>
))}
@@ -409,21 +430,21 @@ export function ExportDialog() {
</Select>
</Field>
<Field
- label="Loudness"
+ label={t("loudnessLabel")}
hint={
loudness === "off"
? undefined
- : `Sets the whole mix to its target and holds true peaks under ${String(CUT_LOUDNESS.truePeakCeiling).replace("-", "−")} dBTP.`
+ : t("loudnessHint", { ceiling: String(CUT_LOUDNESS.truePeakCeiling).replace("-", "−") })
}
>
<Select value={loudness} onValueChange={(v) => setLoudness(v as LoudnessId)}>
- <SelectTrigger className="w-fit min-w-32" aria-label="Loudness">
+ <SelectTrigger className="w-fit min-w-32" aria-label={t("loudnessLabel")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{LOUDNESS_CHOICES.map((c) => (
<SelectItem key={c.id} value={c.id}>
- {loudnessLabel(c.id)}
+ {loudnessName(c.id)}
</SelectItem>
))}
</SelectContent>
@@ -433,13 +454,13 @@ export function ExportDialog() {
<Collapsible open={moreOpen} onOpenChange={setMoreOpen} className="flex flex-col gap-3">
<CollapsibleTrigger className="flex items-center justify-between text-sm text-muted-foreground transition-colors hover:text-foreground">
- More settings
+ {t("moreSettings")}
<ChevronDown className={cn("size-4 transition-transform", moreOpen && "rotate-180")} />
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col gap-3">
<Field
- label="Custom bitrate"
- hint="Higher bitrates mean better quality and larger files. Use it when a platform requires a specific bitrate; ProRes sets its own."
+ label={t("customBitrate")}
+ hint={t("customBitrateHint")}
>
<label
className={cn(
@@ -453,8 +474,8 @@ export function ExportDialog() {
min={0.5}
max={MAX_MBPS}
step={0.5}
- placeholder="Auto"
- aria-label="Bitrate in megabits per second"
+ placeholder={t("auto")}
+ aria-label={t("bitrateLabel")}
disabled={prores}
className="h-6 w-16 border-0 bg-transparent px-0 text-sm shadow-none [appearance:textfield] focus-visible:ring-0 disabled:cursor-not-allowed [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
value={mbpsText}
@@ -464,16 +485,16 @@ export function ExportDialog() {
set({ bitrateMbps: v > 0 ? v : undefined });
}}
/>
- <span className="text-xs text-muted-foreground">Mbps</span>
+ <span className="text-xs text-muted-foreground">{t("mbps")}</span>
</label>
</Field>
{canStem && (
<Field
- label="Stems"
- hint="Saves one WAV per lane, dialogue and each soundtrack lane, zipped beside the video for mixing elsewhere."
+ label={t("stems")}
+ hint={t("stemsHint")}
>
<Switch
- aria-label="Export stems"
+ aria-label={t("exportStems")}
checked={withStems}
onCheckedChange={(v) => setWithStems(v === true)}
/>
@@ -481,11 +502,11 @@ export function ExportDialog() {
)}
{captionFiles.length > 0 && (
<Field
- label="Captions file"
- hint="Saves the captions as an SRT file to your Downloads folder, for platforms that take their own captions."
+ label={t("captionsFile")}
+ hint={t("captionsFileHint")}
>
<Switch
- aria-label="Save a captions file"
+ aria-label={t("saveCaptionsFile")}
checked={withCaptions}
onCheckedChange={(v) => setWithCaptions(v === true)}
/>
@@ -496,8 +517,7 @@ export function ExportDialog() {
{!inTab && (
<p className="text-xs leading-relaxed text-muted-foreground">
- This browser can&apos;t encode {prores ? "ProRes" : hdr ? "HDR" : "this"} itself, so it renders in the
- cloud and lands here when done.
+ {t("cloudRender", { kind: prores ? "prores" : hdr ? "hdr" : "other" })}
</p>
)}
</DialogBody>
@@ -505,17 +525,17 @@ export function ExportDialog() {
<DialogFooter className="mx-0 mb-0 flex-col gap-3 rounded-b-xl bg-muted/40 px-6 py-5 sm:flex-col">
<div className="flex items-center justify-between gap-3 text-sm text-muted-foreground">
<span className="truncate">
- {settings.width} × {settings.height} · {settings.fps} fps ·{" "}
+ {t("size", { width: settings.width, height: settings.height })} · {t("fps", { fps: settings.fps })} ·{" "}
{FORMATS.find((f) => f.id === formatId)?.label ?? formatId} · {settings.audioCodec.toUpperCase()}
- {hdr ? ` · ${OUTPUT_SPACES.find((o) => o.id === colorSpace)?.label}` : ""}
+ {hdr ? ` · ${t(`colorSpaces.${colorSpace}`)}` : ""}
{range ? ` · ${formatTime(span)}` : ""}
- {settings.loudness !== undefined ? ` · ${String(settings.loudness).replace("-", "−")} LUFS` : ""}
- {stems ? " · stems" : ""}
+ {settings.loudness !== undefined ? ` · ${t("lufs", { lufs: String(settings.loudness).replace("-", "−") })}` : ""}
+ {stems ? ` · ${t("stemsTag")}` : ""}
</span>
<span className="shrink-0 tabular-nums">{sizeEstimate}</span>
</div>
<Button className="h-11 w-full text-base" onClick={run} disabled={waiting}>
- {waiting ? "Reading the footage…" : "Export video"}
+ {waiting ? t("reading") : t("exportVideo")}
</Button>
</DialogFooter>
</DialogContent>
@@ -554,7 +574,7 @@ function PresetTile({
)}
onClick={onClick}
>
- {label}
+ <span className="truncate">{label}</span>
</button>
);
}
@@ -580,6 +600,7 @@ function Scale({
disabled?: boolean;
onIndex: (i: number) => void;
}) {
+ const t = useTranslations("editor.exportDialog");
const last = Math.max(0, stops.length - 1);
return (
<div className={cn("flex flex-col gap-1", disabled && "opacity-40")}>
@@ -596,7 +617,7 @@ function Scale({
value={index ?? 0}
onValueChange={(v) => onIndex(Array.isArray(v) ? v[0]! : v)}
/>
- <div className="relative h-4" role="radiogroup" aria-label={`${label} presets`}>
+ <div className="relative h-4" role="radiogroup" aria-label={t("scalePresets", { label })}>
{stops.map((s, i) => (
<button
key={s.label}
diff --git a/site/src/cut/components/ExportsDock.tsx b/site/src/cut/components/ExportsDock.tsx
index c4e15f78..f567a168 100644
--- a/site/src/cut/components/ExportsDock.tsx
+++ b/site/src/cut/components/ExportsDock.tsx
@@ -13,6 +13,7 @@ import {
Loader2,
X,
} from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { useElapsed } from "@/cut/hooks/useElapsed";
import { downloadExport, revealExport } from "@/cut/lib/exportClient";
@@ -28,6 +29,7 @@ import {
import { framedHref } from "@/cut/lib/hostBridge";
import { projectHref, useCutBase } from "@/cut/lib/nav";
import { cn } from "@/lib/utils";
+import { useDescribeError } from "@/i18n/describeError";
import { exportsDockOpen, inFlightCount, type DockChoice } from "@/cut/lib/exportsDockView";
/**
@@ -39,6 +41,7 @@ import { exportsDockOpen, inFlightCount, type DockChoice } from "@/cut/lib/expor
* Cut app layout, above the per-project editor.
*/
export function ExportsDock() {
+ const t = useTranslations("editor.exportsDock");
const [choice, setChoice] = useState<DockChoice>(null);
// Poll the feed while the dock is mounted (i.e. the whole time the app is up).
@@ -95,11 +98,11 @@ export function ExportsDock() {
<div className="fixed right-4 bottom-4 z-50 max-h-[calc(100dvh-2rem)] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-xl border border-border bg-card shadow-lg">
{(multi || !open || choice === "open") && (
<div className="flex items-center gap-2 px-3 py-2">
- <span className="text-xs font-semibold">Exports</span>
+ <span className="text-xs font-semibold">{t("title")}</span>
<span className="flex-1 truncate text-[11px] text-muted-foreground tabular-nums">
- {[running && `${running} running`, waiting && `${waiting} queued`]
+ {[running && t("running", { count: running }), waiting && t("queuedCount", { count: waiting })]
.filter(Boolean)
- .join(" · ") || `${items.length} done`}
+ .join(" · ") || t("doneCount", { count: items.length })}
</span>
{settled > 0 && (
<Button
@@ -108,13 +111,13 @@ export function ExportsDock() {
className="text-muted-foreground"
onClick={() => useExports.getState().dismissSettled()}
>
- Clear all
+ {t("clearAll")}
</Button>
)}
<Button
variant="ghost"
size="icon-xs"
- aria-label={open ? "Collapse exports" : "Expand exports"}
+ aria-label={open ? t("collapse") : t("expand")}
onClick={() => setChoice(open ? "closed" : "open")}
>
<ChevronDown className={cn("transition-transform", open && "rotate-180")} />
@@ -150,14 +153,15 @@ function StatusIcon({ status }: { status: string }) {
}
function ProjectName({ projectId, name }: { projectId: string; name?: string }) {
+ const t = useTranslations("editor.exportsDock");
const base = useCutBase();
return (
<Link
href={framedHref(projectHref(base, projectId, "projects"))}
className="block truncate text-xs font-medium hover:underline"
- title={name || "Untitled"}
+ title={name || t("untitled")}
>
- {name || "Untitled"}
+ {name || t("untitled")}
</Link>
);
}
@@ -165,6 +169,8 @@ function ProjectName({ projectId, name }: { projectId: string; name?: string })
function ExportRow({ job }: { job: ExportJob }) {
// The job's own backend, not the globally bound one: the row must keep
// working after the app rebinds to the other residency.
+ const t = useTranslations("editor.exportsDock");
+ const describeError = useDescribeError();
const backend = exportBackend(job.residency);
const caps = backend.caps;
const elapsed = useElapsed(job.status === "running" ? job.startedAt ?? null : null);
@@ -174,10 +180,10 @@ function ExportRow({ job }: { job: ExportJob }) {
job.status === "running"
? `${pct}%${elapsed ? ` · ${elapsed}` : ""}`
: job.status === "queued"
- ? "Queued"
+ ? t("queued")
: job.status === "done"
- ? "Ready"
- : job.error || "Export failed";
+ ? t("ready")
+ : describeError(job, t("exportFailed"));
return (
<div className="relative flex items-center gap-2.5 px-3 py-2">
@@ -202,13 +208,13 @@ function ExportRow({ job }: { job: ExportJob }) {
className="text-muted-foreground hover:text-destructive"
onClick={() => useExports.getState().cancel(job.id)}
>
- Cancel
+ {t("cancel")}
</Button>
<Button
variant="ghost"
size="icon-xs"
- aria-label="Dismiss"
- title="Hide — the export keeps running"
+ aria-label={t("dismiss")}
+ title={t("hide")}
onClick={() => useExports.getState().dismiss(job.id)}
>
<X />
@@ -223,8 +229,8 @@ function ExportRow({ job }: { job: ExportJob }) {
<Button
variant="ghost"
size="icon-xs"
- aria-label="Show in Finder"
- title="Show in Finder"
+ aria-label={t("showInFinder")}
+ title={t("showInFinder")}
onClick={() =>
void revealExport(job.projectId, job.outName!, backend).catch(() => {})
}
@@ -235,8 +241,8 @@ function ExportRow({ job }: { job: ExportJob }) {
<Button
variant="ghost"
size="icon-xs"
- aria-label="Download again"
- title="Download"
+ aria-label={t("downloadAgain")}
+ title={t("download")}
onClick={() => downloadExport(job.id, job.outName!, backend)}
>
<Download />
@@ -246,7 +252,7 @@ function ExportRow({ job }: { job: ExportJob }) {
<Button
variant="ghost"
size="icon-xs"
- aria-label="Dismiss"
+ aria-label={t("dismiss")}
onClick={() => useExports.getState().dismiss(job.id)}
>
<X />
@@ -257,7 +263,7 @@ function ExportRow({ job }: { job: ExportJob }) {
<Button
variant="ghost"
size="icon-xs"
- aria-label="Dismiss"
+ aria-label={t("dismiss")}
onClick={() => useExports.getState().dismiss(job.id)}
>
<X />
@@ -277,6 +283,8 @@ function ExportRow({ job }: { job: ExportJob }) {
}
function LocalRowView({ row }: { row: LocalRow }) {
+ const t = useTranslations("editor.exportsDock");
+ const describeError = useDescribeError();
const rendering = row.status === "rendering";
const pct = Math.round(Math.min(1, Math.max(0, row.progress ?? 0)) * 100);
return (
@@ -291,17 +299,17 @@ function LocalRowView({ row }: { row: LocalRow }) {
)}
>
{rendering
- ? `Rendering… ${pct}%`
+ ? t("rendering", { pct })
: row.status === "preparing"
- ? "Preparing…"
- : row.error || "Couldn't start export"}
+ ? t("preparing")
+ : describeError(row, t("startFailed"))}
</div>
</div>
<Button
variant="ghost"
size="icon-xs"
- aria-label="Dismiss"
- title={row.status === "error" ? "Dismiss" : "Hide — the export keeps running"}
+ aria-label={t("dismiss")}
+ title={row.status === "error" ? t("dismiss") : t("hide")}
onClick={() => useExports.getState().dismiss(row.id)}
>
<X />
diff --git a/site/src/cut/components/FlashPulseRows.tsx b/site/src/cut/components/FlashPulseRows.tsx
index fb7db95c..0d5870e0 100644
--- a/site/src/cut/components/FlashPulseRows.tsx
+++ b/site/src/cut/components/FlashPulseRows.tsx
@@ -1,16 +1,14 @@
"use client";
-import { EASE_IDS, EASE_LABELS, FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_TONES, type FlashFadeChoice, type FlashRhythm, type FlashPulse, type FlashTone } from "@donkeycut/effects-kit";
+import { useTranslations } from "next-intl";
+import { EASE_IDS, FLASH_FADE_CHOICES, FLASH_FADE_NONE, FLASH_RHYTHMS, FLASH_RATE_MAX, FLASH_TONES, type FlashFadeChoice, type FlashRhythm, type FlashPulse, type FlashTone } from "@donkeycut/effects-kit";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Row, useSliderCheckpoint } from "@/cut/components/panelBits";
import { parseNumberInput } from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
+import { useLabels } from "@/i18n/labels";
import { cn } from "@/lib/utils";
-const FLASH_TONE_LABELS: Record<FlashTone, string> = { white: "White", black: "Black" };
-const FLASH_RHYTHM_LABELS: Record<FlashRhythm, string> = { strobe: "Strobe", flicker: "Flicker" };
-const FLASH_FADE_LABELS: Record<FlashFadeChoice, string> = { none: "Off", to: "To", from: "From" };
-
/** How a write lands: `draft` while a slider drags (one undo step, closed by
* the checkpoint), `commit` for a single click. */
export type PulseWrite = "draft" | "commit";
@@ -25,7 +23,7 @@ function Segmented<T extends string>({ items, value, labels, onPick }: { items:
type="button"
aria-pressed={value === c}
className={cn(
- "flex-1 rounded-md px-1 py-1 whitespace-nowrap transition-colors",
+ "min-w-0 flex-1 truncate rounded-md px-1 py-1 whitespace-nowrap transition-colors",
value === c ? "bg-neutral-900 text-white" : "text-muted-foreground hover:text-foreground"
)}
onClick={() => onPick(c)}
@@ -42,28 +40,34 @@ function Segmented<T extends string>({ items, value, labels, onPick }: { items:
* effect element and a clip's own flash share these rows; defaults write as
* absence. */
export function FlashPulseRows({ pulse, write }: { pulse: FlashPulse; write: (patch: FlashPulse, how: PulseWrite) => void }) {
+ const t = useTranslations("timeline.flash");
const rateCk = useSliderCheckpoint();
+
+ // The segment names in the page's language, keyed by the choices' ids.
+ const toneLabels: Record<FlashTone, string> = { white: t("tones.white"), black: t("tones.black") };
+ const rhythmLabels: Record<FlashRhythm, string> = { strobe: t("rhythms.strobe"), flicker: t("rhythms.flicker") };
+ const off = t("off");
return (
<>
- <Row label="Tone">
+ <Row label={t("tone")}>
<Segmented
items={FLASH_TONES}
value={pulse.tone ?? "white"}
- labels={FLASH_TONE_LABELS}
+ labels={toneLabels}
onPick={(c) => write({ tone: c === "white" ? undefined : c }, "commit")}
/>
</Row>
- <Row label="Strobe">
+ <Row label={t("strobe")}>
<ValueSlider
- label="Strobe rate"
+ label={t("strobeRate")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={pulse.rate ?? 0}
min={0}
max={FLASH_RATE_MAX}
step={0.5}
- format={(v) => (v ? `${v}/s` : "Off")}
- parse={(raw) => (raw.trim().toLowerCase() === "off" ? 0 : parseNumberInput(raw.replace(/\/s$/, "")))}
+ format={(v) => (v ? `${v}/s` : off)}
+ parse={(raw) => (raw.trim().toLowerCase() === off.toLowerCase() ? 0 : parseNumberInput(raw.replace(/\/s$/, "")))}
onDraft={(v) => {
rateCk.begin();
write({ rate: v || undefined }, "draft");
@@ -76,11 +80,11 @@ export function FlashPulseRows({ pulse, write }: { pulse: FlashPulse; write: (pa
/>
</Row>
{!!pulse.rate && (
- <Row label="Rhythm">
+ <Row label={t("rhythm")}>
<Segmented
items={FLASH_RHYTHMS}
value={pulse.rhythm ?? "strobe"}
- labels={FLASH_RHYTHM_LABELS}
+ labels={rhythmLabels}
onPick={(c) => write({ rhythm: c === "strobe" ? undefined : c }, "commit")}
/>
</Row>
@@ -89,26 +93,30 @@ export function FlashPulseRows({ pulse, write }: { pulse: FlashPulse; write: (pa
);
}
-const FADE_EASE_ITEMS: Record<string, string> = Object.fromEntries(EASE_IDS.map((id) => [id, EASE_LABELS[id]]));
-
/** A flash element's fade: off (the pop), into the tone, or out of it, and
* the curve it runs along. Off and the even ramp write as absence. */
export function FlashFadeRow({ pulse, write }: { pulse: FlashPulse; write: (patch: FlashPulse, how: PulseWrite) => void }) {
+ const t = useTranslations("timeline.flash");
+ const easeLabel = useLabels("ease");
+
+ // The fade's segments and the curve menu's names, in the page's language.
+ const fadeLabels: Record<FlashFadeChoice, string> = { none: t("fades.none"), to: t("fades.to"), from: t("fades.from") };
+ const easeItems: Record<string, string> = Object.fromEntries(EASE_IDS.map((id) => [id, easeLabel(id)]));
return (
<>
- <Row label="Fade">
+ <Row label={t("fade")}>
<Segmented
items={FLASH_FADE_CHOICES}
value={pulse.fade ?? FLASH_FADE_NONE}
- labels={FLASH_FADE_LABELS}
+ labels={fadeLabels}
onPick={(c) => write({ fade: c === FLASH_FADE_NONE ? undefined : c }, "commit")}
/>
</Row>
{pulse.fade && (
- <Row label="Curve">
+ <Row label={t("curve")}>
<Select
value={pulse.fadeEase ?? "linear"}
- items={FADE_EASE_ITEMS}
+ items={easeItems}
onValueChange={(id) => write({ fadeEase: id === "linear" ? undefined : (id as FlashPulse["fadeEase"]) }, "commit")}
>
<SelectTrigger className="h-8 w-36 text-[12px]">
@@ -117,7 +125,7 @@ export function FlashFadeRow({ pulse, write }: { pulse: FlashPulse; write: (patc
<SelectContent>
{EASE_IDS.map((id) => (
<SelectItem key={id} value={id} className="text-[12px]">
- {EASE_LABELS[id]}
+ {easeLabel(id)}
</SelectItem>
))}
</SelectContent>
diff --git a/site/src/cut/components/FontPicker.tsx b/site/src/cut/components/FontPicker.tsx
index 29503bcd..b3aed6b0 100644
--- a/site/src/cut/components/FontPicker.tsx
+++ b/site/src/cut/components/FontPicker.tsx
@@ -11,6 +11,7 @@
*/
import { Loader2, Upload } from "lucide-react";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import {
Select,
@@ -32,6 +33,7 @@ import {
uploadLibraryFont,
} from "@/cut/lib/linkedLibrary";
import { allFonts, fontStack, onFontsChanged } from "@/cut/lib/types";
+import { useDescribeError } from "@/i18n/describeError";
import { cn } from "@/lib/utils";
/** Room left either side of the menu inside its panel. */
@@ -102,6 +104,8 @@ export function FontPicker({
}) {
// The menu re-reads the registry when the bundled families finish registering
// or a shelf font lands (the bump re-renders, and the render re-reads).
+ const t = useTranslations("inspector.fontPicker");
+ const describeError = useDescribeError();
const [, bump] = useState(0);
const again = () => bump((n) => n + 1);
useEffect(() => onFontsChanged(again), []);
@@ -140,14 +144,14 @@ export function FontPicker({
);
if (!file) {
if (files?.length)
- setError("That file has no font in it. Try a .ttf, .otf or .woff.");
+ setError(t("noFontInFile"));
setBusy(false);
return;
}
try {
onChange(await uploadLibraryFont(file));
} catch (e) {
- setError(e instanceof Error ? e.message : "Could not add that font.");
+ setError(describeError(e, t("addFailed")));
} finally {
setBusy(false);
}
@@ -178,7 +182,7 @@ export function FontPicker({
fontSize: rowSize(fontStack(value)),
}}
>
- <SelectValue placeholder="Mixed" />
+ <SelectValue placeholder={t("mixed")} />
</SelectTrigger>
{/* The menu is the field's own width: a face's name sets in a face
that runs wide, and the panel it drops out of is narrow. */}
@@ -194,7 +198,7 @@ export function FontPicker({
<>
<SelectSeparator />
<SelectGroup>
- <SelectLabel>Custom fonts</SelectLabel>
+ <SelectLabel>{t("customFonts")}</SelectLabel>
{mine.map(row)}
</SelectGroup>
</>
@@ -207,7 +211,7 @@ export function FontPicker({
) : (
<Upload className="size-3.5" />
)}
- {busy ? "Adding font…" : "Upload font…"}
+ {busy ? t("adding") : t("upload")}
</span>
</SelectItem>
</SelectContent>
diff --git a/site/src/cut/components/FontSpecimen.tsx b/site/src/cut/components/FontSpecimen.tsx
index 3b0b9a66..dfb252d9 100644
--- a/site/src/cut/components/FontSpecimen.tsx
+++ b/site/src/cut/components/FontSpecimen.tsx
@@ -1,7 +1,8 @@
"use client";
+import { useTranslations } from "next-intl";
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
-import { isCurrentSpecimen, SPECIMEN_TEXT } from "@/cut/lib/fontSpecimen";
+import { isCurrentSpecimen } from "@/cut/lib/fontSpecimen";
import { linkIdForAsset, onLinkedChanged } from "@/cut/lib/linkedLibrary";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { fontStack, hasFont, onFontsChanged } from "@/cut/lib/types";
@@ -46,6 +47,8 @@ export function FontSpecimen({
pad?: number;
className?: string;
}) {
+ const t = useTranslations("inspector.fontSpecimen");
+ const specimen = t("pangram");
const [gen, bump] = useState(0);
const [broken, setBroken] = useState(false);
const again = () => bump((n) => n + 1);
@@ -109,7 +112,7 @@ export function FontSpecimen({
ro.disconnect();
fonts?.removeEventListener?.("loadingdone", fit);
};
- }, [family, gen, pad]);
+ }, [family, gen, pad, specimen]);
if (poster && isCurrentSpecimen(poster) && !broken && !installed)
return (
// eslint-disable-next-line @next/next/no-img-element -- library media file, not Next-optimizable
@@ -133,7 +136,7 @@ export function FontSpecimen({
aria-hidden
className="pointer-events-none invisible fixed top-0 left-0 leading-[1.2]"
>
- {SPECIMEN_TEXT}
+ {specimen}
</span>
<span
className="leading-[1.2]"
@@ -141,7 +144,7 @@ export function FontSpecimen({
// sheet stays blank until the face itself is in.
style={{ fontSize: size || undefined, opacity: size && installed ? 1 : 0, paddingInline: pad }}
>
- {SPECIMEN_TEXT}
+ {specimen}
</span>
{!installed && (
// Lines of type-shaped shimmer while the face loads.
diff --git a/site/src/cut/components/GenerateCost.tools.ts b/site/src/cut/components/GenerateCost.tools.ts
index 975ddf31..0c13c950 100644
--- a/site/src/cut/components/GenerateCost.tools.ts
+++ b/site/src/cut/components/GenerateCost.tools.ts
@@ -6,12 +6,13 @@
*/
import { obj, type AiToolDef } from "@/cut/lib/aiToolDef";
+import { DEFAULT_LOCALE } from "@/i18n/locales";
import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";
export const CREDIT_TOOLS = [
{
name: "credit_prices",
- description: `What each hosted generation costs right now, in credits (${creditCountLabel(creditsPerDollar)} = $1): a video by resolution and length in seconds ("auto" is the model's own length), one image, a music track by length, and a minute of voiceover; plus the account's credit balance. Call it before quoting a price or when the user asks what something costs or how much they have left. Chat and edits bill by use and have no set price. Needs the user signed in to Donkey.`,
+ description: `What each hosted generation costs right now, in credits (${creditCountLabel(creditsPerDollar, DEFAULT_LOCALE)} = $1): a video by resolution and length in seconds ("auto" is the model's own length), one image, a music track by length, and a minute of voiceover; plus the account's credit balance. Call it before quoting a price or when the user asks what something costs or how much they have left. Chat and edits bill by use and have no set price. Needs the user signed in to Donkey.`,
inputSchema: obj({}),
},
] as const satisfies readonly AiToolDef[];
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index d1b7c8c4..e88d78f7 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
+import { useTranslations } from "next-intl";
import { Copy, Film, Loader2, Maximize2, Plus, RotateCw, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -27,15 +28,14 @@ import { nearestAspect } from "@/cut/lib/types";
import { useLocalPref } from "@/cut/lib/uiState";
import { useVideoGen } from "@/cut/lib/videoGen";
import {
- VIDEO_ASPECT_LABEL,
VIDEO_MODELS,
- VIDEO_RESOLUTION_LABEL,
type VideoAspect,
type VideoModelOption,
type VideoResolution,
DEFAULT_VIDEO_RESOLUTION,
} from "@/cut/lib/videoModels";
import { videoRenderMicros } from "@/lib/credits/price-sheet";
+import { useLabels } from "@/i18n/labels";
import { cn } from "@/lib/utils";
import { CopyHandlePill, MentionTextarea, RefChips } from "./AssetRefs";
import { DictationControl } from "./MicDictation";
@@ -53,12 +53,15 @@ import { ScrollArea } from "@/components/ui/scroll-area";
// takes one input image, so the first reference's picture becomes the start
// frame.
-const ASPECT_WORD: Record<VideoAspect, string> = {
- "16:9": "Landscape",
- "9:16": "Portrait",
+const ASPECT_WORD: Record<VideoAspect, "landscape" | "portrait"> = {
+ "16:9": "landscape",
+ "9:16": "portrait",
};
export function GenerateVideoPanel({ projectId }: { projectId: string }) {
+ const t = useTranslations("media");
+ const aspectLabel = useLabels("videoAspect");
+ const resolutionLabel = useLabels("videoResolution");
const readOnly = useEditor((s) => s.readOnly);
const signedIn = useSignedIn();
const allJobs = useGenerate((s) => s.jobs);
@@ -99,10 +102,10 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
// model's longest clip.
const cost = useGenerateCost((sheet) => videoRenderMicros(sheet, effResolution, effDuration));
const durationOptions = [
- { value: "auto", label: "Auto length" },
+ { value: "auto", label: t("generateVideo.autoLength") },
...Array.from({ length: maxSeconds - minSeconds + 1 }, (_, i) => {
const s = minSeconds + i;
- return { value: String(s), label: `${s} seconds` };
+ return { value: String(s), label: t("generateVideo.seconds", { count: s }) };
}),
];
@@ -141,7 +144,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
return (
<>
<div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">
- <span className="text-sm font-semibold tracking-tight">Generate video</span>
+ <span className="text-sm font-semibold tracking-tight">{t("generateVideo.title")}</span>
</div>
<ScrollArea
@@ -172,7 +175,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
{stockTitle(character.id)}
</span>
<button
- title="Leave character mode"
+ title={t("generateVideo.leaveCharacter")}
className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground hover:text-foreground"
onClick={() => useVideoGen.getState().clearCharacter()}
>
@@ -191,8 +194,8 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
className="gen-prompt min-h-[88px] w-full resize-y bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
placeholder={
character
- ? "What should they say?"
- : "A drone shot rising over a foggy coastline at sunrise… Drop media in or type @ to reference it."
+ ? t("generateVideo.characterPlaceholder")
+ : t("generateVideo.placeholder")
}
value={prompt}
onChange={(v) => useVideoGen.getState().setPrompt(v)}
@@ -220,7 +223,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
below are its shape, its output size, and its length. */}
<PillSelect
className="h-7 shrink-0"
- title="Model"
+ title={t("generateVideo.model")}
value={tier}
display={model.model}
options={VIDEO_MODELS.map((m) => ({
@@ -235,12 +238,12 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
{/* Shape, the same pill family as the image panel. */}
<PillSelect
className="h-7 shrink-0"
- title="Aspect ratio"
+ title={t("generateVideo.aspectRatio")}
value={effAspect}
- display={ASPECT_WORD[effAspect]}
+ display={t(`aspectWord.${ASPECT_WORD[effAspect]}`)}
options={model.aspects.map((a) => ({
value: a,
- label: VIDEO_ASPECT_LABEL[a],
+ label: aspectLabel(a),
}))}
onChange={(v) => useVideoGen.getState().setAspect(v)}
/>
@@ -249,12 +252,12 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
cost more per second. */}
<PillSelect
className="h-7 shrink-0"
- title="Resolution"
+ title={t("generateVideo.resolution")}
value={effResolution}
- display={VIDEO_RESOLUTION_LABEL[effResolution]}
+ display={resolutionLabel(effResolution)}
options={model.resolutions.map((r) => ({
value: r,
- label: VIDEO_RESOLUTION_LABEL[r],
+ label: resolutionLabel(r),
}))}
onChange={(v) => useVideoGen.getState().setResolution(v)}
/>
@@ -262,9 +265,13 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
{/* Length: a fixed number of seconds, or the model's own pick. */}
<PillSelect
className="h-7 shrink-0"
- title="Length"
+ title={t("generateVideo.length")}
value={effDuration === null ? "auto" : String(effDuration)}
- display={effDuration === null ? "Auto" : `${effDuration}s`}
+ display={
+ effDuration === null
+ ? t("generateVideo.auto")
+ : t("generateVideo.secondsShort", { count: effDuration })
+ }
options={durationOptions}
onChange={(v) =>
useVideoGen.getState().setDurationSeconds(v === "auto" ? null : Number(v))
@@ -277,20 +284,22 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
onClick={button.onClick}
>
<Sparkles data-icon="inline-start" />
- Generate video
+ {t("generateVideo.button")}
</Button>
{signedIn === false ? (
<p className="gen-signin shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- Generating runs on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("signInToGenerate", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
) : (
<p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- Renders take a minute or two. Keep editing while it runs.
+ {t("generateVideo.rendersTake")}
</p>
)}
</>)}
@@ -318,6 +327,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
* gradient, and the actions overlay the corners. In-flight and failed jobs
* stay a compact status row. */
function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
+ const t = useTranslations("media.generateVideo");
const asset = useEditor((s) => s.assets.find((a) => a.id === job.assetId));
const readOnly = useEditor((s) => s.readOnly);
const pulse = useGenPulse("video", job.assetId);
@@ -348,13 +358,13 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
>
{job.status === "running" ? (
<>
- Rendering…{" "}
+ {t("rendering")}{" "}
{elapsed && (
<span className="tabular-nums text-muted-foreground/80">{elapsed}</span>
)}
</>
) : (
- <HostedErrorText error={job.error} />
+ <HostedErrorText error={job} />
)}
</div>
</div>
@@ -362,7 +372,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
<div className="flex shrink-0 items-center gap-1">
{job.status === "error" && !readOnly && (
<button
- title="Retry"
+ title={t("retry")}
className={cardIconButton}
onClick={() => useGenerate.getState().retry(job.id)}
>
@@ -370,7 +380,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
</button>
)}
<button
- title="Dismiss"
+ title={t("dismiss")}
className={cn(cardIconButton, "opacity-0 group-hover:opacity-100")}
onClick={() => useGenerate.getState().dismiss(job.id)}
>
@@ -422,14 +432,14 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
</div>
<div className="absolute top-1 right-1 flex gap-1">
<button
- title="Add to timeline"
+ title={t("addToTimeline")}
className="grid size-5 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:brightness-110"
onClick={() => useEditor.getState().addAssetAtPlayhead(asset.id)}
>
<Plus className="size-3" />
</button>
<button
- title="Expand"
+ title={t("expand")}
className="grid size-5 place-items-center rounded-full bg-black/45 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/65"
onClick={() =>
useLightbox.getState().open({
@@ -454,7 +464,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
before={
<>
<DropdownMenuItem onClick={() => useVideoGen.getState().openWith(job.prompt)}>
- <Sparkles /> Use this prompt
+ <Sparkles /> {t("useThisPrompt")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
@@ -463,7 +473,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
.catch(() => {})
}
>
- <Copy /> Copy reference
+ <Copy /> {t("copyReference")}
</DropdownMenuItem>
</>
}
diff --git a/site/src/cut/components/GeneratedAssetMenu.tsx b/site/src/cut/components/GeneratedAssetMenu.tsx
index 234c3fa9..f7cabd7e 100644
--- a/site/src/cut/components/GeneratedAssetMenu.tsx
+++ b/site/src/cut/components/GeneratedAssetMenu.tsx
@@ -2,6 +2,7 @@
import { useState, type ReactNode } from "react";
import { Clapperboard, Download, Ellipsis, FolderPlus, Trash2 } from "lucide-react";
+import { useTranslations } from "next-intl";
import {
AlertDialog,
AlertDialogAction,
@@ -39,7 +40,7 @@ export function GeneratedAssetMenu({
before,
after,
onDelete,
- deleteLabel = "Delete",
+ deleteLabel,
}: {
asset: MediaAsset;
projectId: string;
@@ -49,6 +50,7 @@ export function GeneratedAssetMenu({
onDelete?: () => void;
deleteLabel?: string;
}) {
+ const t = useTranslations("home.generatedMenu");
// Timeline items the delete would take with it; null = no prompt open.
const [confirmUses, setConfirmUses] = useState<number | null>(null);
@@ -65,8 +67,8 @@ export function GeneratedAssetMenu({
<>
<DropdownMenu>
<DropdownMenuTrigger
- aria-label="More actions"
- title="More actions"
+ aria-label={t("moreActions")}
+ title={t("moreActions")}
className={triggerClassName}
>
<Ellipsis className="size-3.5" />
@@ -81,7 +83,7 @@ export function GeneratedAssetMenu({
useEditor.getState().updateAsset(asset.id, { origin: undefined, chatId: undefined })
}
>
- <Clapperboard /> Add to Media
+ <Clapperboard /> {t("addToMedia")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
@@ -90,19 +92,19 @@ export function GeneratedAssetMenu({
})
}
>
- <FolderPlus /> Add to Library
+ <FolderPlus /> {t("addToLibrary")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => downloadMedia(projectId, asset)}
disabled={!!asset.upload}
>
- <Download /> Download
+ <Download /> {t("download")}
</DropdownMenuItem>
{(after != null || onDelete) && <DropdownMenuSeparator />}
{after}
{onDelete && (
<DropdownMenuItem variant="destructive" onClick={remove}>
- <Trash2 /> {deleteLabel}
+ <Trash2 /> {deleteLabel ?? t("delete")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
@@ -110,16 +112,13 @@ export function GeneratedAssetMenu({
<AlertDialog open={confirmUses !== null} onOpenChange={(o) => !o && setConfirmUses(null)}>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>Delete “{asset.name}”?</AlertDialogTitle>
+ <AlertDialogTitle>{t("deleteTitle", { name: asset.name })}</AlertDialogTitle>
<AlertDialogDescription>
- {confirmUses === 1
- ? "It plays in 1 place on the timeline, which goes with it."
- : `It plays in ${confirmUses} places on the timeline, which go with it.`}{" "}
- The media file is deleted too, and this can’t be undone.
+ {t("timelineUses", { count: confirmUses ?? 0 })} {t("fileGoes")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive/10 text-destructive hover:bg-destructive/20"
onClick={() => {
@@ -127,7 +126,7 @@ export function GeneratedAssetMenu({
onDelete?.();
}}
>
- Delete
+ {t("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/site/src/cut/components/GroupPanel.tsx b/site/src/cut/components/GroupPanel.tsx
index a065d6e4..9ba8ce73 100644
--- a/site/src/cut/components/GroupPanel.tsx
+++ b/site/src/cut/components/GroupPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useMemo, useState } from "react";
+import { useTranslations } from "next-intl";
import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, FlipHorizontal2, FlipVertical2, Italic, StretchHorizontal, Type } from "lucide-react";
import { hasOverlayKeys, hasSpeedCurve, LETTER_SPACING_MIN, lineLikeShape, poseAt, retimeOf, ZOOM_LEVELS, ZOOM_RAMP_MAX, zoomRampOf } from "@donkeycut/effects-kit";
import { ColorField } from "@/cut/components/ColorField";
@@ -13,7 +14,7 @@ import { parseNumberInput, parsePercentInput, parseSecondsInput, parseSpeedInput
import { ValueSlider } from "@/cut/components/ValueSlider";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { selectionCenter, selectionSummary, selectionTranslation, sharedNumber, sharedValue } from "@/cut/lib/groupEdit";
+import { selectionCenter, selectionCounts, selectionTranslation, sharedNumber, sharedValue } from "@/cut/lib/groupEdit";
import { usePanelState } from "@/cut/lib/panelState";
import { usePreviewTime } from "@/cut/lib/playhead";
import { clipWindow, maxClipFade, useEditor } from "@/cut/lib/store";
@@ -47,6 +48,7 @@ import {
type VideoClip,
} from "@/cut/lib/types";
import { cn } from "@/lib/utils";
+import type { Messages } from "@/i18n/namespaces";
/**
* The panel for several items at once: a group, or any multi-selection. It
@@ -58,6 +60,7 @@ import { cn } from "@/lib/utils";
* what one title, clip, shape, sticker or effect can set, several can.
*/
export function GroupPanel({ selection }: { selection: readonly NonNullable<Selection>[] }) {
+ const t = useTranslations("media.groupPanel");
const overlays = useEditor((s) => s.overlays);
const clips = useEditor((s) => s.clips);
const audios = useEditor((s) => s.audioClips);
@@ -72,7 +75,7 @@ export function GroupPanel({ selection }: { selection: readonly NonNullable<Sele
}, [selection, overlays, clips, audios]);
const all = [...items.overlays, ...items.clips, ...items.audios];
const group = sharedValue(all.map((it) => it.groupId));
- const title = !group.mixed && group.value ? "Group" : `${all.length} items`;
+ const title = !group.mixed && group.value ? t("group") : t("items", { count: all.length });
const texts = items.overlays.filter(isTextOverlay);
const shapes = items.overlays.filter(isShapeOverlay);
const stickers = items.overlays.filter(isStickerOverlay);
@@ -107,7 +110,7 @@ export function GroupPanel({ selection }: { selection: readonly NonNullable<Sele
<span className="truncate text-sm font-semibold tracking-tight">{title}</span>
</div>
<div className="flex flex-col gap-1 px-3.5 pb-4">
- <div className="mb-1 text-[11px] text-muted-foreground">{selectionSummary(items)}</div>
+ <div className="mb-1 text-[11px] text-muted-foreground">{selectionCounts(items).map(([kind, count]) => t(`summary.${kind}`, { count })).join(" · ")}</div>
{onlyOverlays && texts.length === items.overlays.length && <TextRows texts={texts} />}
{onlyOverlays && shapes.length === items.overlays.length && <ShapeRows shapes={shapes} />}
{onlyOverlays && stickers.length === items.overlays.length && <StickerRows stickers={stickers} />}
@@ -167,11 +170,24 @@ const formatPercent = (v: number) => `${Math.round(v * 100)}%`;
const formatSpeed = (v: number) => `${v.toFixed(2)}×`;
const parsePercentText = (raw: string) => parseNumberInput(raw.replace(/%$/, ""));
+// The align toggles' names, by the alignment each sets.
+const ALIGN_LABEL = { left: "alignLeft", center: "alignCenter", right: "alignRight" } as const;
+
+/** A zoom depth's catalog key; the kit's ids are "shallow", "moderate", "deep". */
+type ZoomLevelId = keyof Messages["media"]["groupPanel"]["zoomLevels"];
+
+/** Typed "off" in the duck field reads as off, in English or the page's word. */
+const isOffWord = (raw: string, off: string) => {
+ const word = raw.trim().toLowerCase();
+ return word === "off" || word === off.toLowerCase();
+};
+
function MixedSwitch({ label, values, onChange }: { label: string; values: boolean[]; onChange: (v: boolean) => void }) {
+ const t = useTranslations("media.groupPanel");
const shared = sharedValue(values);
return (
<Row label={label}>
- {shared.mixed && <Value className="text-muted-foreground italic">Mixed</Value>}
+ {shared.mixed && <Value className="text-muted-foreground italic">{t("mixed")}</Value>}
<Switch checked={!shared.mixed && shared.value} onCheckedChange={onChange} aria-label={label} />
</Row>
);
@@ -219,6 +235,7 @@ function MixedSeg<T extends string>({
* An effect has no transform: it joins the Hidden row and nothing else.
*/
function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoClip[]; audios: AudioClip[] } }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const now = usePreviewTime();
const { clips, audios } = items;
@@ -273,7 +290,7 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
const hidden = [...items.overlays.map((o) => !!o.hidden), ...clips.map((c) => !!c.hidden), ...audios.map((a) => !!a.hidden)];
const hiddenRow = (
<MixedSwitch
- label="Hidden"
+ label={t("hidden")}
values={hidden}
onChange={(v) =>
write.once(() => {
@@ -287,14 +304,14 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
// Sound and effects have no transform: such a selection shares only Hidden.
if (!visual) return hiddenRow;
return (
- <Section title="Transform">
+ <Section title={t("transform")}>
{overlays.length > 0 && !clips.length && (
- <Row label="Position">
+ <Row label={t("position")}>
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`${axis.toUpperCase()} position`}
+ label={axis === "x" ? t("xPosition") : t("yPosition")}
className="w-9 text-muted-foreground"
value={center[axis] * 100}
min={clampOverlayPos(-Infinity, grouped) * 100}
@@ -311,9 +328,9 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
))}
</Row>
)}
- <Row label="Rotation">
+ <Row label={t("rotation")}>
<ValueSlider
- label="Rotation"
+ label={t("rotation")}
{...SLIDER}
value={rotation.value}
mixed={rotation.mixed}
@@ -327,9 +344,9 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
onCommit={(v) => write.commit(() => rotate(v))}
/>
</Row>
- <Row label="Opacity">
+ <Row label={t("opacity")}>
<ValueSlider
- label="Opacity"
+ label={t("opacity")}
{...SLIDER}
value={opacity.value}
mixed={opacity.mixed}
@@ -351,6 +368,7 @@ function TransformRows({ items }: { items: { overlays: Overlay[]; clips: VideoCl
* weight and slant, alignment, size, spacing, text box width, color, outline,
* shadow and backdrop. */
function TextRows({ texts }: { texts: TextOverlay[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const font = sharedValue(texts.map((t) => t.font));
const size = sharedNumber(texts.map((t) => t.size));
@@ -396,15 +414,15 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
return (
<>
<StylePresetsRow overlay={texts[0]} peers={texts} />
- <Field label="Font">
+ <Field label={t("font")}>
<FontPicker value={font.value} mixed={font.mixed} onChange={(id) => write.once(() => set({ font: id as TextOverlay["font"] }))} />
</Field>
<div className="mt-1 flex items-center gap-2">
<SegGroup>
- <SegToggle label="Bold" active={!bold.mixed && bold.value} onClick={() => write.once(() => set({ weight: bold.mixed || !bold.value ? 700 : 400 }))}>
+ <SegToggle label={t("bold")} active={!bold.mixed && bold.value} onClick={() => write.once(() => set({ weight: bold.mixed || !bold.value ? 700 : 400 }))}>
<Bold />
</SegToggle>
- <SegToggle label="Italic" active={!italic.mixed && italic.value} onClick={() => write.once(() => set({ italic: italic.mixed || !italic.value ? true : undefined }))}>
+ <SegToggle label={t("italic")} active={!italic.mixed && italic.value} onClick={() => write.once(() => set({ italic: italic.mixed || !italic.value ? true : undefined }))}>
<Italic />
</SegToggle>
</SegGroup>
@@ -418,7 +436,7 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
).map(([a, Icon]) => (
<SegToggle
key={a}
- label={`Align ${a}`}
+ label={t(ALIGN_LABEL[a])}
active={!align.mixed && align.value === a}
onClick={() => write.once(() => set({ align: a === "center" ? undefined : a }))}
>
@@ -427,7 +445,7 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
))}
</SegGroup>
<NumberField
- label="Text size"
+ label={t("textSize")}
className="ml-auto w-[74px]"
icon={<Type />}
value={size.value}
@@ -443,9 +461,9 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
/>
</div>
<div className="mt-1 grid grid-cols-2 gap-2">
- <Field label="Line height">
+ <Field label={t("lineHeight")}>
<NumberField
- label="Line height"
+ label={t("lineHeight")}
icon={<AlignVerticalSpaceAround />}
value={lineHeight.value}
mixed={lineHeight.mixed}
@@ -460,9 +478,9 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
onCommit={(v) => write.commit(() => set({ lineHeight: Math.abs(v - 1.25) < 0.025 ? undefined : v }))}
/>
</Field>
- <Field label="Letter spacing">
+ <Field label={t("letterSpacing")}>
<NumberField
- label="Letter spacing"
+ label={t("letterSpacing")}
icon={<AlignHorizontalSpaceAround />}
value={letterSpacing.value}
mixed={letterSpacing.mixed}
@@ -478,59 +496,59 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
/>
</Field>
</div>
- <Field label="Text width">
- <NumberField label="Text box width" icon={<StretchHorizontal />} value={wrapWidth.value} mixed={wrapWidth.mixed}
- min={0} max={200} step={1} presets={TEXT_WIDTHS} format={(v) => v === 0 ? "Auto" : `${Math.round(v)}%`} parse={parsePercentText}
+ <Field label={t("textWidth")}>
+ <NumberField label={t("textBoxWidth")} icon={<StretchHorizontal />} value={wrapWidth.value} mixed={wrapWidth.mixed}
+ min={0} max={200} step={1} presets={TEXT_WIDTHS} format={(v) => v === 0 ? t("auto") : `${Math.round(v)}%`} parse={parsePercentText}
onDraft={(v) => write.draft(() => set({ wrapWidth: v > 0 ? v / 100 : undefined }))}
onCommit={(v) => write.commit(() => set({ wrapWidth: v > 0 ? v / 100 : undefined }))}
/>
</Field>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={color.value}
mixed={color.mixed}
- label="Text color"
+ label={t("textColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set({ color: c })}
onCommit={(c) => write.once(() => set({ color: c }))}
/>
</Row>
<Section
- title="Outline"
+ title={t("outline")}
enabled={outlined}
onEnabledChange={(v) => write.once(() => setEach((t) => ({ stroke: v ? (t.stroke ?? { color: "#111114", width: 0.04 }) : undefined })))}
>
{outlined && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={strokeColor.value}
mixed={strokeColor.mixed}
- label="Outline color"
+ label={t("outlineColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => setEach((t) => ({ stroke: { ...t.stroke!, color: c } }))}
onCommit={(c) => write.once(() => setEach((t) => ({ stroke: { ...t.stroke!, color: c } })))}
/>
</Row>
- {slide("Width", strokeWidth, { min: 1, max: 15, step: 0.5, snap: [4] }, (v) => String(Math.round(v)), parseNumberInput, (v) =>
+ {slide(t("width"), strokeWidth, { min: 1, max: 15, step: 0.5, snap: [4] }, (v) => String(Math.round(v)), parseNumberInput, (v) =>
setEach((t) => ({ stroke: { ...t.stroke!, width: v / 100 } }))
)}
</>
)}
</Section>
- <Section title="Shadow" enabled={shadowed} onEnabledChange={(v) => write.once(() => set({ shadow: v }))}>
+ <Section title={t("shadow")} enabled={shadowed} onEnabledChange={(v) => write.once(() => set({ shadow: v }))}>
{shadowed && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={shadowColor.value}
mixed={shadowColor.mixed}
- label="Shadow color"
+ label={t("shadowColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => setEach((t) => ({ shadow: { ...shadowOf(t), color: c } }))}
onCommit={(c) => write.once(() => setEach((t) => ({ shadow: { ...shadowOf(t), color: c } })))}
opacity={{
- label: "Shadow opacity",
+ label: t("shadowOpacity"),
value: shadowOpacity.value,
mixed: shadowOpacity.mixed,
onDraft: (v) => write.draft(() => setEach((t) => ({ shadow: { ...shadowOf(t), opacity: v } }))),
@@ -538,25 +556,25 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
}}
/>
</Row>
- {slide("Blur", shadowBlur, { min: 0, max: 60, step: 1, snap: [14] }, (v) => String(Math.round(v)), parseNumberInput, (v) =>
+ {slide(t("blur"), shadowBlur, { min: 0, max: 60, step: 1, snap: [14] }, (v) => String(Math.round(v)), parseNumberInput, (v) =>
setEach((t) => ({ shadow: { ...shadowOf(t), blur: v } }))
)}
</>
)}
</Section>
- <Section title="Backdrop" enabled={plated} onEnabledChange={(v) => write.once(() => set({ plate: v }))}>
+ <Section title={t("backdrop")} enabled={plated} onEnabledChange={(v) => write.once(() => set({ plate: v }))}>
{plated && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={plateColor.value}
mixed={plateColor.mixed}
- label="Backdrop color"
+ label={t("backdropColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set({ plateColor: c })}
onCommit={(c) => write.once(() => set({ plateColor: c }))}
opacity={{
- label: "Backdrop opacity",
+ label: t("backdropOpacity"),
value: plateOpacity.value,
mixed: plateOpacity.mixed,
onDraft: (v) => write.draft(() => set({ plateOpacity: v })),
@@ -564,7 +582,7 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
}}
/>
</Row>
- {slide("Radius", plateRadius, { min: 0, max: 1, step: 0.01, snap: [PLATE_RADIUS] }, (v) => String(Math.round(v * 100)), parsePercentInput, (v) =>
+ {slide(t("radius"), plateRadius, { min: 0, max: 1, step: 0.01, snap: [PLATE_RADIUS] }, (v) => String(Math.round(v * 100)), parsePercentInput, (v) =>
set({ plateRadius: v })
)}
</>
@@ -576,6 +594,7 @@ function TextRows({ texts }: { texts: TextOverlay[] }) {
/** Fill, corner radius and outline, over a selection of shapes only. */
function ShapeRows({ shapes }: { shapes: ShapeOverlay[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const boxes = shapes.every((s) => !lineLikeShape(s.shape));
const rects = shapes.every((s) => s.shape === "rect");
@@ -588,18 +607,18 @@ function ShapeRows({ shapes }: { shapes: ShapeOverlay[] }) {
const set = (patch: (s: ShapeOverlay) => OverlayPatch) => patchOverlays(shapes, (o) => patch(o as ShapeOverlay));
return (
<>
- <Row label={boxes ? "Fill" : "Color"}>
+ <Row label={boxes ? t("fill") : t("color")}>
<ColorField
value={fill.value}
mixed={fill.mixed}
- label={boxes ? "Fill color" : "Shape color"}
+ label={boxes ? t("fillColor") : t("shapeColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set(() => ({ fill: c }))}
onCommit={(c) => write.once(() => set(() => ({ fill: c })))}
opacity={
boxes
? {
- label: "Fill opacity",
+ label: t("fillOpacity"),
value: fillOpacity.value,
mixed: fillOpacity.mixed,
onDraft: (v) => write.draft(() => set(() => ({ fillOpacity: v >= 0.995 ? undefined : v }))),
@@ -610,9 +629,9 @@ function ShapeRows({ shapes }: { shapes: ShapeOverlay[] }) {
/>
</Row>
{rects && (
- <Row label="Corner radius">
+ <Row label={t("cornerRadius")}>
<ValueSlider
- label="Corner radius"
+ label={t("cornerRadius")}
{...SLIDER}
value={radius.value}
mixed={radius.mixed}
@@ -628,25 +647,25 @@ function ShapeRows({ shapes }: { shapes: ShapeOverlay[] }) {
)}
{boxes && (
<Section
- title="Outline"
+ title={t("outline")}
enabled={outlined}
onEnabledChange={(v) => write.once(() => set((s) => ({ stroke: v ? (s.stroke ?? { color: "#111114", width: 6 }) : undefined })))}
>
{outlined && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={strokeColor.value}
mixed={strokeColor.mixed}
- label="Outline color"
+ label={t("outlineColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set((s) => ({ stroke: { ...s.stroke!, color: c } }))}
onCommit={(c) => write.once(() => set((s) => ({ stroke: { ...s.stroke!, color: c } })))}
/>
</Row>
- <Row label="Width">
+ <Row label={t("width")}>
<ValueSlider
- label="Outline width"
+ label={t("outlineWidth")}
{...SLIDER}
value={strokeWidth.value}
mixed={strokeWidth.mixed}
@@ -670,12 +689,13 @@ function ShapeRows({ shapes }: { shapes: ShapeOverlay[] }) {
/** Size, over a selection of stickers only. */
function StickerRows({ stickers }: { stickers: StickerOverlay[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const size = sharedNumber(stickers.map((s) => s.w));
return (
- <Row label="Size">
+ <Row label={t("size")}>
<ValueSlider
- label="Sticker size"
+ label={t("stickerSize")}
{...SLIDER}
value={size.value}
mixed={size.mixed}
@@ -695,6 +715,7 @@ function StickerRows({ stickers }: { stickers: StickerOverlay[] }) {
* one is a zoom, amount otherwise. Where a zoom lands is aimed on its own
* picture, so the focus stays per effect. */
function EffectRows({ effects }: { effects: EffectOverlay[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const amount = sharedNumber(effects.map((e) => e.amount ?? 0.5));
const set = (patch: OverlayPatch) => patchOverlays(effects, () => patch);
@@ -702,7 +723,7 @@ function EffectRows({ effects }: { effects: EffectOverlay[] }) {
const ramp = sharedNumber(effects.map((e) => zoomRampOf(e.ramp)));
return (
<>
- <Row label="Depth" grow>
+ <Row label={t("depth")} grow>
<div className="flex min-w-0 grow rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
{ZOOM_LEVELS.map((l) => {
const active = !amount.mixed && Math.abs(amount.value - l.amount) < 0.01;
@@ -717,15 +738,15 @@ function EffectRows({ effects }: { effects: EffectOverlay[] }) {
)}
onClick={() => write.once(() => set({ amount: l.amount }))}
>
- {l.label}
+ {t(`zoomLevels.${l.id as ZoomLevelId}`)}
</button>
);
})}
</div>
</Row>
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Zoom speed"
+ label={t("zoomSpeed")}
{...SLIDER}
value={ramp.value}
mixed={ramp.mixed}
@@ -742,9 +763,9 @@ function EffectRows({ effects }: { effects: EffectOverlay[] }) {
);
}
return (
- <Row label="Amount">
+ <Row label={t("amount")}>
<ValueSlider
- label="Effect amount"
+ label={t("effectAmount")}
{...SLIDER}
value={amount.value}
mixed={amount.mixed}
@@ -767,6 +788,7 @@ function EffectRows({ effects }: { effects: EffectOverlay[] }) {
* clip's own switch, ducking and fades belong to soundtrack clips.
*/
function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios: AudioClip[]; onOpenSound: () => void }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
// A clip's rate lands once, on release: changing it resettles the row.
const [speedDraft, setSpeedDraft] = useState<number | null>(null);
@@ -811,9 +833,9 @@ function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios:
);
return (
<>
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Speed"
+ label={t("speed")}
{...SLIDER}
value={speedDraft ?? speed.value}
mixed={speedDraft === null && speed.mixed}
@@ -833,7 +855,7 @@ function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios:
/>
</Row>
<MixedSwitch
- label="Reverse"
+ label={t("reverse")}
values={[...clips.map((c) => !!c.reverse), ...audios.map((a) => !!a.reverse)]}
onChange={(v) =>
write.batch(() => {
@@ -842,9 +864,9 @@ function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios:
})
}
/>
- <Row label="Volume">
+ <Row label={t("volume")}>
<ValueSlider
- label="Volume"
+ label={t("volume")}
{...SLIDER}
value={volume.value}
mixed={volume.mixed}
@@ -860,30 +882,30 @@ function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios:
</Row>
{clips.length > 0 && (
<MixedSwitch
- label="Mute audio"
+ label={t("muteAudio")}
values={clips.map((c) => c.muted)}
onChange={(v) => write.once(() => patchClips(clips, () => ({ muted: v })))}
/>
)}
{audios.length > 0 && !clips.length && (
- <Row label="Duck others">
+ <Row label={t("duckOthers")}>
<ValueSlider
- label="Duck others"
+ label={t("duckOthers")}
{...SLIDER}
value={duck.value}
mixed={duck.mixed}
min={0}
max={1}
step={0.05}
- format={(v) => (v >= 0.999 ? "Off" : formatPercent(v))}
- parse={(raw) => (raw.trim().toLowerCase() === "off" ? 1 : parsePercentInput(raw))}
+ format={(v) => (v >= 0.999 ? t("off") : formatPercent(v))}
+ parse={(raw) => (isOffWord(raw, t("off")) ? 1 : parsePercentInput(raw))}
onDraft={(v) => write.draft(() => patchAudios(audios, () => ({ duck: v < 0.999 ? v : undefined })))}
onCommit={(v) => write.commit(() => patchAudios(audios, () => ({ duck: v < 0.999 ? v : undefined })))}
/>
</Row>
)}
- {audios.length > 0 && !clips.length && fadeRow("Fade in", "fadeIn", fadeIn)}
- {audios.length > 0 && !clips.length && fadeRow("Fade out", "fadeOut", fadeOut)}
+ {audios.length > 0 && !clips.length && fadeRow(t("fadeIn"), "fadeIn", fadeIn)}
+ {audios.length > 0 && !clips.length && fadeRow(t("fadeOut"), "fadeOut", fadeOut)}
<SoundQualityRow sound={sound} onOpen={onOpenSound} />
</>
);
@@ -892,25 +914,26 @@ function SoundRows({ clips, audios, onOpenSound }: { clips: VideoClip[]; audios:
/** Framing, zoom and flip over a selection of video clips. Pan stays per
* clip: where a picture has slack depends on that clip's own footage. */
function ClipPictureRows({ clips }: { clips: VideoClip[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const fit = sharedValue(clips.map((c) => c.fit ?? "fit"));
const zoom = sharedNumber(clips.map(clipZoom));
const flips = (key: "flipH" | "flipV") => sharedValue(clips.map((c) => !!c[key]));
return (
<>
- <Row label="Framing">
+ <Row label={t("framing")}>
<MixedSeg
options={[
- { id: "fit", label: "Fit" },
- { id: "fill", label: "Fill" },
+ { id: "fit", label: t("fit") },
+ { id: "fill", label: t("fill") },
]}
shared={fit}
onPick={(mode) => write.once(() => patchClips(clips, () => ({ fit: mode, panX: 0, panY: 0 })))}
/>
</Row>
- <Row label="Zoom">
+ <Row label={t("zoom")}>
<ValueSlider
- label="Zoom"
+ label={t("zoom")}
{...SLIDER}
value={zoom.value}
mixed={zoom.mixed}
@@ -925,12 +948,12 @@ function ClipPictureRows({ clips }: { clips: VideoClip[] }) {
onCommit={(v) => write.commit(() => patchClips(clips, () => ({ zoom: v > 1.001 ? v : undefined })))}
/>
</Row>
- <Row label="Flip">
+ <Row label={t("flip")}>
<div className="flex rounded-lg border border-input p-0.5">
{(
[
- ["flipH", "Flip horizontal", FlipHorizontal2],
- ["flipV", "Flip vertical", FlipVertical2],
+ ["flipH", t("flipHorizontal"), FlipHorizontal2],
+ ["flipV", t("flipVertical"), FlipVertical2],
] as const
).map(([key, label, Icon]) => {
const shared = flips(key);
@@ -962,6 +985,7 @@ function ClipPictureRows({ clips }: { clips: VideoClip[] }) {
/** Corner radius, border width and color over a selection of video clips. */
function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const bordered = clips.every((c) => !!c.boxStyle);
const width = sharedNumber(clips.map((c) => c.boxStyle?.borderWidth ?? 0));
@@ -970,7 +994,7 @@ function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
const set = (patch: Partial<BoxStyle>) => patchClips(clips, (c) => ({ boxStyle: { ...liveClip(c).boxStyle, ...patch } }));
return (
<Section
- title="Border"
+ title={t("border")}
enabled={bordered}
onEnabledChange={(v) =>
write.once(() =>
@@ -980,9 +1004,9 @@ function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
>
{bordered && (
<>
- <Row label="Width">
+ <Row label={t("width")}>
<ScrubValue
- label="Border width"
+ label={t("borderWidth")}
className="w-9 text-muted-foreground"
value={width.value}
min={0}
@@ -994,9 +1018,9 @@ function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
onCommit={(v) => write.commit(() => set({ borderWidth: v }))}
/>
</Row>
- <Row label="Radius">
+ <Row label={t("radius")}>
<ScrubValue
- label="Corner radius"
+ label={t("cornerRadius")}
className="w-9 text-muted-foreground"
value={radius.value}
min={0}
@@ -1008,11 +1032,11 @@ function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
onCommit={(v) => write.commit(() => set({ radius: v }))}
/>
</Row>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={color.value}
mixed={color.mixed}
- label="Border color"
+ label={t("borderColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set({ borderColor: c })}
onCommit={(c) => write.once(() => set({ borderColor: c }))}
@@ -1026,6 +1050,7 @@ function ClipBorderRows({ clips }: { clips: VideoClip[] }) {
/** Drop shadow over a selection of video clips. */
function ClipShadowRows({ clips }: { clips: VideoClip[] }) {
+ const t = useTranslations("media.groupPanel");
const write = useGroupWrite();
const shadowed = clips.every((c) => !!c.boxStyle?.shadow);
const blur = sharedNumber(clips.map((c) => c.boxStyle?.shadow?.blur ?? 24));
@@ -1054,7 +1079,7 @@ function ClipShadowRows({ clips }: { clips: VideoClip[] }) {
);
return (
<Section
- title="Shadow"
+ title={t("shadow")}
enabled={shadowed}
onEnabledChange={(v) =>
write.once(() =>
@@ -1070,8 +1095,8 @@ function ClipShadowRows({ clips }: { clips: VideoClip[] }) {
>
{shadowed && (
<>
- <Row label="Blur">{scrub("Shadow blur", blur, { min: 0, max: 120 }, (v) => set({ blur: v }))}</Row>
- <Row label="Offset">
+ <Row label={t("blur")}>{scrub(t("shadowBlur"), blur, { min: 0, max: 120 }, (v) => set({ blur: v }))}</Row>
+ <Row label={t("offset")}>
{(
[
["x", offsetX],
@@ -1080,13 +1105,13 @@ function ClipShadowRows({ clips }: { clips: VideoClip[] }) {
).map(([axis, shared]) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
- {scrub(`Shadow ${axis.toUpperCase()} offset`, shared, { min: -120, max: 120 }, (v) => set({ [axis]: Math.round(v) || undefined }))}
+ {scrub(axis === "x" ? t("shadowXOffset") : t("shadowYOffset"), shared, { min: -120, max: 120 }, (v) => set({ [axis]: Math.round(v) || undefined }))}
</span>
))}
</Row>
- <Row label="Opacity">
+ <Row label={t("opacity")}>
<ValueSlider
- label="Shadow opacity"
+ label={t("shadowOpacity")}
{...SLIDER}
value={opacity.value}
mixed={opacity.mixed}
@@ -1099,11 +1124,11 @@ function ClipShadowRows({ clips }: { clips: VideoClip[] }) {
onCommit={(v) => write.commit(() => set({ opacity: v }))}
/>
</Row>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={color.value}
mixed={color.mixed}
- label="Shadow color"
+ label={t("shadowColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => set({ color: c })}
onCommit={(c) => write.once(() => set({ color: c }))}
diff --git a/site/src/cut/components/GuideOverlay.tsx b/site/src/cut/components/GuideOverlay.tsx
index 5ff1cc97..eb9da805 100644
--- a/site/src/cut/components/GuideOverlay.tsx
+++ b/site/src/cut/components/GuideOverlay.tsx
@@ -1,6 +1,7 @@
"use client";
import type React from "react";
+import { useTranslations } from "next-intl";
import { startDrag } from "@/cut/lib/drag";
import { useEditor } from "@/cut/lib/store";
import { guideGeometry, type GuideGeometry } from "@/cut/lib/guides";
@@ -109,6 +110,7 @@ export function GuideHandles({ stage }: { stage: { w: number; h: number } }) {
* Custom lines draw in blue; GuideHandles, inside the stage, moves them.
*/
export function GuideOverlay({ stage }: { stage: { w: number; h: number } }) {
+ const t = useTranslations("timeline.guides");
const geo = useGuideGeometry();
if (!geo) return null;
const { w, h } = stage;
@@ -164,7 +166,7 @@ export function GuideOverlay({ stage }: { stage: { w: number; h: number } }) {
paintOrder="stroke"
style={{ fontFamily: "ui-sans-serif, system-ui, sans-serif" }}
>
- {b.label}
+ {t(`regions.${b.region}`)}
</text>
)}
</g>
diff --git a/site/src/cut/components/GuidesMenu.tsx b/site/src/cut/components/GuidesMenu.tsx
index 15c1d233..9e0800f6 100644
--- a/site/src/cut/components/GuidesMenu.tsx
+++ b/site/src/cut/components/GuidesMenu.tsx
@@ -1,6 +1,7 @@
"use client";
import { ChevronDown, Grid3x3 } from "lucide-react";
+import { useFormatter, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -12,7 +13,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { GUIDE_PRESETS, guideFits } from "@/cut/lib/guides";
+import { GUIDE_PRESETS, guideFits, MARGIN_INSET, type GuideId } from "@/cut/lib/guides";
import { useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
@@ -21,18 +22,32 @@ import { cn } from "@/lib/utils";
* first press with nothing picked turns on the safe margins. The icon lights
* while any guide is showing. */
export function GuidesMenu() {
+ const t = useTranslations("timeline.guides");
+ const format = useFormatter();
const aspect = useEditor((s) => s.aspect);
const guides = useEditor((s) => s.guides);
const guidesHidden = useEditor((s) => s.guidesHidden);
const showing = guides.length > 0 && !guidesHidden;
const toggle = () => useEditor.getState().toggleGuidesShown();
+
+ // A preset's second line, for the presets that carry one: the margins name
+ // their inset, e.g. "5% inset".
+ const sublabel = (id: GuideId) => {
+ if (id === "margins") {
+ return t("sublabels.margins", { inset: format.number(MARGIN_INSET, { style: "percent" }) });
+ }
+ if (id === "shortform" || id === "custom") {
+ return t(`sublabels.${id}`);
+ }
+ return null;
+ };
return (
<div className="mr-2 flex items-center overflow-hidden rounded-md border border-border">
<Button
variant="ghost"
size="icon-xs"
- aria-label={showing ? "Hide guides" : "Show guides"}
- title={showing ? "Hide guides (⌘;)" : "Show guides (⌘;)"}
+ aria-label={showing ? t("hide") : t("show")}
+ title={showing ? t("hideTitle", { key: "⌘;" }) : t("showTitle", { key: "⌘;" })}
aria-pressed={showing}
className="rounded-r-none"
onClick={toggle}
@@ -45,8 +60,8 @@ export function GuidesMenu() {
<Button
variant="ghost"
size="icon-xs"
- aria-label="Guide presets"
- title="Guide presets"
+ aria-label={t("presetsLabel")}
+ title={t("presetsLabel")}
className="w-4 rounded-l-none"
/>
}
@@ -55,9 +70,10 @@ export function GuidesMenu() {
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
<DropdownMenuGroup>
- <DropdownMenuLabel>Guides</DropdownMenuLabel>
+ <DropdownMenuLabel>{t("heading")}</DropdownMenuLabel>
{GUIDE_PRESETS.map((g) => {
const fits = guideFits(g.id, aspect);
+ const sub = sublabel(g.id);
return (
<DropdownMenuCheckboxItem
key={g.id}
@@ -67,10 +83,10 @@ export function GuidesMenu() {
onCheckedChange={() => useEditor.getState().toggleGuide(g.id)}
>
<span className="flex-1">
- {g.name}
- {g.sublabel && (
+ {t(`presets.${g.id}`)}
+ {sub && (
<span className="block text-[10.5px] text-muted-foreground">
- {fits ? g.sublabel : "Portrait frames"}
+ {fits ? sub : t("portraitOnly")}
</span>
)}
</span>
@@ -80,10 +96,10 @@ export function GuidesMenu() {
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem closeOnClick={false} onClick={() => useEditor.getState().addGuideLine("v")}>
- Add vertical line
+ {t("addVertical")}
</DropdownMenuItem>
<DropdownMenuItem closeOnClick={false} onClick={() => useEditor.getState().addGuideLine("h")}>
- Add horizontal line
+ {t("addHorizontal")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsx
index edb47dd9..738660cc 100644
--- a/site/src/cut/components/ImageGenPanel.tsx
+++ b/site/src/cut/components/ImageGenPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
+import { useTranslations } from "next-intl";
import { Copy, Loader2, Maximize2, Sparkles, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -42,10 +43,10 @@ import { ScrollArea } from "@/components/ui/scroll-area";
// References ride along as input images: drag any image or video in (stock
// tile, media card, library clip, timeline clip) or mention it by @name.
-const ASPECT_WORD: Record<ImageAspect, string> = {
- "16:9": "Landscape",
- "9:16": "Portrait",
- "1:1": "Square",
+const ASPECT_WORD: Record<ImageAspect, "landscape" | "portrait" | "square"> = {
+ "16:9": "landscape",
+ "9:16": "portrait",
+ "1:1": "square",
};
// The resolution tier fixes the long edge (4K caps at the model's 4096×4096 max);
@@ -62,6 +63,7 @@ function pixelDims(aspect: ImageAspect, resolution: ImageResolution): string {
}
export function ImageGenPanel({ projectId }: { projectId: string }) {
+ const t = useTranslations("media");
const { prompt, aspect, resolution, refs } = useImageGen();
const readOnly = useEditor((s) => s.readOnly);
const signedIn = useSignedIn();
@@ -112,7 +114,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
return (
<div ref={attachTarget} {...targetProps} className="relative flex min-h-0 flex-1 flex-col">
<div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">
- <span className="text-sm font-semibold tracking-tight">Generate image</span>
+ <span className="text-sm font-semibold tracking-tight">{t("generateImage.title")}</span>
</div>
<ScrollArea className="min-h-0 flex-1" contentClassName="flex flex-col gap-3 px-3.5 pb-4">
@@ -134,7 +136,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
/>
<MentionTextarea
className="min-h-[100px] w-full resize-y bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
- placeholder="A neon-lit street market at night, cinematic… Drop an image in or type @ to reference one."
+ placeholder={t("generateImage.placeholder")}
value={prompt}
onChange={(v) => useImageGen.getState().setPrompt(v)}
candidates={candidates}
@@ -162,17 +164,17 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
<div className="flex shrink-0 items-center gap-2">
<PillSelect
className="min-w-0 flex-1"
- title="Aspect ratio"
+ title={t("generateImage.aspectRatio")}
value={aspect}
- display={ASPECT_WORD[aspect]}
+ display={t(`aspectWord.${ASPECT_WORD[aspect]}`)}
options={(Object.keys(ASPECT_WORD) as ImageAspect[]).map((a) => ({
value: a,
- label: `${ASPECT_WORD[a]} · ${a}`,
+ label: t("generateImage.aspectOption", { word: t(`aspectWord.${ASPECT_WORD[a]}`), ratio: a }),
}))}
onChange={(v) => useImageGen.getState().setAspect(v)}
/>
<PillSelect
- title="Resolution"
+ title={t("generateImage.resolution")}
value={resolution}
display={resolution}
options={(Object.keys(IMAGE_RESOLUTION_LABEL) as ImageResolution[]).map((r) => ({
@@ -189,16 +191,18 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
onClick={button.onClick}
>
<Sparkles data-icon="inline-start" />
- Generate image
+ {t("generateImage.button")}
</Button>
{signedIn === false && (
<p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- Generating runs on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("signInToGenerate", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
)}
</>)}
@@ -214,7 +218,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {
{generated.length > 0 && (
<div className="flex shrink-0 flex-col gap-1.5">
- <SectionTitle>Generated</SectionTitle>
+ <SectionTitle>{t("generateImage.generated")}</SectionTitle>
{generated.map((a) => (
<GeneratedTile
key={a.id}
@@ -244,6 +248,7 @@ function GeneratedTile({
projectId: string;
handle?: string;
}) {
+ const t = useTranslations("media.generateImage");
const tileRef = useRef<HTMLDivElement>(null);
const pulse = useGenPulse("image", asset.id);
const { picked, pick } = useAssetPick(asset.id);
@@ -287,7 +292,7 @@ function GeneratedTile({
</div>
<div className="absolute top-1 right-1 flex gap-1">
<button
- title="Expand"
+ title={t("expand")}
className="grid size-5 place-items-center rounded-full bg-black/45 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/65"
onClick={() =>
useLightbox.getState().open({
@@ -308,7 +313,7 @@ function GeneratedTile({
before={
<>
<DropdownMenuItem onClick={() => useImageGen.getState().openWith(asset.name)}>
- <Sparkles /> Use this prompt
+ <Sparkles /> {t("useThisPrompt")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
@@ -317,7 +322,7 @@ function GeneratedTile({
.catch(() => {})
}
>
- <Copy /> Copy reference
+ <Copy /> {t("copyReference")}
</DropdownMenuItem>
</>
}
@@ -326,7 +331,7 @@ function GeneratedTile({
variant="destructive"
onClick={() => useEditor.getState().removeAsset(asset.id)}
>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
}
/>
@@ -339,6 +344,7 @@ function GeneratedTile({
/** A generation in flight (or failed) as a compact status row with a live
* elapsed clock while it renders. */
function ImageJobRow({ job }: { job: GenerateJob }) {
+ const t = useTranslations("media.generateImage");
const elapsed = useElapsed(job.status === "running" ? job.startedAt : null);
return (
<div className="group flex shrink-0 items-center gap-2">
@@ -355,17 +361,17 @@ function ImageJobRow({ job }: { job: GenerateJob }) {
>
{job.status === "running" ? (
<>
- Generating…{" "}
+ {t("generating")}{" "}
{elapsed && <span className="tabular-nums text-muted-foreground/80">{elapsed}</span>}
</>
) : (
- <HostedErrorText error={job.error} />
+ <HostedErrorText error={job} />
)}
</div>
</div>
{job.status === "error" && (
<button
- title="Dismiss"
+ title={t("dismiss")}
className={cn(cardIconButton, "opacity-0 group-hover:opacity-100")}
onClick={() => useGenerate.getState().dismiss(job.id)}
>
diff --git a/site/src/cut/components/ImportVideoPoster.tsx b/site/src/cut/components/ImportVideoPoster.tsx
index 072de88e..6b807f66 100644
--- a/site/src/cut/components/ImportVideoPoster.tsx
+++ b/site/src/cut/components/ImportVideoPoster.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useEffectEvent, useState } from "react";
import { Film } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Skeleton } from "@/components/ui/skeleton";
import { importPoster, type ImportPosterFrame } from "@/cut/lib/importPoster";
import { holdMemory } from "@/cut/lib/memoryBudget";
@@ -22,6 +23,7 @@ type Props = {
* browser has none: what stands in for a clip still arriving on a shelf, or
* one whose media element cannot show its picture. */
export function ImportVideoPoster({ source, name, size, onShape, onFrame, onUnreadable }: Props) {
+ const t = useTranslations("editor.importPoster");
const [visible, setVisible] = useState(false);
const [poster, setPoster] = useState<string>();
const [unreadable, setUnreadable] = useState(false);
@@ -70,7 +72,7 @@ export function ImportVideoPoster({ source, name, size, onShape, onFrame, onUnre
<img src={poster} alt={name} className="size-full object-cover" />
) : unreadable ? (
<div className="flex size-full items-center justify-center bg-muted text-muted-foreground">
- <Film className="size-8" aria-label="Video" />
+ <Film className="size-8" aria-label={t("video")} />
</div>
) : <Skeleton className="size-full rounded-none" />}
</div>
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 79621fa7..f4a5df9c 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1,6 +1,7 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, ChevronLeft, ChevronRight, Diamond, FlipHorizontal2, FlipVertical2, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PanelTopClose, PenTool, Plus, Scissors, Smile, Sparkles, StretchHorizontal, Trash2, Type, User, Volume2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -57,7 +58,6 @@ import {
EDGE_BLUR_MAX,
EDGE_DISTANCE_MAX,
EASE_IDS,
- EASE_LABELS,
type EaseId,
edgeOwnReach,
edgePreset,
@@ -219,6 +219,9 @@ import {
} from "@/cut/lib/textMotion";
import { getPreviewCanvas } from "@/cut/lib/previewCanvas";
import { cn } from "@/lib/utils";
+import { useDescribeError } from "@/i18n/describeError";
+import { useLabels } from "@/i18n/labels";
+import type { Messages } from "@/i18n/namespaces";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Field, ResetButton, Row, Section, SegGroup, SegToggle, Tip, useSliderCheckpoint, Value } from "@/cut/components/panelBits";
import { ColorPanel } from "@/cut/components/ColorPanel";
@@ -310,6 +313,7 @@ const tenthDeg = (v: number) => Math.round(v * 10) / 10;
const formatDeg = (v: number) => `${tenthDeg(v)}°`;
function ShowTimelineButton() {
+ const t = useTranslations("inspector.rail");
const open = useEditor((s) => s.timelineOpen);
if (open) return null;
return (
@@ -317,37 +321,39 @@ function ShowTimelineButton() {
<TooltipProvider>
<Tooltip>
<TooltipTrigger
- aria-label="Show timeline"
+ aria-label={t("showTimeline")}
onClick={() => useEditor.getState().setTimelineOpen(true)}
className="grid size-8 place-items-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground"
>
<PanelTopClose className="size-4" />
</TooltipTrigger>
- <TooltipContent side="top">Show timeline</TooltipContent>
+ <TooltipContent side="top">{t("showTimeline")}</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
);
}
-/** A view the rail opens beside Home. */
-type RailTab = { id: string; label: string; Icon: LucideIcon };
+/** A view the rail opens beside Home; it names itself under
+ * `inspector.rail.tabs`. */
+type RailTab = { id: RailTabId; Icon: LucideIcon };
+type RailTabId = "color" | "cutout" | "frame" | "animate" | "audio";
/** The video clip's deep views, in rail order under Home. */
const CLIP_TABS: readonly RailTab[] = [
- { id: "color", label: "Color", Icon: Palette },
- { id: "cutout", label: "Cutout", Icon: Scissors },
- { id: "frame", label: "Frame", Icon: Frame },
- { id: "animate", label: "Animation", Icon: Sparkles },
- { id: "audio", label: "Audio", Icon: Volume2 },
+ { id: "color", Icon: Palette },
+ { id: "cutout", Icon: Scissors },
+ { id: "frame", Icon: Frame },
+ { id: "animate", Icon: Sparkles },
+ { id: "audio", Icon: Volume2 },
];
/** An overlay's one deep view: its animation. */
-const ANIM_TAB: RailTab = { id: "animate", label: "Animation", Icon: Sparkles };
+const ANIM_TAB: RailTab = { id: "animate", Icon: Sparkles };
/** The deep views a selection of video clips shares. */
const GROUP_CLIP_TABS: readonly RailTab[] = [
- { id: "color", label: "Color", Icon: Palette },
+ { id: "color", Icon: Palette },
ANIM_TAB,
];
@@ -487,12 +493,13 @@ function InspectorRail({
// A running matte bake shows on the Cutout tab itself, so the work stays
// visible from any view.
const baking = useMatteBakes((s) => !!clipId && s.jobs[clipId]?.status === "running");
+ const t = useTranslations("inspector.rail");
return (
<div className="pointer-events-auto flex min-h-0 flex-col items-center rounded-xl border bg-background p-1 shadow-md">
<ScrollArea className="min-h-0 w-full" viewportClassName="overscroll-contain" contentClassName="flex flex-col items-center gap-1">
- <RailButton id="home" label="Home" Icon={House} active={view === "main"} onClick={() => onPick("main")} />
- {tabs.map(({ id, label, Icon }) => (
- <RailButton key={id} id={id} label={label} Icon={Icon} active={view === id} onClick={() => onPick(id)}>
+ <RailButton id="home" label={t("home")} Icon={House} active={view === "main"} onClick={() => onPick("main")} />
+ {tabs.map(({ id, Icon }) => (
+ <RailButton key={id} id={id} label={t(`tabs.${id}`)} Icon={Icon} active={view === id} onClick={() => onPick(id)}>
{id === "cutout" && baking && (
<Loader2 className="absolute top-1 right-1 size-2.5 animate-spin" />
)}
@@ -502,7 +509,7 @@ function InspectorRail({
<div className="my-1 h-px w-5 shrink-0 bg-border" />
<RailButton
id="toggle"
- label={open ? "Hide panel" : "Show panel"}
+ label={open ? t("hidePanel") : t("showPanel")}
Icon={open ? PanelRightClose : PanelRightOpen}
active={false}
onClick={onToggle}
@@ -603,14 +610,26 @@ function InlineName({
/** An element panel's title: the element's name, renamed in place. The
* timeline chip and chat references show the same name. */
function ElementTitle({ overlay: o }: { overlay: Overlay }) {
+ const t = useTranslations("inspector.titles");
+ const shapeLabel = useLabels("shape");
+ const effectLabel = useLabels("effect");
const update = useEditor((s) => s.updateOverlay);
+ // What the element is, standing in for a name: a title's text, a shape's
+ // kind, an effect's name, or "Sticker", in the page's language.
+ const kindName = isTextOverlay(o)
+ ? overlayName({ ...o, name: undefined } as Overlay)
+ : isShapeOverlay(o)
+ ? shapeLabel(o.shape)
+ : isEffectOverlay(o)
+ ? effectLabel(o.effect)
+ : t("sticker");
return (
<div className="flex h-10 shrink-0 items-center px-3.5">
<InlineName
key={o.id}
- label="Element name"
+ label={t("elementName")}
name={o.name}
- fallback={overlayName({ ...o, name: undefined } as Overlay) || "Text"}
+ fallback={kindName || t("text")}
onRename={(name) => update(o.id, { name })}
/>
</div>
@@ -632,13 +651,14 @@ function ClipHead({
time: string;
onRename: (name: string | undefined) => void;
}) {
+ const t = useTranslations("inspector.titles");
return (
<div className="mb-1.5 flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border">
<InlineName
key={clip.id}
- label="Clip name"
+ label={t("clipName")}
name={clip.name}
- fallback={fileName?.trim() || "Clip"}
+ fallback={fileName?.trim() || t("clip")}
onRename={onRename}
/>
<Value className="shrink-0 text-muted-foreground">{time}</Value>
@@ -683,16 +703,17 @@ function LayoutButtons({
/** Narrow the box to the source's own shape, dropping the margins. */
onSourceAspect?: () => void;
}) {
+ const t = useTranslations("inspector.layout");
const currentId =
(Object.keys(LAYOUTS) as LayoutId[]).find((id) => LAYOUTS[id].label === regionLabel(rect)) ??
"full";
return (
<>
<div className="flex items-center justify-between gap-2 py-1">
- <span className="text-[11.5px] font-medium text-muted-foreground">Layout</span>
+ <span className="text-[11.5px] font-medium text-muted-foreground">{t("title")}</span>
<Select
value={currentId}
- items={Object.fromEntries((Object.keys(LAYOUTS) as LayoutId[]).map((id) => [id, LAYOUTS[id].label]))}
+ items={Object.fromEntries((Object.keys(LAYOUTS) as LayoutId[]).map((id) => [id, t(`layouts.${id}`)]))}
onValueChange={(id) => {
const L = LAYOUTS[id as LayoutId];
onPick(id === "full" ? undefined : { ...L.rect }, L.fit);
@@ -704,19 +725,19 @@ function LayoutButtons({
<SelectContent>
{(Object.keys(LAYOUTS) as LayoutId[]).map((id) => (
<SelectItem key={id} value={id} className="text-[12px]">
- {LAYOUTS[id].label}
+ {t(`layouts.${id}`)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{onSourceAspect && (
- <Row label="Shape">
+ <Row label={t("shape")}>
<button
className="clip-source-aspect rounded-md border border-input px-2 py-0.5 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
onClick={onSourceAspect}
>
- Match source
+ {t("matchSource")}
</button>
</Row>
)}
@@ -750,6 +771,7 @@ function ClipColumn({ clip, tab }: { clip: VideoClip; tab: string }) {
/** Header for a view: its name, with a back chevron when the view sits
* inside another one. The band the Color view opens with. */
function SubviewHead({ title, onBack }: { title: string; onBack?: () => void }) {
+ const t = useTranslations("inspector.titles");
return (
<div
className={cn(
@@ -760,7 +782,7 @@ function SubviewHead({ title, onBack }: { title: string; onBack?: () => void })
{onBack && (
<button
type="button"
- aria-label="Back"
+ aria-label={t("back")}
className="grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={onBack}
>
@@ -775,9 +797,10 @@ function SubviewHead({ title, onBack }: { title: string; onBack?: () => void })
/** The Frame view: what the clip's box does — its pose keyframes, border,
* shadow, and mask. */
function ClipFramePanel({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.rail");
return (
<>
- <SubviewHead title="Frame" />
+ <SubviewHead title={t("tabs.frame")} />
<div className="flex flex-col gap-1 px-3.5 pb-4">
<ClipTransformSection clip={clip} />
<CameraCardSection clip={clip} />
@@ -804,6 +827,7 @@ function ClipAudioPanel({ clip }: { clip: VideoClip }) {
if (phase === "commit") ck.end();
};
const [view, setView] = usePanelState<"main" | "sound">(clip.id, "audioView", "main");
+ const t = useTranslations("inspector.clipAudio");
if (view === "sound") {
return (
<SoundQualityPanel itemId={clip.id} sound={clip.sound} write={writeSound} onBack={() => setView("main")} />
@@ -811,11 +835,11 @@ function ClipAudioPanel({ clip }: { clip: VideoClip }) {
}
return (
<>
- <SubviewHead title="Audio" />
+ <SubviewHead title={t("title")} />
<div className="flex flex-col gap-1 px-3.5 pb-4">
- <Row label="Volume">
+ <Row label={t("volume")}>
<ValueSlider
- label="Volume"
+ label={t("volume")}
sliderClassName="clip-volume data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={volume}
@@ -832,7 +856,7 @@ function ClipAudioPanel({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Mute audio">
+ <Row label={t("mute")}>
<Switch
checked={clip.muted}
onCheckedChange={(v) => updateClip(clip.id, { muted: v })}
@@ -841,10 +865,7 @@ function ClipAudioPanel({ clip }: { clip: VideoClip }) {
{asset?.type === "video" && <ClipSoundSource clip={clip} asset={asset} />}
{asset?.type === "video" && (!assetIsSilent(asset) || !!asset.soundFrom) && <ClipSplitEdit clip={clip} />}
{asset && !assetIsSilent(asset) && (
- <Row
- label="Beats"
- info="Beat markers detected from the clip's sound, drawn as dots along its bar. Every drag and trim snaps to them; drag a dot to move it, double-click removes it, ⌥-click the clip adds one."
- >
+ <Row label={t("beats")} info={t("beatsInfo")}>
<BeatsControl asset={asset} />
</Row>
)}
@@ -867,6 +888,8 @@ const CAMERA_SOUND = "camera";
* recording with no clear match is refused and the reason shown.
*/
function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }) {
+ const t = useTranslations("inspector.clipAudio");
+ const describeError = useDescribeError();
const assets = useEditor((s) => s.assets);
const recordings = useMemo(
() => assets.filter((a) => a.type === "audio" && !a.upload && a.duration > 0),
@@ -884,15 +907,12 @@ function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }
}
setSyncing(true);
void bindRecording(asset.id, id, clip)
- .catch((e: unknown) => setRefusal(e instanceof Error ? e.message : "Could not line the recording up."))
+ .catch((e: unknown) => setRefusal(describeError(e, t("syncFailed"))))
.finally(() => setSyncing(false));
};
return (
<>
- <Row
- label="Sound"
- info="Where this video's sound comes from. Pick an audio file recorded alongside it (a lav or a recorder) and it is lined up by matching it against the camera's sound; every clip of this video then plays the recording, through any trim, speed or split."
- >
+ <Row label={t("sound")} info={t("soundInfo")}>
{syncing && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
<Select value={bound ? bound.id : CAMERA_SOUND} onValueChange={(v) => pick(String(v))} disabled={syncing}>
<SelectTrigger className="clip-sound-source h-8 w-36 text-[12px]">
@@ -900,7 +920,7 @@ function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }
</SelectTrigger>
<SelectContent>
<SelectItem value={CAMERA_SOUND} className="text-[12px]">
- Camera
+ {t("camera")}
</SelectItem>
{recordings.map((r) => (
<SelectItem key={r.id} value={r.id} className="text-[12px]">
@@ -909,12 +929,13 @@ function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }
))}
</SelectContent>
</Select>
- <ResetButton title="Use the camera's sound" show={!!bound} onClick={() => pick(CAMERA_SOUND)} />
+ <ResetButton title={t("useCameraSound")} show={!!bound} onClick={() => pick(CAMERA_SOUND)} />
</Row>
{bound && asset.soundFrom && (
<p className="pb-1 text-[11.5px] text-muted-foreground">
- Synced {asset.soundFrom.offset >= 0 ? "+" : "−"}
- {Math.abs(asset.soundFrom.offset).toFixed(3)} s · every clip of this video plays it
+ {t("synced", {
+ offset: `${asset.soundFrom.offset >= 0 ? "+" : "−"}${Math.abs(asset.soundFrom.offset).toFixed(3)}`,
+ })}
</p>
)}
{refusal && <p className="pb-1 text-[11.5px] text-destructive">{refusal}</p>}
@@ -922,9 +943,13 @@ function ClipSoundSource({ clip, asset }: { clip: VideoClip; asset: MediaAsset }
);
}
-const formatSplit = (v: number) => (v > 0 ? `${v.toFixed(2)} s` : "Off");
-const parseSplitInput = (raw: string) =>
- /^off$/i.test(raw.trim()) ? 0 : parseNumberInput(raw.replace(/\s*s$/i, ""));
+/** A split edit's readout: its seconds, or the word for none. Typing that
+ * word (or "off") clears it. */
+const formatSplit = (v: number, off: string) => (v > 0 ? `${v.toFixed(2)} s` : off);
+const parseSplitInput = (raw: string, off: string) =>
+ /^off$/i.test(raw.trim()) || raw.trim().toLowerCase() === off.toLowerCase()
+ ? 0
+ : parseNumberInput(raw.replace(/\s*s$/i, ""));
/**
* The clip's split edit: its sound running ahead of the picture (a J-cut)
@@ -932,6 +957,8 @@ const parseSplitInput = (raw: string) =>
* and the clip's place on the timeline stay put.
*/
function ClipSplitEdit({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.clipAudio");
+ const off = t("off");
const updateClip = useEditor((s) => s.updateClip);
const [leadDraft, setLeadDraft] = useState<number | null>(null);
const [tailDraft, setTailDraft] = useState<number | null>(null);
@@ -951,8 +978,8 @@ function ClipSplitEdit({ clip }: { clip: VideoClip }) {
min={0}
max={SPLIT_EDIT_MAX_S}
step={0.05}
- format={formatSplit}
- parse={parseSplitInput}
+ format={(v) => formatSplit(v, off)}
+ parse={(raw) => parseSplitInput(raw, off)}
onDraft={onDraft}
onCommit={(v) => {
updateClip(clip.id, write(v));
@@ -962,17 +989,11 @@ function ClipSplitEdit({ clip }: { clip: VideoClip }) {
);
return (
<>
- <Row
- label="Sound lead"
- info="J-cut: this clip's sound starts this long before its picture, under the clip before it. A tenth to half a second softens a dialogue cut; a second or two hands one scene into the next."
- >
- {slider("Sound lead", lead, setLeadDraft, (v) => ({ audioLead: v > 0 ? v : undefined }))}
+ <Row label={t("soundLead")} info={t("soundLeadInfo")}>
+ {slider(t("soundLead"), lead, setLeadDraft, (v) => ({ audioLead: v > 0 ? v : undefined }))}
</Row>
- <Row
- label="Sound tail"
- info="L-cut: this clip's sound carries on this long past its picture, under the clip after it."
- >
- {slider("Sound tail", tail, setTailDraft, (v) => ({ audioTail: v > 0 ? v : undefined }))}
+ <Row label={t("soundTail")} info={t("soundTailInfo")}>
+ {slider(t("soundTail"), tail, setTailDraft, (v) => ({ audioTail: v > 0 ? v : undefined }))}
</Row>
</>
);
@@ -1010,6 +1031,7 @@ function SoundQualitySections({
sound: ClipSound | undefined;
write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
}) {
+ const t = useTranslations("inspector.sound");
const set = (next: ClipSound | undefined, phase: "draft" | "commit") =>
write(normalizeSound(next), phase);
const eq = SOUND_EQ_BANDS.map((_, i) => sound?.eq?.[i] ?? 0);
@@ -1063,10 +1085,10 @@ function SoundQualitySections({
<>
<SoundPresetsRow itemId={itemId} sound={sound} onApply={(s) => set(s, "commit")} />
<Section
- title="Equalizer"
+ title={t("equalizer")}
aside={
<ResetButton
- title="Flatten equalizer"
+ title={t("flattenEqualizer")}
show={!!sound?.eq}
onClick={() => set({ ...sound, eq: undefined }, "commit")}
/>
@@ -1079,7 +1101,7 @@ function SoundQualitySections({
{EQ_GROUPS.map((group) => (
<div key={group}>
<div className="mb-0.5 text-[9.5px] leading-none tracking-wider text-muted-foreground/50 uppercase">
- {group}
+ {t(`eqGroups.${group}`)}
</div>
<div className={EQ_ROWS}>
{SOUND_EQ_BANDS.map((b, i) =>
@@ -1103,7 +1125,7 @@ function SoundQualitySections({
</div>
</Section>
<Section
- title="Compressor"
+ title={t("compressor")}
enabled={!!comp}
onEnabledChange={(on) =>
set(
@@ -1118,14 +1140,14 @@ function SoundQualitySections({
{comp && (
<>
{dbRow(
- "Threshold",
+ t("threshold"),
comp.threshold,
cr.threshold,
(v) => setComp({ threshold: v }, "draft"),
(v) => setComp({ threshold: v }, "commit"),
)}
{dbRow(
- "Ratio",
+ t("ratio"),
comp.ratio,
cr.ratio,
(v) => setComp({ ratio: v }, "draft"),
@@ -1135,7 +1157,7 @@ function SoundQualitySections({
0.1,
)}
{dbRow(
- "Attack",
+ t("attack"),
comp.attack,
cr.attack,
(v) => setComp({ attack: v }, "draft"),
@@ -1145,7 +1167,7 @@ function SoundQualitySections({
0.5,
)}
{dbRow(
- "Release",
+ t("release"),
comp.release,
cr.release,
(v) => setComp({ release: v }, "draft"),
@@ -1158,7 +1180,7 @@ function SoundQualitySections({
)}
</Section>
<Section
- title="Limiter"
+ title={t("limiter")}
enabled={!!sound?.limiter}
onEnabledChange={(on) =>
set(
@@ -1169,7 +1191,7 @@ function SoundQualitySections({
>
{sound?.limiter &&
dbRow(
- "Ceiling",
+ t("ceiling"),
sound.limiter.ceiling,
SOUND_LIMITER_RANGE.ceiling,
(v) => set({ ...sound, limiter: { ceiling: v } }, "draft"),
@@ -1180,24 +1202,32 @@ function SoundQualitySections({
);
}
+type SoundT = ReturnType<typeof useTranslations<"inspector.sound">>;
+type SoundPresetId = keyof Messages["inspector"]["sound"]["presets"];
+
+/** A shipped sound preset's name in the page's language. */
+const soundPresetName = (t: SoundT, id: string) => t(`presets.${id as SoundPresetId}`);
+
/** What a clip's treatment reads as on the row that opens it. */
-const soundSummary = (sound: ClipSound | undefined) => {
+const soundSummary = (t: SoundT, sound: ClipSound | undefined) => {
const s = normalizeSound(sound);
- if (!s) return "Off";
- return SOUND_PRESETS.find((p) => p.sound && sameSound(p.sound, s))?.name ?? "On";
+ if (!s) return t("off");
+ const preset = SOUND_PRESETS.find((p) => p.sound && sameSound(p.sound, s));
+ return preset ? soundPresetName(t, preset.id) : t("on");
};
/** The row on an audio panel that opens the Sound quality view, reading
* what the clip carries. */
export function SoundQualityRow({ sound, onOpen }: { sound: ClipSound | undefined; onOpen: () => void }) {
+ const t = useTranslations("inspector.sound");
return (
- <Row label="Sound quality">
+ <Row label={t("title")}>
<button
type="button"
className="sound-quality-open flex h-8 items-center gap-1 rounded-md border border-input px-2.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
onClick={onOpen}
>
- {soundSummary(sound)}
+ {soundSummary(t, sound)}
<ChevronRight className="size-3.5 shrink-0" />
</button>
</Row>
@@ -1216,9 +1246,10 @@ export function SoundQualityPanel({
write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
onBack: () => void;
}) {
+ const t = useTranslations("inspector.sound");
return (
<>
- <SubviewHead title="Sound quality" onBack={onBack} />
+ <SubviewHead title={t("title")} onBack={onBack} />
<div className="flex flex-col gap-1 px-3.5 pb-4">
<SoundQualitySections itemId={itemId} sound={sound} write={write} />
</div>
@@ -1239,6 +1270,7 @@ function SoundPresetsRow({
sound: ClipSound | undefined;
onApply: (sound: ClipSound | undefined) => void;
}) {
+ const t = useTranslations("inspector.sound");
const [naming, setNaming] = useState(false);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
@@ -1284,7 +1316,7 @@ function SoundPresetsRow({
// Flat is the shipped "nothing applied" treatment; it reads as Off.
...SOUND_PRESETS.map((p) => ({
key: `shipped:${p.id}`,
- label: p.sound ? p.name : "Off",
+ label: p.sound ? soundPresetName(t, p.id) : t("off"),
sound: p.sound,
})),
...saved.map((p) => ({
@@ -1305,12 +1337,12 @@ function SoundPresetsRow({
const value = current?.key ?? CUSTOM;
const items = Object.fromEntries([
...options.map((o) => [o.key, o.label]),
- [CUSTOM, "Custom"],
+ [CUSTOM, t("custom")],
]);
return (
<>
- <Row label="Preset">
+ <Row label={t("preset")}>
<Select
value={value}
items={items}
@@ -1335,15 +1367,15 @@ function SoundPresetsRow({
className="text-[12px]"
disabled={value !== CUSTOM}
>
- Custom
+ {t("custom")}
</SelectItem>
</SelectContent>
</Select>
{current?.saved ? (
<button
type="button"
- title={`Delete ${current.label}`}
- aria-label={`Delete preset ${current.label}`}
+ title={t("deleteNamed", { name: current.label })}
+ aria-label={t("deletePresetNamed", { name: current.label })}
className="grid size-5 shrink-0 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
onClick={() => {
const p = current.saved!;
@@ -1351,7 +1383,7 @@ function SoundPresetsRow({
patchLibrary(client, (prev) => ({
...prev,
templates: prev.templates.filter(
- (t) => !(t.id === p.id && t.residency === p.residency)
+ (item) => !(item.id === p.id && item.residency === p.residency)
),
}));
}}
@@ -1361,19 +1393,19 @@ function SoundPresetsRow({
) : (
<button
type="button"
- title="Save preset"
+ title={t("savePreset")}
className="shrink-0 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
disabled={!sound}
onClick={() => setNaming(true)}
>
- Save
+ {t("save")}
</button>
)}
</Row>
<Dialog open={naming} onOpenChange={(o) => !o && setNaming(false)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>Save sound preset</DialogTitle>
+ <DialogTitle>{t("saveDialogTitle")}</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
@@ -1383,14 +1415,14 @@ function SoundPresetsRow({
>
<Input
autoFocus
- placeholder="Preset name"
+ placeholder={t("presetName")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<DialogFooter className="mt-4">
<Button type="submit" disabled={busy || !name.trim()} className="w-full">
{busy && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Save preset
+ {t("savePreset")}
</Button>
</DialogFooter>
</form>
@@ -1400,6 +1432,7 @@ function SoundPresetsRow({
);
}
function ClipPanel({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.clip");
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const aspect = useEditor((s) => s.aspect);
const updateClip = useEditor((s) => s.updateClip);
@@ -1456,10 +1489,10 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
{asset?.block && (
// A blocked-out shot's whole picture is its colour, so that is the
// one thing there is to set on it by hand.
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={asset.block.color || BLOCK_COLOR}
- label="Block color"
+ label={t("blockColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateAsset(asset.id, { block: { ...asset.block!, color: c } })
@@ -1470,9 +1503,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
/>
</Row>
)}
- <Row label="Trim">
+ <Row label={t("trim")}>
<ScrubValue
- label="Trim start"
+ label={t("trimStart")}
value={clip.in}
min={0}
max={clip.out - MIN_TRIM}
@@ -1484,7 +1517,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
/>
<Value className="text-muted-foreground">–</Value>
<ScrubValue
- label="Trim end"
+ label={t("trimEnd")}
value={clip.out}
min={clip.in + MIN_TRIM}
max={maxOut}
@@ -1495,14 +1528,14 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
onCommit={(v) => useEditor.getState().setClipTrim(clip.id, clip.in, v)}
/>
<ResetButton
- title="Reset trim"
+ title={t("resetTrim")}
show={Number.isFinite(maxOut) && (clip.in > 1e-3 || clip.out < maxOut - 1e-3)}
onClick={() => useEditor.getState().setClipTrim(clip.id, 0, maxOut)}
/>
</Row>
- <Row label="Starts at">
+ <Row label={t("startsAt")}>
<ScrubValue
- label="Starts at"
+ label={t("startsAt")}
value={clip.start}
min={0}
max={Infinity}
@@ -1516,9 +1549,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Speed"
+ label={t("speed")}
sliderClassName="clip-speed data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={speed}
@@ -1537,7 +1570,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
<ResetButton
- title="Reset speed"
+ title={t("resetSpeed")}
show={curved || Math.abs(speed - 1) > 1e-4}
onClick={() => {
useEditor.getState().setClipSpeed(clip.id, 1);
@@ -1545,12 +1578,12 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Speed Curve">
+ <Row label={t("speedCurve")}>
<Button
variant={curveOpen ? "secondary" : "outline"}
size="sm"
className="h-6 px-2 text-[11px]"
- title="Shape the speed across the footage with nodes"
+ title={t("speedCurveHint")}
onClick={() => {
if (curveOpen) {
setCurveOpen(false);
@@ -1562,15 +1595,15 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
setCurveOpen(true);
}}
>
- {curveOpen ? "Editing" : curved ? "Edit" : "Add"}
+ {curveOpen ? t("curveEditing") : curved ? t("curveEdit") : t("curveAdd")}
</Button>
{curved && (
<span className="text-[11px] tabular-nums text-muted-foreground">
- {clip.speedCurve!.length} nodes
+ {t("nodes", { count: clip.speedCurve!.length })}
</span>
)}
</Row>
- <Row label="Reverse">
+ <Row label={t("reverse")}>
<Switch
checked={!!clip.reverse}
onCheckedChange={(v) => useEditor.getState().setClipReverse(clip.id, v)}
@@ -1579,7 +1612,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
{/* Picture */}
<div className="my-1.5 h-px bg-border" />
- <Row label="Hidden">
+ <Row label={t("hidden")}>
<Switch
checked={!!clip.hidden}
onCheckedChange={(v) => updateClip(clip.id, { hidden: v })}
@@ -1587,7 +1620,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
</Row>
{/* A camera card places the footage itself (Frame view). */}
{!clip.card && (<>
- <Row label="Framing">
+ <Row label={t("framing")}>
<div className="clip-framing flex rounded-lg border border-input p-0.5">
{(["fit", "fill"] as const).map((mode) => (
<button
@@ -1601,14 +1634,14 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
aria-pressed={(clip.fit ?? "fit") === mode}
onClick={() => updateClip(clip.id, { fit: mode, panX: 0, panY: 0 })}
>
- {mode === "fit" ? "Fit" : "Fill"}
+ {mode === "fit" ? t("fit") : t("fill")}
</button>
))}
</div>
</Row>
- <Row label="Zoom">
+ <Row label={t("zoom")}>
<ValueSlider
- label="Zoom"
+ label={t("zoom")}
sliderClassName="clip-zoom data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clipZoom(clip)}
@@ -1632,7 +1665,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
<ResetButton
- title="Reset zoom"
+ title={t("resetZoom")}
show={clipZoom(clip) > 1}
onClick={() => updateClip(clip.id, { zoom: undefined, panX: 0, panY: 0 })}
/>
@@ -1642,9 +1675,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
const value = clip[axis] ?? 0;
if (!free && value === 0) return null;
return (
- <Row key={axis} label={axis === "panX" ? "Pan X" : "Pan Y"}>
+ <Row key={axis} label={axis === "panX" ? t("panX") : t("panY")}>
<ValueSlider
- label={axis === "panX" ? "Pan X" : "Pan Y"}
+ label={axis === "panX" ? t("panX") : t("panY")}
sliderClassName="clip-pan data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={value}
@@ -1666,7 +1699,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
<ResetButton
- title="Center"
+ title={t("center")}
show={value !== 0}
onClick={() => updateClip(clip.id, { [axis]: 0 })}
/>
@@ -1674,9 +1707,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
);
})}
</>)}
- <Row label="Rotation">
+ <Row label={t("rotation")}>
<ValueSlider
- label="Rotation"
+ label={t("rotation")}
sliderClassName="clip-rotation data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.rotation ?? 0}
@@ -1700,17 +1733,17 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
<ResetButton
- title="Reset rotation"
+ title={t("resetRotation")}
show={!!clip.rotation}
onClick={() => updateClip(clip.id, { rotation: undefined })}
/>
</Row>
- <Row label="Flip">
+ <Row label={t("flip")}>
<div className="clip-flip flex rounded-lg border border-input p-0.5">
{(
[
- ["flipH", "Flip horizontal", FlipHorizontal2],
- ["flipV", "Flip vertical", FlipVertical2],
+ ["flipH", t("flipHorizontal"), FlipHorizontal2],
+ ["flipV", t("flipVertical"), FlipVertical2],
] as const
).map(([key, label, Icon]) => (
<TooltipProvider key={key}>
@@ -1734,9 +1767,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
))}
</div>
</Row>
- <Row label="Opacity">
+ <Row label={t("opacity")}>
<ValueSlider
- label="Opacity"
+ label={t("opacity")}
sliderClassName="clip-opacity data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.opacity ?? 1}
@@ -1759,7 +1792,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
}}
/>
<ResetButton
- title="Reset opacity"
+ title={t("resetOpacity")}
show={(clip.opacity ?? 1) < 1}
onClick={() => updateClip(clip.id, { opacity: undefined })}
/>
@@ -1838,17 +1871,18 @@ function ClipGeneratedAudio({ clip }: { clip: VideoClip }) {
return first ? first.volume : 1;
});
const genVol = genVolDraft ?? genVolStore;
+ const t = useTranslations("inspector.clipAudio");
return (
<div className="mt-2 flex flex-col gap-1 border-t border-border pt-3">
<GenerateSubtitlesAudio
selectCueIds={selectClipCueIds}
ensureCues={ensureClipCues}
- label="Generate audio for clip"
+ label={t("generateForClip")}
/>
{genAudioIds.length > 0 && (
- <Row label="Volume">
+ <Row label={t("volume")}>
<ValueSlider
- label="Generated audio volume"
+ label={t("generatedVolume")}
sliderClassName="clip-gen-volume data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={genVol}
@@ -1882,14 +1916,16 @@ function ClipGeneratedAudio({ clip }: { clip: VideoClip }) {
* clear it. The dots themselves live on the clip bars — dragged, added
* (⌥-click), and removed (double-click) there. */
function BeatsControl({ asset }: { asset: MediaAsset }) {
+ const t = useTranslations("inspector.beats");
const busy = useSyncExternalStore(subscribeBeatsBusy, () => beatsBusyFor(asset.id), () => false);
const grid = asset.beats;
return (
<>
{grid && (
<Value className="whitespace-nowrap text-muted-foreground">
- {grid.beats.length}
- {grid.bpm > 0 ? `·${Math.round(grid.bpm)} BPM` : " beats"}
+ {grid.bpm > 0
+ ? t("countBpm", { count: grid.beats.length, bpm: Math.round(grid.bpm) })
+ : t("count", { count: grid.beats.length })}
</Value>
)}
<Button
@@ -1903,11 +1939,11 @@ function BeatsControl({ asset }: { asset: MediaAsset }) {
}}
>
{busy && <Loader2 className="size-3.5 animate-spin" />}
- Detect
+ {t("detect")}
</Button>
{grid && (
<ResetButton
- title="Clear beats"
+ title={t("clear")}
show
onClick={() => {
useEditor.getState().pushHistory();
@@ -1920,6 +1956,8 @@ function BeatsControl({ asset }: { asset: MediaAsset }) {
}
function AudioPanel({ clip }: { clip: AudioClip }) {
+ const t = useTranslations("inspector.clip");
+ const ta = useTranslations("inspector.clipAudio");
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const updateAudioTransient = useEditor((s) => s.updateAudioTransient);
const ck = useSliderCheckpoint();
@@ -1959,9 +1997,9 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
time={formatTime(len)}
onRename={(name) => useEditor.getState().updateAudio(clip.id, { name })}
/>
- <Row label="Trim">
+ <Row label={t("trim")}>
<ScrubValue
- label="Trim start"
+ label={t("trimStart")}
value={clip.in}
min={0}
max={clip.out - MIN_TRIM}
@@ -1973,7 +2011,7 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
/>
<Value className="text-muted-foreground">–</Value>
<ScrubValue
- label="Trim end"
+ label={t("trimEnd")}
value={clip.out}
min={clip.in + MIN_TRIM}
max={asset?.duration ?? clip.out}
@@ -1984,14 +2022,14 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onCommit={(v) => commitAudio({ out: v })}
/>
<ResetButton
- title="Reset trim"
+ title={t("resetTrim")}
show={!!asset && (clip.in > 1e-3 || clip.out < asset.duration - 1e-3)}
onClick={() => asset && commitAudio({ in: 0, out: asset.duration })}
/>
</Row>
- <Row label="Starts at">
+ <Row label={t("startsAt")}>
<ScrubValue
- label="Starts at"
+ label={t("startsAt")}
value={clip.start}
min={0}
max={Infinity}
@@ -2002,9 +2040,9 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onCommit={(v) => commitAudio({ start: v })}
/>
</Row>
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Speed"
+ label={t("speed")}
sliderClassName="audio-speed data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={speed}
@@ -2020,20 +2058,20 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onCommit={(v) => commitAudio({ speed: Math.abs(v - 1) < 1e-4 ? undefined : v, speedCurve: undefined })}
/>
<ResetButton
- title="Reset speed"
+ title={t("resetSpeed")}
show={Math.abs(speed - 1) > 1e-4 || !!clip.speedCurve}
onClick={() => commitAudio({ speed: undefined, speedCurve: undefined })}
/>
</Row>
- <Row label="Reverse">
+ <Row label={t("reverse")}>
<Switch
checked={!!clip.reverse}
onCheckedChange={(v) => commitAudio({ reverse: v || undefined })}
/>
</Row>
- <Row label="Volume">
+ <Row label={ta("volume")}>
<ValueSlider
- label="Volume"
+ label={ta("volume")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.volume}
@@ -2047,9 +2085,9 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onCommit={(v) => commitAudio({ volume: v })}
/>
</Row>
- <Row label="Fade in">
+ <Row label={ta("fadeIn")}>
<ValueSlider
- label="Fade in"
+ label={ta("fadeIn")}
sliderClassName="fade-in-slider data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.fadeIn ?? 0}
@@ -2062,9 +2100,9 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onCommit={(v) => commitAudio({ fadeIn: v })}
/>
</Row>
- <Row label="Fade out">
+ <Row label={ta("fadeOut")}>
<ValueSlider
- label="Fade out"
+ label={ta("fadeOut")}
sliderClassName="fade-out-slider data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.fadeOut ?? 0}
@@ -2078,36 +2116,37 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
/>
</Row>
<Row
- label="Duck others"
+ label={ta("duck")}
info={
clip.duck !== undefined
- ? `While this clip plays, everything else drops to ${Math.round(clip.duck * 100)}% volume.`
- : "While this clip plays, drop everything else to this volume."
+ ? ta("duckInfoSet", { percent: Math.round(clip.duck * 100) })
+ : ta("duckInfo")
}
>
<ValueSlider
- label="Duck others"
+ label={ta("duck")}
sliderClassName="duck-slider data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={clip.duck ?? 1}
min={0}
max={1}
step={0.05}
- format={(v) => (v >= 0.999 ? "Off" : formatPercent(v))}
- parse={(raw) => (raw.trim().toLowerCase() === "off" ? 1 : parsePercentInput(raw))}
+ format={(v) => (v >= 0.999 ? ta("off") : formatPercent(v))}
+ parse={(raw) =>
+ raw.trim().toLowerCase() === "off" || raw.trim().toLowerCase() === ta("off").toLowerCase()
+ ? 1
+ : parsePercentInput(raw)
+ }
onDraft={(v) => setAudio({ duck: v < 0.999 ? v : undefined })}
onCommit={(v) => commitAudio({ duck: v < 0.999 ? v : undefined })}
/>
</Row>
{asset && !assetIsSilent(asset) && (
- <Row
- label="Beats"
- info="Beat markers detected from the music, drawn as dots on the clip. Every drag and trim snaps to them; drag a dot to move it, double-click removes it, ⌥-click the clip adds one."
- >
+ <Row label={ta("beats")} info={ta("musicBeatsInfo")}>
<BeatsControl asset={asset} />
</Row>
)}
- <Row label="Hidden">
+ <Row label={t("hidden")}>
<Switch
checked={!!clip.hidden}
onCheckedChange={(v) => useEditor.getState().updateAudio(clip.id, { hidden: v })}
@@ -2127,6 +2166,7 @@ export const LETTER_SPACINGS = [-2, 0, 2, 5, 10, 20];
export const TEXT_WIDTHS = [0, 25, 50, 75, 100];
function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
+ const t = useTranslations("inspector.text");
const update = useEditor((s) => s.updateOverlay);
const sizeCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
@@ -2197,8 +2237,8 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
<Button
variant="ghost"
size="icon-sm"
- aria-label="Insert emoji"
- title="Insert emoji"
+ aria-label={t("insertEmoji")}
+ title={t("insertEmoji")}
className="absolute top-1.5 right-1.5 text-muted-foreground"
>
<Smile />
@@ -2218,7 +2258,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
<div className="mt-1 flex items-center gap-2">
<SegGroup>
<SegToggle
- label="Italic"
+ label={t("italic")}
active={!!o.italic}
onClick={() => update(o.id, { italic: o.italic ? undefined : true })}
>
@@ -2235,7 +2275,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
).map(([a, Icon]) => (
<SegToggle
key={a}
- label={`Align ${a}`}
+ label={t(`align.${a}`)}
active={(o.align ?? "center") === a}
onClick={() => update(o.id, { align: a === "center" ? undefined : a })}
>
@@ -2244,7 +2284,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
))}
</SegGroup>
<NumberField
- label="Text size"
+ label={t("textSize")}
className="ml-auto w-[74px]"
icon={<Type />}
value={o.size}
@@ -2266,9 +2306,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
/>
</div>
<div className="mt-1 grid grid-cols-2 gap-2">
- <Field label="Line height">
+ <Field label={t("lineHeight")}>
<NumberField
- label="Line height"
+ label={t("lineHeight")}
icon={<AlignVerticalSpaceAround />}
value={o.lineHeight ?? 1.25}
min={0.8}
@@ -2293,9 +2333,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
}}
/>
</Field>
- <Field label="Letter spacing">
+ <Field label={t("letterSpacing")}>
<NumberField
- label="Letter spacing"
+ label={t("letterSpacing")}
icon={<AlignHorizontalSpaceAround />}
value={(o.letterSpacing ?? 0) * 100}
min={LETTER_SPACING_MIN * 100}
@@ -2321,20 +2361,20 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
/>
</Field>
</div>
- <Field label="Text width">
- <NumberField label="Text box width" icon={<StretchHorizontal />}
+ <Field label={t("textWidth")}>
+ <NumberField label={t("textBoxWidth")} icon={<StretchHorizontal />}
value={(o.wrapWidth ?? 0) * 100} min={0} max={200} step={1} presets={TEXT_WIDTHS}
- format={(v) => v === 0 ? "Auto" : `${Math.round(v)}%`}
+ format={(v) => v === 0 ? t("auto") : `${Math.round(v)}%`}
parse={(raw) => parseNumberInput(raw.replace(/%$/, ""))}
onDraft={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); }}
onCommit={(v) => { widthCk.begin(); useEditor.getState().updateOverlayTransient(o.id, { wrapWidth: v > 0 ? v / 100 : undefined }); widthCk.end(); }}
/>
</Field>
<TextTextureRow overlay={o} />
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={o.color}
- label="Text color"
+ label={t("textColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { color: c })}
onCommit={(c) => update(o.id, { color: c })}
@@ -2342,7 +2382,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
</Row>
<TransformRows overlay={o} />
<Section
- title="Outline"
+ title={t("outline")}
enabled={!!o.stroke}
onEnabledChange={(v) =>
update(o.id, { stroke: v ? { color: "#111114", width: 0.04 } : undefined })
@@ -2350,10 +2390,10 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
>
{o.stroke && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={o.stroke.color}
- label="Outline color"
+ label={t("outlineColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateOverlayTransient(o.id, {
@@ -2363,9 +2403,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
onCommit={(c) => update(o.id, { stroke: { ...o.stroke!, color: c } })}
/>
</Row>
- <Row label="Width">
+ <Row label={t("width")}>
<ValueSlider
- label="Outline width"
+ label={t("outlineWidth")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.stroke.width * 100}
@@ -2395,20 +2435,20 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
</Section>
<ShadowSection id={o.id} shadow={o.shadow} onToggle={(v) => update(o.id, { shadow: v })} />
<Section
- title="Backdrop"
+ title={t("backdrop")}
enabled={o.plate}
onEnabledChange={(v) => update(o.id, { plate: v })}
>
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={o.plateColor ?? PLATE_COLOR}
- label="Backdrop color"
+ label={t("backdropColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { plateColor: c })}
onCommit={(c) => update(o.id, { plateColor: c })}
opacity={{
- label: "Backdrop opacity",
+ label: t("backdropOpacity"),
value: o.plateOpacity ?? PLATE_OPACITY,
onDraft: (v) => {
opacityCk.begin();
@@ -2422,9 +2462,9 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
}}
/>
</Row>
- <Row label="Radius">
+ <Row label={t("radius")}>
<ValueSlider
- label="Backdrop radius"
+ label={t("backdropRadius")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.plateRadius ?? PLATE_RADIUS}
@@ -2456,6 +2496,7 @@ function TextPanel({ overlay: o }: { overlay: TextOverlay }) {
/** Named text-style presets from the shared Library: chips that apply a saved
* look to the selected title, plus saving the current look under a name. */
export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; peers?: readonly TextOverlay[] }) {
+ const t = useTranslations("inspector.styles");
const [presets, setPresets] = useState<StylePreset[] | null>(null);
const [naming, setNaming] = useState(false);
const [name, setName] = useState("");
@@ -2511,7 +2552,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
return (
<div className="mb-1.5">
<div className="mb-1 flex items-center justify-between">
- <span className="text-[13px] text-muted-foreground">Styles</span>
+ <span className="text-[13px] text-muted-foreground">{t("title")}</span>
{!naming && (
<div className="flex items-center gap-3">
{canUpdate && (
@@ -2520,7 +2561,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
disabled={busy}
className="text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
>
- Update style
+ {t("update")}
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{presets.map((p) => (
@@ -2536,7 +2577,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
className="text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"
onClick={() => setNaming(true)}
>
- Save style
+ {t("save")}
</button>
</div>
)}
@@ -2546,7 +2587,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
<input
autoFocus
className="h-7 min-w-0 flex-1 rounded-md border border-input bg-transparent px-2 text-[12px] outline-none focus:border-ring"
- placeholder="Style name"
+ placeholder={t("name")}
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
@@ -2555,7 +2596,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
}}
/>
<Button size="sm" variant="outline" disabled={busy || !name.trim()} onClick={() => void save()}>
- Save
+ {t("saveButton")}
</Button>
</div>
)}
@@ -2565,7 +2606,7 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
<span key={`${p.residency}:${p.id}`} className="group relative">
<button
type="button"
- title={`Apply ${p.name}`}
+ title={t("apply", { name: p.name })}
className={cn(
"flex items-center gap-1.5 rounded-md border border-input px-2 py-1 text-[11.5px] transition-colors hover:border-ring",
p === worn && PICKED_RING
@@ -2595,8 +2636,8 @@ export function StylePresetsRow({ overlay: o, peers }: { overlay: TextOverlay; p
</button>
<button
type="button"
- title={`Delete ${p.name}`}
- aria-label={`Delete style ${p.name}`}
+ title={t("delete", { name: p.name })}
+ aria-label={t("deleteStyle", { name: p.name })}
className="absolute -top-1.5 -right-1.5 hidden size-4 place-items-center rounded-full bg-black/60 text-[9px] text-white group-hover:grid"
onClick={() => {
void deleteStylePreset(p).catch(() => {});
@@ -2690,6 +2731,7 @@ function MoveStrengthSlider({ overlay: o, label, peers }: { overlay: Overlay; la
* nothing. With no effect picked the rows sit greyed, so the panel floor
* keeps its height while the reader scrolls the grid. */
function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.anim");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const words = anim.words;
@@ -2710,9 +2752,9 @@ function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonl
return (
<>
{knobs.size && (
- <Row label="Word size">
+ <Row label={t("wordSize")}>
<ValueSlider
- label="Word size"
+ label={t("wordSize")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={wordSwell(words)}
@@ -2732,9 +2774,9 @@ function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonl
</Row>
)}
{knobs.dim && (
- <Row label="Faded to">
+ <Row label={t("fadedTo")}>
<ValueSlider
- label="Faded to"
+ label={t("fadedTo")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={wordDim(words)}
@@ -2754,10 +2796,10 @@ function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonl
</Row>
)}
{knobs.color && (
- <Row label="Word color">
+ <Row label={t("wordColor")}>
<ColorField
value={wordAccent(words, isTextOverlay(o) ? o.color : WORD_ACCENT_DEFAULT)}
- label="Word color"
+ label={t("wordColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={setColor}
onCommit={setColor}
@@ -2771,6 +2813,7 @@ function WordSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonl
/** The typing bar of a typewriter entrance: on or off, whether it blinks once
* typing stops, how many times, whether it goes after, and its color. */
function CaretSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.anim");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const edge = anim.in;
@@ -2803,7 +2846,7 @@ function CaretSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readon
};
return (
<>
- <Row label="Caret">
+ <Row label={t("caret")}>
<Switch
checked={!!caret}
onCheckedChange={(v) => {
@@ -2813,21 +2856,21 @@ function CaretSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readon
/>
</Row>
{caret && (
- <Row label="Blink">
+ <Row label={t("blink")}>
<Switch checked={caretBlink} onCheckedChange={(v) => toggle({ blink: v })} />
</Row>
)}
{caret && caretBlink && (
- <Row label="Blinks">
+ <Row label={t("blinks")}>
<ValueSlider
- label="Blinks"
+ label={t("blinks")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={caretBlinks}
min={0}
max={CARET_BLINKS_MAX}
step={1}
- format={(v) => (v === 0 ? "All" : `${Math.round(v)}`)}
+ format={(v) => (v === 0 ? t("allBlinks") : `${Math.round(v)}`)}
parse={parseNumberInput}
onDraft={(v) => {
ck.begin();
@@ -2841,15 +2884,15 @@ function CaretSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readon
</Row>
)}
{caret && (!caretBlink || caretBlinks > 0) && (
- <Row label="Then hide">
+ <Row label={t("thenHide")}>
<Switch checked={caretHide} onCheckedChange={(v) => toggle({ hide: v })} />
</Row>
)}
{caret && (
- <Row label="Caret color">
+ <Row label={t("caretColor")}>
<ColorField
value={caretColor}
- label="Caret color"
+ label={t("caretColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={setColor}
onCommit={setColor}
@@ -2874,6 +2917,7 @@ function pickedHit(o: Overlay, anim: OverlayAnim, style: string): OverlayHit {
/** The hit's moment inside the element, its length, and whether it darkens. */
function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.anim");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const hit = anim.hit;
@@ -2888,9 +2932,9 @@ function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly
};
return (
<>
- <Row label="At">
+ <Row label={t("at")}>
<ValueSlider
- label="At"
+ label={t("at")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={hitAt}
@@ -2907,9 +2951,9 @@ function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly
}}
/>
</Row>
- <Row label="Duration">
+ <Row label={t("duration")}>
<ValueSlider
- label="Duration"
+ label={t("duration")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={hitSeconds}
@@ -2927,7 +2971,7 @@ function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly
}}
/>
</Row>
- <Row label="Darken">
+ <Row label={t("darken")}>
<Switch
checked={hitDarken}
disabled={!hit}
@@ -2942,31 +2986,24 @@ function HitSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly
);
}
-/** What each text weight is called in the weight menu. */
-const WEIGHT_LABELS: Record<TextWeight, string> = {
- 400: "Regular",
- 500: "Medium",
- 600: "Semibold",
- 700: "Bold",
- 800: "Extra bold",
- 900: "Black",
-};
-
-/** A title's weight, from regular to black. */
+/** A title's weight, from regular to black; each weight names itself under
+ * `inspector.text.weights`. */
function WeightSelect({ value, onChange }: { value: TextWeight; onChange: (w: TextWeight) => void }) {
+ const t = useTranslations("inspector.text");
+ const weightLabel = (w: TextWeight) => t(`weights.${w}`);
return (
<Select
value={String(value)}
- items={Object.fromEntries(TEXT_WEIGHTS.map((w) => [String(w), WEIGHT_LABELS[w]]))}
+ items={Object.fromEntries(TEXT_WEIGHTS.map((w) => [String(w), weightLabel(w)]))}
onValueChange={(v) => onChange(Number(v) as TextWeight)}
>
- <SelectTrigger aria-label="Weight" size="sm" className="w-24 text-[12px]">
+ <SelectTrigger aria-label={t("weight")} size="sm" className="w-24 text-[12px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TEXT_WEIGHTS.map((w) => (
<SelectItem key={w} value={String(w)} className="text-[12px]">
- {WEIGHT_LABELS[w]}
+ {weightLabel(w)}
</SelectItem>
))}
</SelectContent>
@@ -2991,6 +3028,7 @@ function nextCycleFont(o: TextOverlay, faces: CycleFace[]): string {
* font, weight, size and tracking, and a button to add another. The first
* face added starts a cycle across the title's whole length. */
function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.fontCycle");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const fontCycle = anim.fonts;
@@ -3019,18 +3057,18 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
<Button
variant="ghost"
size="icon-sm"
- aria-label="Remove face"
+ aria-label={t("removeFace")}
onClick={() => commit(faces.filter((_, j) => j !== i))}
>
<X />
</Button>
</div>
- <Row label="Weight">
+ <Row label={t("weight")}>
<div className="flex items-center gap-1.5">
<WeightSelect value={face.weight ?? o.weight} onChange={(weight) => commit(setFace(i, { weight }))} />
<SegGroup>
<SegToggle
- label="Italic"
+ label={t("italic")}
active={face.italic ?? !!o.italic}
onClick={() => commit(setFace(i, { italic: !(face.italic ?? !!o.italic) }))}
>
@@ -3039,9 +3077,9 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
</SegGroup>
</div>
</Row>
- <Row label="Size">
+ <Row label={t("size")}>
<ValueSlider
- label="Size"
+ label={t("size")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={face.scale ?? 1}
@@ -3061,9 +3099,9 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
}}
/>
</Row>
- <Row label="Tracking">
+ <Row label={t("tracking")}>
<ValueSlider
- label="Tracking"
+ label={t("tracking")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={(face.tracking ?? o.letterSpacing ?? 0) * 100}
@@ -3083,9 +3121,9 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
/>
</Row>
{/* Hold: how long this face shows; 0 follows the cycle's rate. */}
- <Row label="Hold">
+ <Row label={t("hold")}>
<ValueSlider
- label="Hold"
+ label={t("hold")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={face.hold ?? 0}
@@ -3093,7 +3131,7 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
max={CYCLE_HOLD_MAX}
step={1 / 60}
snap={[0]}
- format={(v) => (v > 0 ? `${v.toFixed(2)}s` : "Rate")}
+ format={(v) => (v > 0 ? `${v.toFixed(2)}s` : t("rate"))}
parse={parseNumberInput}
onDraft={(v) => {
ck.begin();
@@ -3114,7 +3152,7 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
onClick={() => commit([...faces, { font: nextCycleFont(o, faces) }])}
>
<Plus />
- Add face
+ {t("addFace")}
</Button>
</div>
);
@@ -3124,6 +3162,7 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
* many times a second the face changes, and the music beats that can time
* every face instead. */
function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.fontCycle");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
const cycle = anim.fonts;
@@ -3189,7 +3228,7 @@ function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: re
const timeToBeats = () => {
if (!cycle || !beatSource) return;
const elDur = o.end - o.start;
- const beats = clipBeatTimes(beatSource.clip, beatSource.asset).map((t) => t - o.start);
+ const beats = clipBeatTimes(beatSource.clip, beatSource.asset).map((at) => at - o.start);
const edges = tidySwitches(
beatSwitches(beats, fontCycleBeatStep, fontCycleAt, fontCycleAt + fontCycleSeconds),
elDur
@@ -3198,10 +3237,10 @@ function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: re
if (problem) {
setBeatNote(
problem.kind === "few"
- ? "No beat of that clip lands inside the cycle."
+ ? t("beatsFew")
: problem.kind === "many"
- ? `That is ${problem.faces} face changes; a cycle holds ${FONT_CYCLE_FACES_MAX}. Pick a longer step.`
- : `One face would hold ${problem.seconds.toFixed(2)}s, past the ${CYCLE_HOLD_MAX}s limit.`
+ ? t("beatsMany", { faces: problem.faces, max: FONT_CYCLE_FACES_MAX })
+ : t("beatsLong", { seconds: problem.seconds.toFixed(2), max: CYCLE_HOLD_MAX })
);
return;
}
@@ -3212,15 +3251,12 @@ function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: re
return (
<>
- {slider("At", fontCycleAt, 0, Math.max(0, dur - 0.05), 0.05, secs, "at")}
- {slider("Duration", fontCycleSeconds, 0.05, Math.max(0.05, dur - fontCycleAt), 0.05, secs, "seconds")}
- {slider("Rate", fontCycleRate, FONT_CYCLE_RATE_MIN, FONT_CYCLE_RATE_MAX, 1, (v) => `${Math.round(v)}/s`, "rate")}
- <Row
- label="Beats"
- info="Time every face to the music: a new face on each beat of the picked clip inside the cycle, the faces repeating in order. Detect beats on the music clip first. Each face's Hold shows the result."
- >
+ {slider(t("at"), fontCycleAt, 0, Math.max(0, dur - 0.05), 0.05, secs, "at")}
+ {slider(t("duration"), fontCycleSeconds, 0.05, Math.max(0.05, dur - fontCycleAt), 0.05, secs, "seconds")}
+ {slider(t("rate"), fontCycleRate, FONT_CYCLE_RATE_MIN, FONT_CYCLE_RATE_MAX, 1, (v) => `${Math.round(v)}/s`, "rate")}
+ <Row label={t("beats")} info={t("beatsInfo")}>
{beatClips.length === 0 ? (
- <span className="text-[12px] text-muted-foreground">Detect beats on a clip</span>
+ <span className="text-[12px] text-muted-foreground">{t("detectFirst")}</span>
) : (
<Select value={beatSource?.clip.id} onValueChange={(v) => setFontCycleBeats(String(v))} disabled={!cycle}>
<SelectTrigger className="h-8 w-36 text-[12px]">
@@ -3237,26 +3273,26 @@ function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: re
)}
</Row>
{beatClips.length > 0 && (
- <Row label="Each face">
+ <Row label={t("eachFace")}>
<div className="flex items-center gap-1.5">
<Select
value={String(fontCycleBeatStep)}
onValueChange={(v) => setFontCycleBeatStep(Number(v))}
disabled={!cycle}
>
- <SelectTrigger className="h-8 w-20 text-[12px]" aria-label="Beats per face">
+ <SelectTrigger className="h-8 w-20 text-[12px]" aria-label={t("beatsPerFace")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CYCLE_BEAT_STEPS.map((step) => (
<SelectItem key={step} value={String(step)} className="text-[12px]">
- {step === 0.5 ? "½ beat" : step === 1 ? "1 beat" : `${step} beats`}
+ {step === 0.5 ? t("halfBeat") : t("beatStep", { count: step })}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="secondary" size="sm" disabled={!cycle} onClick={timeToBeats}>
- Time
+ {t("time")}
</Button>
</div>
</Row>
@@ -3283,6 +3319,7 @@ function SlotTabs<T extends string>({
isSet: (id: T) => boolean;
onPick: (id: T) => void;
}) {
+ const t = useTranslations("inspector.anim.slots");
return (
<div className="mx-3.5 flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
{tabs.map((id) => (
@@ -3296,7 +3333,7 @@ function SlotTabs<T extends string>({
)}
onClick={() => onPick(id)}
>
- {id}
+ {t(id as AnimSlot)}
</button>
))}
</div>
@@ -3310,6 +3347,7 @@ const CLIP_ANIM_SLOTS = ["in", "out"] as const;
* the timeline draws it, the Transitions tab marks it, and the assistant's
* set_animation writes the same one — and plays itself on the footage. */
export function ClipAnimationPanel({ clip, peers }: { clip: VideoClip; peers?: readonly VideoClip[] }) {
+ const t = useTranslations("inspector.anim");
const [picked, setSlot] = usePanelState<"in" | "out">(clip.id, "animSlot", "in");
const slot = picked === "out" ? "out" : "in";
const tilesScroll = useRememberedScroll(clip.id, `anim:${slot}`);
@@ -3342,7 +3380,7 @@ export function ClipAnimationPanel({ clip, peers }: { clip: VideoClip; peers?: r
<div className="flex min-h-0 flex-1 flex-col">
<div className="shrink-0 bg-card pb-2">
<div className="flex h-10 shrink-0 items-center px-3.5 text-sm font-semibold tracking-tight">
- Animation
+ {t("title")}
</div>
<SlotTabs
tabs={CLIP_ANIM_SLOTS}
@@ -3362,9 +3400,9 @@ export function ClipAnimationPanel({ clip, peers }: { clip: VideoClip; peers?: r
<ClipAnimationTiles clip={clip} which={slot} value={anim?.style} onPick={pick} />
</ScrollArea>
<div className="shrink-0 border-t border-border bg-card px-3.5 py-0.5">
- <Row label="Duration">
+ <Row label={t("duration")}>
<ValueSlider
- label="Duration"
+ label={t("duration")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={secondsDraft ?? anim?.seconds ?? ANIM_DEFAULT_SECONDS}
@@ -3394,6 +3432,7 @@ export function ClipAnimationPanel({ clip, peers }: { clip: VideoClip; peers?: r
* the same grid, one at a time — the tiles are big enough to read the motion,
* which a stack of grids would not be. */
export function AnimationPanel({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.anim");
const anim = o.anim ?? {};
// The active slot holds for the session, like every settings view's tab.
const [picked, setSlot] = usePanelState<AnimSlot>(o.id, "animSlot", "in");
@@ -3500,7 +3539,7 @@ export function AnimationPanel({ overlay: o, peers }: { overlay: Overlay; peers?
<div className="flex min-h-0 flex-1 flex-col">
<div className="shrink-0 bg-card pb-2">
<div className="flex h-10 shrink-0 items-center px-3.5 text-sm font-semibold tracking-tight">
- Animation
+ {t("title")}
</div>
<SlotTabs
tabs={tabs}
@@ -3562,6 +3601,8 @@ export function AnimationPanel({ overlay: o, peers }: { overlay: Overlay; peers?
* put with the slot unset, greyed rather than gone, because a bar that comes
* and goes moves the grid under the pointer. */
function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot: AnimSlot; peers?: readonly Overlay[] }) {
+ const t = useTranslations("inspector.anim");
+ const easeLabel = useLabels("ease");
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
// The ramp fits the shortest element it lands on.
@@ -3572,7 +3613,7 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
<div className="shrink-0 border-t border-border bg-card px-3.5 py-0.5">{children}</div>
);
- if (slot === "move") return bar(<MoveStrengthSlider overlay={o} label="Strength" peers={peers} />);
+ if (slot === "move") return bar(<MoveStrengthSlider overlay={o} label={t("strength")} peers={peers} />);
if (slot === "words") return bar(<WordSettings overlay={o} peers={peers} />);
@@ -3587,9 +3628,9 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
writeOverlayAnim(o, anim, { loop: { ...anim.loop, speed } }, peers);
};
return bar(
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Speed"
+ label={t("speed")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={anim.loop?.speed ?? 1}
@@ -3639,6 +3680,11 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
const edgeFadeShare = typeof edge?.fade === "number" ? edge.fade : 1;
// How soft it starts: the slot's own, else the style's far-end defocus.
const edgeBlur = edge?.blur ?? (edge ? ((edge.preset ?? edgePreset(edge.style))?.animate.blur?.[0]?.v ?? 0) : 0);
+ // An edge's curve: the style's own, or any ease by name.
+ const edgeEaseItems: Record<string, string> = {
+ style: t("styleOwnEase"),
+ ...Object.fromEntries(EASE_IDS.map((id) => [id, easeLabel(id)])),
+ };
const writeEdge = (patch: Partial<OverlayEdge>) => {
if (!edge) return;
ck.begin();
@@ -3646,9 +3692,9 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
};
return bar(
<>
- <Row label="Duration">
+ <Row label={t("duration")}>
<ValueSlider
- label="Duration"
+ label={t("duration")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={edge?.seconds ?? OVERLAY_ANIM_DEFAULT_SECONDS}
@@ -3667,9 +3713,9 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
/>
</Row>
{stagger !== undefined && (
- <Row label="Stagger">
+ <Row label={t("stagger")}>
<ValueSlider
- label="Stagger"
+ label={t("stagger")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={stagger}
@@ -3688,7 +3734,7 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
</Row>
)}
{stagger !== undefined && (
- <Row label="Shuffle">
+ <Row label={t("shuffle")}>
<Switch
checked={edgeOrder !== "reading"}
onCheckedChange={(v) => {
@@ -3700,10 +3746,10 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
)}
{ownReach > 0 && (
// The curve the move travels on, over the style's own.
- <Row label="Ease">
+ <Row label={t("ease")}>
<Select
value={edgeEase}
- items={EDGE_EASE_ITEMS}
+ items={edgeEaseItems}
onValueChange={(id) => {
const rest = { ...edge! };
delete rest.ease;
@@ -3716,7 +3762,7 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
<SelectValue />
</SelectTrigger>
<SelectContent>
- {Object.entries(EDGE_EASE_ITEMS).map(([id, label]) => (
+ {Object.entries(edgeEaseItems).map(([id, label]) => (
<SelectItem key={id} value={id} className="text-[12px]">
{label}
</SelectItem>
@@ -3726,7 +3772,7 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
</Row>
)}
{edgeFades && (
- <Row label="Fade">
+ <Row label={t("fade")}>
<Switch
checked={edgeFade}
onCheckedChange={(v) => {
@@ -3740,9 +3786,9 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
</Row>
)}
{edgeFades && edgeFade && (
- <Row label="Fade length">
+ <Row label={t("fadeLength")}>
<ValueSlider
- label="Fade length"
+ label={t("fadeLength")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={edgeFadeShare}
@@ -3761,16 +3807,16 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
)}
{edgeSequence && isTextOverlay(o) && (
// An order read off a reference: the letters as they arrive.
- <Row label="Order">
- <span className="truncate text-xs text-muted-foreground" title="Letters in the order they move">
+ <Row label={t("order")}>
+ <span className="truncate text-xs text-muted-foreground" title={t("orderHint")}>
{edgeSequence.map((i) => [...o.text][i] ?? "").join(" ")}
</span>
</Row>
)}
{ownReach > 0 && (
- <Row label="Distance">
+ <Row label={t("distance")}>
<ValueSlider
- label="Distance"
+ label={t("distance")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={edgeDistance}
@@ -3789,9 +3835,9 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
</Row>
)}
{edge && (
- <Row label="Blur">
+ <Row label={t("blur")}>
<ValueSlider
- label="Blur"
+ label={t("blur")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={edgeBlur}
@@ -3813,12 +3859,6 @@ function AnimationToolbar({ overlay: o, slot, peers }: { overlay: Overlay; slot:
);
}
-/** An edge's curve: the style's own, or any ease by name. */
-const EDGE_EASE_ITEMS: Record<string, string> = {
- style: "Style's own",
- ...Object.fromEntries(EASE_IDS.map((id) => [id, EASE_LABELS[id]])),
-};
-
/** Rotation and opacity, shared by every overlay kind. Neutral values store
* as absence so untouched elements carry nothing. */
/** The element twin of the clip panels' Hidden row: parked on the timeline,
@@ -3826,9 +3866,10 @@ const EDGE_EASE_ITEMS: Record<string, string> = {
* (the effect panel, which has no Transform, mounts it alone), so the
* timeline chip always has an inspector fallback. */
function HiddenRow({ overlay: o }: { overlay: Overlay }) {
+ const t = useTranslations("inspector.clip");
const update = useEditor((s) => s.updateOverlay);
return (
- <Row label="Hidden">
+ <Row label={t("hidden")}>
<Switch
checked={!!o.hidden}
onCheckedChange={(v) => update(o.id, { hidden: v || undefined })}
@@ -3853,13 +3894,14 @@ function PositionRow({
ck: { begin: () => void; end: () => void };
onSet: (axis: "x" | "y", pct: number) => void;
}) {
+ const t = useTranslations("inspector.transform");
return (
- <Row label="Position">
+ <Row label={t("position")}>
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`${axis.toUpperCase()} position`}
+ label={t("axisPosition", { axis: axis.toUpperCase() })}
className="w-9 text-muted-foreground"
value={pose[axis] * 100}
min={min}
@@ -3906,13 +3948,14 @@ function KeyAxisRow({
parse: (s: string) => number | null;
ck: { begin: () => void; end: () => void };
}) {
+ const t = useTranslations("inspector.transform");
return (
<Row label={label}>
{axes.map((axis) => (
<span key={axis.name} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis.name}</span>
<ScrubValue
- label={`${label} ${axis.name}`}
+ label={t("axisLabel", { label, axis: axis.name })}
className="w-10 text-muted-foreground"
value={axis.value}
min={min}
@@ -3941,6 +3984,7 @@ function KeyAxisRow({
/** One caption's own settings: where it sits, and which of its words are set
* apart in the track's emphasis style (the Subtitles panel styles it). */
function CuePanel({ cue }: { cue: SubtitleCue }) {
+ const t = useTranslations("inspector.cue");
const subtitles = useEditor((s) => s.subtitles);
const posCk = useSliderCheckpoint();
const own = cue.x !== undefined && cue.y !== undefined;
@@ -3954,8 +3998,8 @@ function CuePanel({ cue }: { cue: SubtitleCue }) {
return (
<div className="flex flex-col gap-1 px-3.5 pt-2 pb-4">
<Section
- title="Own position"
- info="A caption sits where its track does. With its own position it moves alone, here or by Option-dragging it in the preview."
+ title={t("ownPosition")}
+ info={t("ownPositionInfo")}
enabled={own}
onEnabledChange={(on) => {
useEditor.getState().pushHistory();
@@ -3965,8 +4009,8 @@ function CuePanel({ cue }: { cue: SubtitleCue }) {
<PositionRow pose={pose} min={2} max={98} ck={posCk} onSet={setPos} />
</Section>
<Section
- title="Emphasis"
- info="Set words apart in the track's emphasis style, which the Subtitles panel's Options tab sets."
+ title={t("emphasis")}
+ info={t("emphasisInfo")}
>
<div className="cue-emphasis flex flex-wrap gap-1 pb-1.5">
{words.map((w, i) => (
@@ -3992,6 +4036,7 @@ function CuePanel({ cue }: { cue: SubtitleCue }) {
}
function TransformRows({ overlay: o }: { overlay: Overlay }) {
+ const t = useTranslations("inspector.transform");
const rotationCk = useSliderCheckpoint();
const opacityCk = useSliderCheckpoint();
const scaleCk = useSliderCheckpoint();
@@ -4027,13 +4072,13 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
useEditor.getState().updateOverlayTransient(o.id, { [axis]: v });
};
return (
- <Section title="Transform">
+ <Section title={t("title")}>
<KeyframeControls overlay={o} />
<PositionRow pose={pose} min={clampPos(-Infinity, o) * 100} max={clampPos(Infinity, o) * 100} ck={posCk} onSet={setPos} />
{keyed && (
- <Row label="Scale">
+ <Row label={t("scale")}>
<ValueSlider
- label="Scale"
+ label={t("scale")}
sliderClassName="data-horizontal:w-20"
valueClassName="w-12 text-muted-foreground"
value={keyPose.scale}
@@ -4063,7 +4108,7 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
)}
{keyed && (
<KeyAxisRow
- label="Stretch"
+ label={t("stretch")}
axes={[
{ name: "W", value: keyPose.scaleX ?? 1, set: (v) => setKey({ scaleX: v }) },
{ name: "H", value: keyPose.scaleY ?? 1, set: (v) => setKey({ scaleY: v }) },
@@ -4078,7 +4123,7 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
)}
{keyed && (
<KeyAxisRow
- label="Tilt"
+ label={t("tilt")}
axes={[
{ name: "X", value: keyPose.tiltX ?? 0, set: (v) => setKey({ tiltX: Math.round(v) }) },
{ name: "Y", value: keyPose.tiltY ?? 0, set: (v) => setKey({ tiltY: Math.round(v) }) },
@@ -4091,9 +4136,9 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
ck={tiltCk}
/>
)}
- <Row label="Rotation">
+ <Row label={t("rotation")}>
<ValueSlider
- label="Rotation"
+ label={t("rotation")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={keyed ? pose.rotation : (o.rotation ?? 0)}
@@ -4115,9 +4160,9 @@ function TransformRows({ overlay: o }: { overlay: Overlay }) {
}}
/>
</Row>
- <Row label="Opacity">
+ <Row label={t("opacity")}>
<ValueSlider
- label="Opacity"
+ label={t("opacity")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={keyed ? pose.opacity : (o.opacity ?? 1)}
@@ -4195,6 +4240,7 @@ export function KeyRow({
onRemove: (tLocal: number) => void;
onSeek: (t: number) => void;
}) {
+ const tr = useTranslations("inspector.keys");
const inWindow = now >= element.start - 1e-6 && now <= element.end + 1e-6;
const tLocal = Math.max(
0,
@@ -4204,14 +4250,14 @@ export function KeyRow({
const prev = [...keys].sort((a, b) => a.t - b.t).reverse().find((k) => k.t < tLocal - KEY_EPSILON);
const next = [...keys].sort((a, b) => a.t - b.t).find((k) => k.t > tLocal + KEY_EPSILON);
return (
- <Row label="Keyframes">
+ <Row label={tr("title")}>
<Button
size="sm"
variant="ghost"
className="size-7 p-0"
disabled={!inWindow}
- title={here >= 0 ? "Update the key here" : "Add a key at the playhead"}
- aria-label={here >= 0 ? "Update the key here" : "Add a key at the playhead"}
+ title={here >= 0 ? tr("update") : tr("add")}
+ aria-label={here >= 0 ? tr("update") : tr("add")}
onClick={() => onAdd(tLocal)}
>
<Diamond
@@ -4227,8 +4273,8 @@ export function KeyRow({
variant="ghost"
className="size-7 p-0"
disabled={!prev}
- title="Previous key"
- aria-label="Previous key"
+ title={tr("previous")}
+ aria-label={tr("previous")}
onClick={() => prev && onSeek(element.start + prev.t)}
>
<ChevronLeft className="size-3.5" />
@@ -4238,8 +4284,8 @@ export function KeyRow({
variant="ghost"
className="size-7 p-0"
disabled={!next}
- title="Next key"
- aria-label="Next key"
+ title={tr("next")}
+ aria-label={tr("next")}
onClick={() => next && onSeek(element.start + next.t)}
>
<ChevronRight className="size-3.5" />
@@ -4252,8 +4298,8 @@ export function KeyRow({
// edge. The pull-right lands this glyph on the same edge as their text.
className="-mr-1.5 size-7 p-0 text-muted-foreground"
disabled={here < 0}
- title="Remove the key here"
- aria-label="Remove the key here"
+ title={tr("remove")}
+ aria-label={tr("remove")}
onClick={() => onRemove(tLocal)}
>
<Trash2 className="size-3.5" />
@@ -4316,6 +4362,7 @@ interface MaskTarget {
* rests in its region, so the rows appear with the first key.
*/
function ClipTransformSection({ clip }: { clip: VideoClip }) {
+ const tr = useTranslations("inspector.transform");
const clips = useEditor((s) => s.clips);
const assets = useEditor((s) => s.assets);
const now = usePreviewTime();
@@ -4334,7 +4381,7 @@ function ClipTransformSection({ clip }: { clip: VideoClip }) {
const setKey = (patch: Partial<Omit<OverlayKey, "t">>) =>
st().setClipKey(clip.id, tLocal, patch, { transient: true });
return (
- <Section title="Transform">
+ <Section title={tr("title")}>
<KeyRow
element={el}
now={now}
@@ -4353,9 +4400,9 @@ function ClipTransformSection({ clip }: { clip: VideoClip }) {
ck={posCk}
onSet={(axis, pct) => setKey({ [axis]: pct / 100 })}
/>
- <Row label="Scale">
+ <Row label={tr("scale")}>
<ValueSlider
- label="Scale"
+ label={tr("scale")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={pose.scale}
@@ -4377,9 +4424,9 @@ function ClipTransformSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Rotation">
+ <Row label={tr("rotation")}>
<ValueSlider
- label="Rotation"
+ label={tr("rotation")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={pose.rotation}
@@ -4401,9 +4448,9 @@ function ClipTransformSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Opacity">
+ <Row label={tr("opacity")}>
<ValueSlider
- label="Opacity"
+ label={tr("opacity")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={pose.opacity}
@@ -4456,6 +4503,7 @@ function OverlayMaskSection({ overlay: o }: { overlay: Overlay }) {
* switch turns the style on with visible defaults; off returns the clip to a
* plain box. */
function ClipBorderSection({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.box");
const widthCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
const bs = clip.boxStyle;
@@ -4464,8 +4512,8 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
st().updateClipTransient(clip.id, { boxStyle: { ...st().clips.find((c) => c.id === clip.id)?.boxStyle, ...patch } });
return (
<Section
- title="Border"
- info="Round the clip's corners and stroke a border along its box edge. Sizes are design pixels, matched between preview and export."
+ title={t("border")}
+ info={t("borderInfo")}
enabled={!!bs}
onEnabledChange={(v) =>
st().updateClip(clip.id, {
@@ -4475,9 +4523,9 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
>
{bs && (
<>
- <Row label="Width">
+ <Row label={t("width")}>
<ScrubValue
- label="Border width"
+ label={t("borderWidth")}
className="w-9 text-muted-foreground"
value={bs.borderWidth ?? 0}
min={0}
@@ -4496,9 +4544,9 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Radius">
+ <Row label={t("radius")}>
<ScrubValue
- label="Corner radius"
+ label={t("cornerRadius")}
className="w-9 text-muted-foreground"
value={bs.radius ?? 0}
min={0}
@@ -4517,10 +4565,10 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={bs.borderColor ?? "#FFFFFF"}
- label="Border color"
+ label={t("borderColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => write({ borderColor: c })}
onCommit={(c) => st().updateClip(clip.id, { boxStyle: { ...bs, borderColor: c } })}
@@ -4535,6 +4583,7 @@ function ClipBorderSection({ clip }: { clip: VideoClip }) {
/** The clip's drop shadow: cast by whatever shape the clip really shows — the
* box, its rounded corners, and its mask together. */
function ClipShadowSection({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("inspector.box");
const blurCk = useSliderCheckpoint();
const offsetCk = useSliderCheckpoint();
const opacityCk = useSliderCheckpoint();
@@ -4548,8 +4597,8 @@ function ClipShadowSection({ clip }: { clip: VideoClip }) {
};
return (
<Section
- title="Shadow"
- info="Cast a drop shadow from the clip's shape — its box, corners, and mask together, so a circle-masked clip throws a circular shadow. Sizes are design pixels, matched between preview and export."
+ title={t("shadow")}
+ info={t("shadowInfo")}
enabled={!!sh}
onEnabledChange={(v) =>
st().updateClip(clip.id, {
@@ -4563,9 +4612,9 @@ function ClipShadowSection({ clip }: { clip: VideoClip }) {
>
{sh && (
<>
- <Row label="Blur">
+ <Row label={t("blur")}>
<ScrubValue
- label="Shadow blur"
+ label={t("shadowBlur")}
className="w-9 text-muted-foreground"
value={sh.blur}
min={0}
@@ -4584,12 +4633,12 @@ function ClipShadowSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Offset">
+ <Row label={t("offset")}>
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`Shadow ${axis.toUpperCase()} offset`}
+ label={t("shadowOffset", { axis: axis.toUpperCase() })}
className="w-9 text-muted-foreground"
value={sh[axis] ?? 0}
min={-120}
@@ -4610,9 +4659,9 @@ function ClipShadowSection({ clip }: { clip: VideoClip }) {
</span>
))}
</Row>
- <Row label="Opacity">
+ <Row label={t("opacity")}>
<ValueSlider
- label="Shadow opacity"
+ label={t("shadowOpacity")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={sh.opacity ?? 0.35}
@@ -4632,10 +4681,10 @@ function ClipShadowSection({ clip }: { clip: VideoClip }) {
}}
/>
</Row>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={sh.color ?? "#000000"}
- label="Shadow color"
+ label={t("shadowColor")}
onBegin={() => st().pushHistory()}
onLive={(c) => write({ color: c })}
onCommit={(c) => write({ color: c })}
@@ -4674,6 +4723,7 @@ function ClipMaskSection({ clip }: { clip: VideoClip }) {
* same contract as Transform; otherwise they edit the mask's resting fields.
*/
function MaskSection({ target }: { target: MaskTarget }) {
+ const tr = useTranslations("inspector.mask");
const now = usePreviewTime();
const seek = useEditor((s) => s.seek);
const posCk = useSliderCheckpoint();
@@ -4738,8 +4788,8 @@ function MaskSection({ target }: { target: MaskTarget }) {
};
return (
<Section
- title="Mask"
- info="Use a shape, draw with Pen, or isolate the Subject."
+ title={tr("title")}
+ info={tr("info")}
enabled={!!m}
onEnabledChange={(v) => target.set(v ? { kind: "rect" } : undefined)}
aside={
@@ -4751,21 +4801,21 @@ function MaskSection({ target }: { target: MaskTarget }) {
onClick={m.kind === "pen" ? redraw : reset}
disabled={drawing}
>
- {m.kind === "pen" ? "Redraw" : "Reset"}
+ {m.kind === "pen" ? tr("redraw") : tr("reset")}
</Button>
) : undefined
}
>
{m && geom && (
<>
- <div className="grid grid-cols-4 gap-1.5 py-1" role="radiogroup" aria-label="Mask shape">
+ <div className="grid grid-cols-4 gap-1.5 py-1" role="radiogroup" aria-label={tr("shape")}>
{MASK_SHAPES.map((s) => (
<button
key={s.id}
type="button"
role="radio"
aria-checked={m.kind === s.id}
- title={s.label}
+ title={tr(`shapes.${s.id}`)}
className={cn(
"flex flex-col items-center gap-1 rounded-md border px-1 pb-1 pt-2 text-[10px] leading-none transition-colors",
m.kind === s.id
@@ -4793,15 +4843,14 @@ function MaskSection({ target }: { target: MaskTarget }) {
}}
>
<MaskShapeIcon kind={s.id} />
- <span className="w-full truncate text-center">{s.label}</span>
+ <span className="w-full truncate text-center">{tr(`shapes.${s.id}`)}</span>
</button>
))}
</div>
{!subject && !drawing && <TrackRow id={target.id} use="mask" />}
{drawing && (
<p className="px-1 py-1.5 text-[11.5px] leading-snug text-muted-foreground">
- Click the picture to place corners. Click the first corner, double-click, or press
- Enter to close the outline.
+ {tr("penHint")}
</p>
)}
{!subject && !drawing && (
@@ -4816,12 +4865,12 @@ function MaskSection({ target }: { target: MaskTarget }) {
/>
)}
{!subject && !drawing && (
- <Row label="Position">
+ <Row label={tr("position")}>
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`Mask ${axis.toUpperCase()} offset`}
+ label={tr("axisOffset", { axis: axis.toUpperCase() })}
className="w-9 text-muted-foreground"
value={geom[axis] * 100}
min={-100}
@@ -4846,7 +4895,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
</Row>
)}
{sizeAxes.length > 0 && !drawing && (
- <Row label="Size">
+ <Row label={tr("size")}>
{sizeAxes.map((axis, i) => (
<span key={axis} className="flex items-center gap-1">
{i === 1 && (
@@ -4854,9 +4903,9 @@ function MaskSection({ target }: { target: MaskTarget }) {
variant="ghost"
size="icon"
className={cn("size-6", sizeLinked ? "text-foreground" : "text-muted-foreground/60")}
- aria-label={sizeLinked ? "Unlink width and height" : "Link width and height"}
+ aria-label={sizeLinked ? tr("unlinkSize") : tr("linkSize")}
aria-pressed={sizeLinked}
- title={sizeLinked ? "Sizes move together" : "Sizes move on their own"}
+ title={sizeLinked ? tr("sizesLinked") : tr("sizesFree")}
onClick={() => setLinked(!sizeLinked)}
>
{sizeLinked ? <Link2 className="size-3.5" /> : <Link2Off className="size-3.5" />}
@@ -4864,7 +4913,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
)}
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`Mask ${axis === "w" ? "width" : "height"}`}
+ label={axis === "w" ? tr("width") : tr("height")}
className="w-9 text-muted-foreground"
value={geom[axis] * 100}
min={1}
@@ -4888,9 +4937,9 @@ function MaskSection({ target }: { target: MaskTarget }) {
</Row>
)}
{!subject && !drawing && (
- <Row label="Rotation">
+ <Row label={tr("rotation")}>
<ValueSlider
- label="Mask rotation"
+ label={tr("maskRotation")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={geom.rotation}
@@ -4914,9 +4963,9 @@ function MaskSection({ target }: { target: MaskTarget }) {
</Row>
)}
{!drawing && (
- <Row label="Feather">
+ <Row label={tr("feather")}>
<ValueSlider
- label="Feather"
+ label={tr("feather")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={geom.feather}
@@ -4938,9 +4987,9 @@ function MaskSection({ target }: { target: MaskTarget }) {
</Row>
)}
{maskHasRadius(m.kind) && (
- <Row label="Radius">
+ <Row label={tr("radius")}>
<ValueSlider
- label="Mask corner radius"
+ label={tr("cornerRadius")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={geom.radius}
@@ -4962,11 +5011,11 @@ function MaskSection({ target }: { target: MaskTarget }) {
</Row>
)}
{!drawing && (
- <Row label="Invert">
+ <Row label={tr("invert")}>
<Switch
checked={!!m.invert}
onCheckedChange={(v) => target.set({ ...m, invert: v || undefined })}
- aria-label="Invert mask"
+ aria-label={tr("invertMask")}
/>
</Row>
)}
@@ -4977,6 +5026,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
}
function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
+ const t = useTranslations("inspector.shape");
const update = useEditor((s) => s.updateOverlay);
const fillCk = useSliderCheckpoint();
const radiusCk = useSliderCheckpoint();
@@ -4987,17 +5037,17 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
<>
<ElementTitle overlay={o} />
<div className="flex flex-col gap-1 px-3.5 pb-4">
- <Row label={boxShape ? "Fill" : "Color"}>
+ <Row label={boxShape ? t("fill") : t("color")}>
<ColorField
value={o.fill}
- label={boxShape ? "Fill color" : "Shape color"}
+ label={boxShape ? t("fillColor") : t("shapeColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { fill: c })}
onCommit={(c) => update(o.id, { fill: c })}
opacity={
boxShape
? {
- label: "Fill opacity",
+ label: t("fillOpacity"),
value: o.fillOpacity ?? 1,
onDraft: (v) => {
fillCk.begin();
@@ -5018,9 +5068,9 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
/>
</Row>
{o.shape === "rect" && (
- <Row label="Corner radius">
+ <Row label={t("cornerRadius")}>
<ValueSlider
- label="Corner radius"
+ label={t("cornerRadius")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.radius ?? 0}
@@ -5049,7 +5099,7 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
)}
{boxShape && (
<Section
- title="Outline"
+ title={t("outline")}
enabled={!!o.stroke}
onEnabledChange={(v) =>
update(o.id, { stroke: v ? { color: "#111114", width: 6 } : undefined })
@@ -5057,10 +5107,10 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
>
{o.stroke && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={o.stroke.color}
- label="Outline color"
+ label={t("outlineColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) =>
useEditor.getState().updateOverlayTransient(o.id, {
@@ -5070,9 +5120,9 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
onCommit={(c) => update(o.id, { stroke: { ...o.stroke!, color: c } })}
/>
</Row>
- <Row label="Width">
+ <Row label={t("width")}>
<ValueSlider
- label="Outline width"
+ label={t("outlineWidth")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.stroke.width}
@@ -5115,6 +5165,7 @@ function ShapePanel({ overlay: o }: { overlay: ShapeOverlay }) {
* and an add button while there is room. Each mark takes the fill or one of
* these. */
function InksRow({ overlay: o }: { overlay: ShapeOverlay }) {
+ const t = useTranslations("inspector.shape");
const update = useEditor((s) => s.updateOverlay);
const inks = o.inks ?? [];
@@ -5122,24 +5173,24 @@ function InksRow({ overlay: o }: { overlay: ShapeOverlay }) {
const swap = (i: number, c: string) => inks.map((x, j) => (j === i ? c : x));
const write = (next: string[]) => update(o.id, { inks: next.length > 0 ? next : undefined });
return (
- <Row label="Inks">
+ <Row label={t("inks")}>
<div className="flex flex-col items-end gap-1">
{inks.map((ink, i) => (
<div key={i} className="flex items-center gap-1">
<ColorField
value={ink}
- label={`Ink ${i + 1}`}
+ label={t("ink", { n: i + 1 })}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(o.id, { inks: swap(i, c) })}
onCommit={(c) => update(o.id, { inks: swap(i, c) })}
/>
- <Button variant="ghost" size="icon-xs" aria-label={`Remove ink ${i + 1}`} onClick={() => write(inks.filter((_, j) => j !== i))}>
+ <Button variant="ghost" size="icon-xs" aria-label={t("removeInk", { n: i + 1 })} onClick={() => write(inks.filter((_, j) => j !== i))}>
<X />
</Button>
</div>
))}
{inks.length < DOODLE_INKS_MAX && (
- <Button variant="ghost" size="icon-xs" aria-label="Add ink" onClick={() => write([...inks, DOODLE_INKS[inks.length % DOODLE_INKS.length]])}>
+ <Button variant="ghost" size="icon-xs" aria-label={t("addInk")} onClick={() => write([...inks, DOODLE_INKS[inks.length % DOODLE_INKS.length]])}>
<Plus />
</Button>
)}
@@ -5159,6 +5210,7 @@ function ShadowSection({
shadow: boolean | ShadowSpec | undefined;
onToggle: (on: boolean) => void;
}) {
+ const t = useTranslations("inspector.box");
const update = useEditor((s) => s.updateOverlay);
const shadowCk = useSliderCheckpoint();
const spec: ShadowSpec = typeof shadow === "object" ? shadow : {};
@@ -5173,26 +5225,26 @@ function ShadowSection({
shadowCk.end();
};
return (
- <Section title="Shadow" enabled={!!shadow} onEnabledChange={onToggle}>
+ <Section title={t("shadow")} enabled={!!shadow} onEnabledChange={onToggle}>
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={spec.color ?? "#000000"}
- label="Shadow color"
+ label={t("shadowColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().updateOverlayTransient(id, { shadow: { ...spec, color: c } })}
onCommit={(c) => update(id, { shadow: { ...spec, color: c } })}
opacity={{
- label: "Shadow opacity",
+ label: t("shadowOpacity"),
value: spec.opacity ?? 0.65,
onDraft: (v) => draft({ opacity: v }),
onCommit: (v) => commit({ opacity: v }),
}}
/>
</Row>
- <Row label="Blur">
+ <Row label={t("blur")}>
<ValueSlider
- label="Shadow blur"
+ label={t("shadowBlur")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={spec.blur ?? SHADOW.blur}
@@ -5206,9 +5258,9 @@ function ShadowSection({
onCommit={(v) => commit({ blur: v })}
/>
</Row>
- <Row label="Offset">
+ <Row label={t("offset")}>
<ValueSlider
- label="Shadow offset"
+ label={t("shadowOffsetY")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={spec.offsetY ?? SHADOW.offsetY}
@@ -5230,6 +5282,7 @@ function ShadowSection({
/** A shape's pattern fill: stripes in the fill color, with line, gap and
* angle sliders. Off is a solid fill. */
function PatternSection({ overlay: o }: { overlay: ShapeOverlay }) {
+ const t = useTranslations("inspector.shape");
const update = useEditor((s) => s.updateOverlay);
const patternCk = useSliderCheckpoint();
const pattern = o.pattern ?? STRIPES_DEFAULT;
@@ -5260,15 +5313,15 @@ function PatternSection({ overlay: o }: { overlay: ShapeOverlay }) {
);
return (
<Section
- title="Pattern"
+ title={t("pattern")}
enabled={!!o.pattern}
onEnabledChange={(v) => update(o.id, { pattern: v ? STRIPES_DEFAULT : undefined })}
>
{o.pattern && (
<>
- <Row label="Line">{slider("Stripe line width", pattern.width, STRIPE_LINE_MIN, STRIPE_LINE_MAX, 0.5, (v) => ({ width: v }))}</Row>
- <Row label="Gap">{slider("Stripe gap", pattern.gap, 0, STRIPE_GAP_MAX, 0.5, (v) => ({ gap: v }))}</Row>
- <Row label="Angle">{slider("Stripe angle", pattern.angle ?? 0, -90, 90, 1, (v) => ({ angle: Math.round(v) || undefined }))}</Row>
+ <Row label={t("line")}>{slider(t("stripeWidth"), pattern.width, STRIPE_LINE_MIN, STRIPE_LINE_MAX, 0.5, (v) => ({ width: v }))}</Row>
+ <Row label={t("gap")}>{slider(t("stripeGap"), pattern.gap, 0, STRIPE_GAP_MAX, 0.5, (v) => ({ gap: v }))}</Row>
+ <Row label={t("angle")}>{slider(t("stripeAngle"), pattern.angle ?? 0, -90, 90, 1, (v) => ({ angle: Math.round(v) || undefined }))}</Row>
</>
)}
</Section>
@@ -5285,6 +5338,7 @@ function writeFlash(id: string, patch: FlashPulse, how: PulseWrite) {
}
function EffectPanel({ overlay: o }: { overlay: EffectOverlay }) {
+ const t = useTranslations("inspector.effect");
const amountCk = useSliderCheckpoint();
return (
<>
@@ -5304,9 +5358,9 @@ function EffectPanel({ overlay: o }: { overlay: EffectOverlay }) {
<FlashFadeRow pulse={o} write={(patch, how) => writeFlash(o.id, patch, how)} />
</>
)}
- <Row label="Amount">
+ <Row label={t("amount")}>
<ValueSlider
- label="Effect amount"
+ label={t("effectAmount")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.amount ?? 0.5}
@@ -5335,25 +5389,17 @@ function EffectPanel({ overlay: o }: { overlay: EffectOverlay }) {
);
}
-/** What a glitch's kinds are called in the panel; "mix" is the random
- * schedule, stored as absence. */
-const GLITCH_LABELS: Record<GlitchKind | "mix", string> = {
- mix: "Mix",
- smear: "Smear",
- split: "Split",
- tint: "Tint",
- blowout: "Blowout",
- rgb: "RGB split",
-};
-
-/** A glitch's kind: the random mix, or one kind pinned to every frame. */
+/** A glitch's kind: the random mix, or one kind pinned to every frame. The
+ * kinds name themselves under `inspector.effect.glitchKinds`; "mix" is the
+ * random schedule, stored as absence. */
function GlitchKindRow({ overlay: o }: { overlay: EffectOverlay }) {
+ const t = useTranslations("inspector.effect");
const kinds = ["mix", ...GLITCH_KINDS] as const;
return (
- <Row label="Kind">
+ <Row label={t("kind")}>
<Select
value={o.glitch ?? "mix"}
- items={Object.fromEntries(kinds.map((k) => [k, GLITCH_LABELS[k]]))}
+ items={Object.fromEntries(kinds.map((k) => [k, t(`glitchKinds.${k}`)]))}
onValueChange={(v) => useEditor.getState().updateOverlay(o.id, { glitch: v === "mix" ? undefined : (v as GlitchKind) })}
>
<SelectTrigger className="h-8 w-36 text-[12px]">
@@ -5362,7 +5408,7 @@ function GlitchKindRow({ overlay: o }: { overlay: EffectOverlay }) {
<SelectContent>
{kinds.map((k) => (
<SelectItem key={k} value={k} className="text-[12px]">
- {GLITCH_LABELS[k]}
+ {t(`glitchKinds.${k}`)}
</SelectItem>
))}
</SelectContent>
@@ -5371,16 +5417,15 @@ function GlitchKindRow({ overlay: o }: { overlay: EffectOverlay }) {
);
}
-/** What each light leak course is called in the panel. */
-const LEAK_LABELS: Record<LeakCourse, string> = { drift: "Drift", burn: "Burn", scorch: "Scorch", film: "Film", char: "Char" };
-
/** A light leak's course: a drifting glow for the whole element, the film
* burn played once across it, the scorch flashing hot tones through it, the
- * film-strip flash over a cut, or the burn's dark climb. */
+ * film-strip flash over a cut, or the burn's dark climb. Each course names
+ * itself under `inspector.effect.leakCourses`. */
function LeakCourseRow({ overlay: o }: { overlay: EffectOverlay }) {
+ const t = useTranslations("inspector.effect");
const leak = o.leak ?? "drift";
return (
- <Row label="Course">
+ <Row label={t("course")}>
<div className="flex w-44 rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
{LEAK_COURSES.map((c) => (
<button
@@ -5393,7 +5438,7 @@ function LeakCourseRow({ overlay: o }: { overlay: EffectOverlay }) {
)}
onClick={() => useEditor.getState().updateOverlay(o.id, { leak: c === "drift" ? undefined : c })}
>
- {LEAK_LABELS[c]}
+ {t(`leakCourses.${c as LeakCourse}`)}
</button>
))}
</div>
@@ -5401,14 +5446,13 @@ function LeakCourseRow({ overlay: o }: { overlay: EffectOverlay }) {
);
}
-/** What each text texture is called in the panel. */
-const TEXT_TEXTURE_LABELS: Record<TextTexture | "none", string> = { none: "None", stipple: "Stipple" };
-
-/** The grain a title wears inside its letters, or none. */
+/** The grain a title wears inside its letters, or none; each names itself
+ * under `inspector.text.textures`. */
function TextTextureRow({ overlay: o }: { overlay: TextOverlay }) {
+ const t = useTranslations("inspector.text");
const texture = o.texture ?? "none";
return (
- <Row label="Texture">
+ <Row label={t("texture")}>
<div className="flex w-36 rounded-lg border border-input p-0.5 text-[11.5px] font-medium">
{(["none", ...TEXT_TEXTURES] as const).map((c) => (
<button
@@ -5421,7 +5465,7 @@ function TextTextureRow({ overlay: o }: { overlay: TextOverlay }) {
)}
onClick={() => useEditor.getState().updateOverlay(o.id, { texture: c === "none" ? undefined : c })}
>
- {TEXT_TEXTURE_LABELS[c]}
+ {t(`textures.${c as TextTexture | "none"}`)}
</button>
))}
</div>
@@ -5441,7 +5485,10 @@ const PUCK = 20;
* three steps — a zoom is a choice of how close, and a slider of it is a
* decision nobody wants to make twice.
*/
+type ZoomLevelId = keyof Messages["inspector"]["effect"]["zoomLevels"];
+
function ZoomTarget({ overlay: o }: { overlay: EffectOverlay }) {
+ const t = useTranslations("inspector.effect");
const aspect = useEditor((s) => s.aspect);
const frame = frameOf(aspect);
const canvasRef = useRef<HTMLCanvasElement>(null);
@@ -5514,7 +5561,7 @@ function ZoomTarget({ overlay: o }: { overlay: EffectOverlay }) {
/>
</div>
<div className="flex w-full flex-col">
- <Row label="Depth" grow>
+ <Row label={t("depth")} grow>
{/* The segmented control the rest of the inspector uses — bordered
box, dark pill on the chosen one — stretched over the row's
free width. */}
@@ -5532,14 +5579,14 @@ function ZoomTarget({ overlay: o }: { overlay: EffectOverlay }) {
)}
onClick={() => useEditor.getState().updateOverlay(o.id, { amount: l.amount })}
>
- {l.label}
+ {t(`zoomLevels.${l.id as ZoomLevelId}`)}
</button>
))}
</div>
</Row>
- <Row label="Speed">
+ <Row label={t("speed")}>
<ValueSlider
- label="Zoom speed"
+ label={t("zoomSpeed")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={ramp}
@@ -5565,6 +5612,7 @@ function ZoomTarget({ overlay: o }: { overlay: EffectOverlay }) {
}
function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
+ const t = useTranslations("inspector.sticker");
const widthCk = useSliderCheckpoint();
const asset = useEditor((s) =>
o.assetId ? s.assets.find((a) => a.id === o.assetId) : undefined
@@ -5578,9 +5626,9 @@ function StickerPanel({ overlay: o }: { overlay: StickerOverlay }) {
{asset.name}
</div>
) : null}
- <Row label="Size">
+ <Row label={t("size")}>
<ValueSlider
- label="Sticker size"
+ label={t("stickerSize")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={o.w}
diff --git a/site/src/cut/components/IntroOffer.tsx b/site/src/cut/components/IntroOffer.tsx
index ddb59bee..33abb933 100644
--- a/site/src/cut/components/IntroOffer.tsx
+++ b/site/src/cut/components/IntroOffer.tsx
@@ -3,24 +3,30 @@
// The intro discount as every Pro surface states it: the terms in one line,
// and a wall's banner that becomes the offer's picture while it is open.
import type { LucideIcon } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import type { OfferBanner } from "@/cut/components/OfferDialog";
+import type { Locale } from "@/i18n/locales";
+import { formatUsdPlain } from "@/lib/credits/format-usd";
import type { IntroOffer } from "@/queries/billing";
/** Cents as a price reads: 1000 → "$10", 999 → "$9.99". */
-export function priceLabel(cents: number): string {
- return cents % 100 === 0 ? `$${cents / 100}` : `$${(cents / 100).toFixed(2)}`;
+export function priceLabel(cents: number, locale: Locale): string {
+ return formatUsdPlain((cents / 100).toFixed(2), locale);
}
-/** "$10 for your first month" or "$10/month for your first 3 months". */
-export function introPrice(offer: IntroOffer): string {
- const price = priceLabel(offer.introCents);
- return offer.months === 1 ? `${price} for your first month` : `${price}/month for your first ${offer.months} months`;
-}
-
-/** "50% off: $10 for your first month, then $20/month." */
-export function introTerms(offer: IntroOffer): string {
- return `${offer.percentOff}% off: ${introPrice(offer)}, then ${priceLabel(offer.priceCents)}/month.`;
+/** The intro terms in the page's language: "50% off: $10 for your first
+ * month, then $20/month." */
+export function useIntroTerms(): (offer: IntroOffer) => string {
+ const t = useTranslations("billing.intro");
+ const locale = useLocale();
+ return (offer) =>
+ t("terms", {
+ full: priceLabel(offer.priceCents, locale),
+ months: offer.months,
+ percent: offer.percentOff,
+ price: priceLabel(offer.introCents, locale),
+ });
}
/** A wall's banner: a quiet bar with the wall's icon, half the height of an
diff --git a/site/src/cut/components/LibraryCard.tsx b/site/src/cut/components/LibraryCard.tsx
index 7d8416c0..98f72938 100644
--- a/site/src/cut/components/LibraryCard.tsx
+++ b/site/src/cut/components/LibraryCard.tsx
@@ -2,6 +2,7 @@
import { useCallback, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { useLocale, useTranslations } from "next-intl";
import { isLinkedAssetType, type AssetType } from "@/cut/lib/types";
import { Film, Image as ImageIcon, Loader2, Music, Type } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
@@ -33,6 +34,7 @@ import { PICKED_RING } from "@/cut/lib/assetPick";
import { formatElapsed } from "@/cut/lib/time";
import { formatBytes } from "@/lib/bytes";
import { cn } from "@/lib/utils";
+import { useDescribeError } from "@/i18n/describeError";
export const LIBRARY_TILE_AREA = 180 * 320;
export const LIBRARY_AUDIO_TILE_AREA = LIBRARY_TILE_AREA * 0.7 ** 2;
@@ -185,6 +187,9 @@ export function LibraryCard({
onRename?: (name: string) => Promise<unknown>;
onDragStartExtra?: (e: React.DragEvent) => void;
}) {
+ const t = useTranslations("home.card");
+ const locale = useLocale();
+ const describeError = useDescribeError();
// ⌘C over the card copies its mention token. A card inside the current
// selection carries the whole set, the same rule its drag follows. A font is
// used from the font menu, so it names nothing a prompt can point a tool
@@ -250,7 +255,7 @@ export function LibraryCard({
// TTF · 42 KB — what the file is, and how much of it there is.
const fontMeta = [
fileKind(a.fileName),
- sizeBytes != null && formatBytes(sizeBytes),
+ sizeBytes != null && formatBytes(sizeBytes, locale),
]
.filter(Boolean)
.join(" · ");
@@ -265,7 +270,7 @@ export function LibraryCard({
if (!name || !onRename) return;
setRenameError(undefined);
onRename(name).catch((e: unknown) => {
- setRenameError(e instanceof Error ? e.message : "Could not rename the file.");
+ setRenameError(describeError(e, t("renameFailed")));
setTimeout(() => setRenameError(undefined), 6000);
});
}}
@@ -410,12 +415,12 @@ export function LibraryCard({
}
>
{proxyState.kind === "making" && <Loader2 className="size-3 animate-spin" />}
- {proxyState.kind === "making" ? "Preparing" : "Can't play"}
+ {proxyState.kind === "making" ? t("preparing") : t("cantPlay")}
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{proxyState.kind === "making"
- ? "Making a copy this browser can play"
- : proxyState.error}
+ ? t("makingCopy")
+ : describeError(proxyState)}
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -469,7 +474,7 @@ export function LibraryCard({
a.type === "video" && "hidden group-hover:inline",
)}
>
- {formatBytes(sizeBytes)}
+ {formatBytes(sizeBytes, locale)}
</span>
)}
</span>
@@ -477,7 +482,7 @@ export function LibraryCard({
{a.type === "audio" && sizeBytes != null && (
// Clear of the play circle, matching the face's duration pill.
<span className="absolute bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 font-mono text-[10px] text-[#d6eddf] tabular-nums opacity-0 transition-opacity group-hover:opacity-100">
- {formatBytes(sizeBytes)}
+ {formatBytes(sizeBytes, locale)}
</span>
)}
{bothShelves && (
@@ -516,7 +521,7 @@ export function LibraryCard({
/>
}
>
- Rename failed
+ {t("renameFailedBadge")}
</TooltipTrigger>
<TooltipContent className="max-w-xs">{renameError}</TooltipContent>
</Tooltip>
diff --git a/site/src/cut/components/LibraryImportCard.tsx b/site/src/cut/components/LibraryImportCard.tsx
index 6bb7b1db..9cff8dc6 100644
--- a/site/src/cut/components/LibraryImportCard.tsx
+++ b/site/src/cut/components/LibraryImportCard.tsx
@@ -2,6 +2,7 @@
import { useCallback, useState } from "react";
import { File as FileIcon, Loader2, RotateCcw, X } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
@@ -24,6 +25,7 @@ import { setLibraryImportShape, type LibraryArrival } from "@/cut/lib/libraryInt
import { fileKind } from "@/cut/lib/media";
import { formatBytes } from "@/lib/bytes";
import { cn } from "@/lib/utils";
+import { useDescribeError } from "@/i18n/describeError";
/** An arriving file wears the tile its asset will, with a spinner in the
* corner while storage runs; failed imports keep their retry. */
@@ -45,6 +47,9 @@ export function LibraryImportCard({
* click opens every card, and a double-click in the editor's panel. */
opensOn?: "click" | "doubleClick";
}) {
+ const t = useTranslations("home.importCard");
+ const locale = useLocale();
+ const describeError = useDescribeError();
const elapsed = useElapsed(item.error ? null : item.startedAt);
const [previewUrl, setPreviewUrl] = useState<string>();
// The clip's decoded frame and length while its poster holds them.
@@ -103,7 +108,7 @@ export function LibraryImportCard({
ref={tileRef}
role={canPreview ? "button" : undefined}
tabIndex={canPreview ? 0 : undefined}
- aria-label={canPreview ? `Preview ${item.name}` : undefined}
+ aria-label={canPreview ? t("preview", { name: item.name }) : undefined}
onClick={canPreview && opensOn === "click" ? openPreview : undefined}
onDoubleClick={canPreview && opensOn === "doubleClick" ? openPreview : undefined}
onKeyDown={canPreview ? (event) => {
@@ -135,7 +140,7 @@ export function LibraryImportCard({
className="w-24 justify-start"
onClick={onRetry}
>
- <RotateCcw data-icon="inline-start" /> Retry
+ <RotateCcw data-icon="inline-start" /> {t("retry")}
</Button>
<Button
variant="outline"
@@ -143,13 +148,13 @@ export function LibraryImportCard({
className="w-24 justify-start text-destructive hover:text-destructive"
onClick={onDismiss}
>
- <X data-icon="inline-start" /> Cancel
+ <X data-icon="inline-start" /> {t("cancel")}
</Button>
</div>
) : font ? (
<LibraryFontFace
name={item.name}
- meta={[fileKind(item.name), file && formatBytes(file.size)].filter(Boolean).join(" · ")}
+ meta={[fileKind(item.name), file && formatBytes(file.size, locale)].filter(Boolean).join(" · ")}
specimen={previewUrl && <FontSpecimen assetId={item.id} src={previewUrl} pad={0} className="size-full" />}
/>
) : mediaType === "lut" ? (
@@ -175,7 +180,7 @@ export function LibraryImportCard({
) : file && !mediaType ? (
<div className="flex size-full flex-col items-center justify-center gap-2 text-muted-foreground">
<FileIcon className="size-8" />
- <span className="text-xs uppercase">Archive</span>
+ <span className="text-xs uppercase">{t("archive")}</span>
</div>
) : (
<Skeleton className="size-full rounded-none" />
@@ -212,9 +217,9 @@ export function LibraryImportCard({
<span className="absolute top-1.5 right-1.5 rounded-md bg-destructive/90 px-1.5 py-0.5 text-[10px] text-white" />
}
>
- Failed
+ {t("failed")}
</TooltipTrigger>
- <TooltipContent className="max-w-xs">{item.error}</TooltipContent>
+ <TooltipContent className="max-w-xs">{describeError(item)}</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
@@ -226,7 +231,7 @@ export function LibraryImportCard({
<TooltipTrigger
render={
<span
- aria-label="Importing"
+ aria-label={t("importing")}
className={cn(
"absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full text-white transition-opacity",
font ? "bg-white/10" : "bg-black/40",
@@ -238,7 +243,10 @@ export function LibraryImportCard({
<Loader2 className="size-3.5 animate-spin" />
</TooltipTrigger>
<TooltipContent>
- Importing <span className="font-mono tabular-nums">{elapsed}</span>
+ {t.rich("importingFor", {
+ elapsed: elapsed ?? "",
+ time: (chunks) => <span className="font-mono tabular-nums">{chunks}</span>,
+ })}
</TooltipContent>
</Tooltip>
</TooltipProvider>
diff --git a/site/src/cut/components/LibraryShareDialog.tsx b/site/src/cut/components/LibraryShareDialog.tsx
index ae1185c7..a8aa61cd 100644
--- a/site/src/cut/components/LibraryShareDialog.tsx
+++ b/site/src/cut/components/LibraryShareDialog.tsx
@@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from "react";
import { Cloud, Loader2 } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { ShareDialog } from "@/cut/components/ShareDialog";
@@ -11,6 +12,7 @@ import { refetchLibrary } from "@/cut/lib/queries";
import type { LibraryData } from "@/cut/lib/library";
import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
import type { Residency } from "@/cut/lib/residency";
+import { useDescribeError } from "@/i18n/describeError";
type Props = {
target: LibraryShareTarget & { residency: Residency };
@@ -19,6 +21,8 @@ type Props = {
onCopied: (target: LibraryShareTarget) => void;
};
export function LibraryShareDialog({ target, library, onClose, onCopied }: Props) {
+ const t = useTranslations("home.libraryShare");
+ const describeError = useDescribeError();
const [ready, setReady] = useState<LibraryShareTarget | null>(target.residency === "cloud" ? target : null);
const [copying, setCopying] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -42,7 +46,7 @@ export function LibraryShareDialog({ target, library, onClose, onCopied }: Props
onCopied(landed);
}
} catch (e) {
- if (mounted.current) setError(e instanceof Error ? e.message : "Could not copy to Cloud.");
+ if (mounted.current) setError(describeError(e, t("copyFailed")));
} finally {
setCopying(false);
started.current = false;
@@ -51,10 +55,10 @@ export function LibraryShareDialog({ target, library, onClose, onCopied }: Props
if (ready) return <ShareDialog libraryTarget={ready} onClose={onClose} />;
return <Dialog open onOpenChange={(open) => { if (!open && !copying) onClose(); }}>
<DialogContent className="sm:max-w-sm" showCloseButton={!copying}>
- <DialogHeader><DialogTitle>Share {target.kind}</DialogTitle></DialogHeader>
- <p className="text-sm text-muted-foreground">Copy this {target.kind} to Cloud so people can open it while your device is offline. Share settings will apply to the cloud copy. Your local files stay here.</p>
+ <DialogHeader><DialogTitle>{t("title", { kind: target.kind })}</DialogTitle></DialogHeader>
+ <p className="text-sm text-muted-foreground">{t("body", { kind: target.kind })}</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
- <Button disabled={copying} onClick={() => void copy()}>{copying ? <Loader2 className="animate-spin" /> : <Cloud />}{copying ? "Copying to Cloud…" : "Copy to Cloud"}</Button>
+ <Button disabled={copying} onClick={() => void copy()}>{copying ? <Loader2 className="animate-spin" /> : <Cloud />}{copying ? t("copying") : t("copy")}</Button>
</DialogContent>
</Dialog>;
}
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index aa46d6fd..693b0019 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -5,6 +5,7 @@ import { LibraryImportCard } from "@/cut/components/LibraryImportCard";
import { libraryFolderRef } from "@/cut/lib/folderReference";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
import { useRouter, useSearchParams } from "next/navigation";
import {
StickyNote,
@@ -87,9 +88,7 @@ import {
import {
DeleteConfirm,
SelectionMenu,
- foldersGoNote,
- phoneGoNote,
- pickLabel,
+ usePickWords,
useSelectionMenu,
} from "./selectionMenu";
@@ -108,6 +107,8 @@ type DeleteSet = { folders: LibraryFolder[]; items: (LibraryAsset | LibraryTempl
const NO_PICK: DeleteSet = { folders: [], items: [] };
export function LibraryView() {
+ const t = useTranslations("home");
+ const { pickLabel, foldersGoNote, phoneGoNote } = usePickWords();
const noteView = useRef<NotesViewHandle>(null);
const router = useRouter();
const base = useCutBase();
@@ -471,7 +472,7 @@ export function LibraryView() {
// The way down to the open folder, and what is filed right here.
const trail = useMemo(() => folderTrail(folders, openFolder), [folders, openFolder]);
// The tab names the open folder; an open note names itself.
- useTabTitle(params.has("note") ? null : openFolder ? trail.at(-1)?.name : "Library");
+ useTabTitle(params.has("note") ? null : openFolder ? trail.at(-1)?.name : t("tabs.library"));
const shownFolders = useMemo(() => childrenOf(folders, openFolder), [folders, openFolder]);
// What can be picked at this level, in the order a ⇧-range runs: the
// shelf's folders, then the grid with templates leading.
@@ -622,10 +623,10 @@ export function LibraryView() {
<div className="mx-auto w-full max-w-6xl px-10 py-9">
<div className="mb-5 flex items-center justify-between gap-4">
{openFolder === null ? (
- <h1 className="text-lg font-semibold tracking-tight">Library</h1>
+ <h1 className="text-lg font-semibold tracking-tight">{t("tabs.library")}</h1>
) : (
<FolderCrumb
- root="Library"
+ root={t("tabs.library")}
trail={trail}
onRename={openOwner && live(openOwner) ? renameFolder : undefined}
mime={LIBRARY_MOVE_MIME}
@@ -636,14 +637,14 @@ export function LibraryView() {
/>
)}
<div className="flex items-center gap-2">
- {openFolder && openOwner && <Button variant="outline" disabled={!live(openOwner)} onClick={() => shareFolder(openFolder)}><Share2 data-icon="inline-start" /> Share</Button>}
+ {openFolder && openOwner && <Button variant="outline" disabled={!live(openOwner)} onClick={() => shareFolder(openFolder)}><Share2 data-icon="inline-start" /> {t("library.share")}</Button>}
{(openFolder === null || newParent) && (
<Button variant="outline" onClick={() => setFolderCreating(true)}>
- <FolderPlus data-icon="inline-start" /> New folder
+ <FolderPlus data-icon="inline-start" /> {t("library.newFolder")}
</Button>
)}
<Button onClick={() => setAddOpen(true)}>
- <Upload data-icon="inline-start" /> Add media
+ <Upload data-icon="inline-start" /> {t("library.addMedia")}
</Button>
</div>
<input
@@ -709,7 +710,7 @@ export function LibraryView() {
onDropFiles={(files, fid) => void upload(files, fid)}
/>
- <NotesView ref={noteView} library={{ folderId: openFolder, residency: openOwner ?? target, name: trail.at(-1)?.name ?? "Library" }} />
+ <NotesView ref={noteView} library={{ folderId: openFolder, residency: openOwner ?? target, name: trail.at(-1)?.name ?? t("tabs.library") }} />
{!library.data && library.isPending && shownPending.length === 0 ? (
<div className="grid place-items-center py-24 text-muted-foreground">
@@ -723,10 +724,10 @@ export function LibraryView() {
<div className="flex flex-col items-center gap-3 text-center">
<FolderOpen className="size-8 text-muted-foreground" />
<div className="text-base font-medium">
- Your Library is shared across all projects.
+ {t("library.emptyTitle")}
</div>
<p className="text-sm text-muted-foreground">
- Drag and drop videos, images, audio, or font files here.
+ {t("library.emptyHint")}
</p>
</div>
</button>
@@ -825,7 +826,7 @@ export function LibraryView() {
<Dialog open={addOpen} onOpenChange={setAddOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>Add media</DialogTitle>
+ <DialogTitle>{t("library.addMedia")}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<button
@@ -833,10 +834,10 @@ export function LibraryView() {
onClick={() => inputRef.current?.click()}
>
<Upload className="size-6 text-muted-foreground" />
- <span className="text-sm font-medium">Choose files</span>
+ <span className="text-sm font-medium">{t("library.chooseFiles")}</span>
</button>
<div className="flex items-center gap-3 text-[11px] tracking-wide text-muted-foreground uppercase">
- <div className="h-px flex-1 bg-border" /> or paste a link{" "}
+ <div className="h-px flex-1 bg-border" /> {t("library.orPasteLink")}{" "}
<div className="h-px flex-1 bg-border" />
</div>
<div className="flex flex-col gap-1.5">
@@ -846,7 +847,7 @@ export function LibraryView() {
<Input
autoFocus
value={url}
- placeholder="TikTok, YouTube, or Instagram link…"
+ placeholder={t("library.linkPlaceholder")}
className="pl-8"
onChange={(e) => setUrl(e.target.value)}
onKeyDown={(e) => {
@@ -858,7 +859,7 @@ export function LibraryView() {
disabled={!url.trim()}
onClick={() => void importLink(url)}
>
- <LinkIcon /> Import
+ <LinkIcon /> {t("library.import")}
</Button>
</div>
</div>
@@ -869,10 +870,10 @@ export function LibraryView() {
<SelectionMenu menu={ctx.menu} onClose={ctx.close}>
{ctx.menu?.ids.length === 0 ? <>
{(openFolder === null || newParent) && (
- <DropdownMenuItem onClick={() => setFolderCreating(true)}><FolderPlus /> New folder</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setFolderCreating(true)}><FolderPlus /> {t("library.newFolder")}</DropdownMenuItem>
)}
- <DropdownMenuItem onClick={() => noteView.current?.create()}><StickyNote /> Add note</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setAddOpen(true)}><Upload /> Add media</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => noteView.current?.create()}><StickyNote /> {t("library.addNote")}</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setAddOpen(true)}><Upload /> {t("library.addMedia")}</DropdownMenuItem>
</> : ctxFolder ? (
<FolderMenuItems
onShare={() => shareFolder(ctxFolder.id)}
@@ -889,11 +890,11 @@ export function LibraryView() {
setSharing({ kind: "asset", id: asset.id, residency: asset.residency });
}}
>
- <Share2 /> Share
+ <Share2 /> {t("library.share")}
</DropdownMenuItem>
)}
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
- <Trash2 /> Delete
+ <Trash2 /> {t("library.delete")}
</DropdownMenuItem>
</>
)}
@@ -902,10 +903,10 @@ export function LibraryView() {
<DeleteConfirm
open={!!deleting}
title={
- deleting ? `Delete ${pickLabel(deleting.folders, deleting.items, ["item", "items"], deletingHeld)}?` : ""
+ deleting ? t("library.deleteTitle", { what: pickLabel(deleting.folders, deleting.items, "item", deletingHeld) }) : ""
}
- description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}
- action="Remove"
+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}${t("library.keepCopy", { count: deletingTotal })}`}
+ action={t("library.remove")}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && void remove(deleting)}
/>
diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsx
index c310b3d9..7820f2ac 100644
--- a/site/src/cut/components/Lightbox.tsx
+++ b/site/src/cut/components/Lightbox.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";
import { LUT_FILE_ICON } from "@/cut/lib/linkedLibrary";
import { isLinkedAssetType } from "@/cut/lib/types";
import { Check, Copy, FileText, Loader2, Music, Plus, X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { addLibraryAssetToProject, fetchLibrary } from "@/cut/lib/library";
@@ -39,6 +40,7 @@ const FALLBACK_RATIO = 16 / 9;
const VIEWER_FRAME_SIZE = 720;
export function Lightbox() {
+ const t = useTranslations("editor.lightbox");
const item = useLightbox((s) => s.item);
// The shape the media reported on load, for an item opened without one.
// Keyed to its src, so the next item starts unmeasured.
@@ -141,7 +143,7 @@ export function Lightbox() {
onClick={(e) => e.stopPropagation()}
>
<button
- title="Close"
+ title={t("close")}
className="absolute top-3 right-3 z-10 grid size-8 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"
onClick={() => useLightbox.getState().close()}
>
@@ -168,7 +170,7 @@ export function Lightbox() {
) : (
<Plus data-icon="inline-start" />
)}
- {added ? "Added" : "Use"}
+ {added ? t("added") : t("use")}
</Button>
)}
</div>
@@ -177,10 +179,10 @@ export function Lightbox() {
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<span className="text-[11px] font-semibold tracking-wide text-white/60 uppercase">
- Prompt
+ {t("prompt")}
</span>
<button
- title="Copy prompt"
+ title={t("copyPrompt")}
className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-white/60 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => {
void navigator.clipboard
@@ -196,7 +198,7 @@ export function Lightbox() {
) : (
<Copy className="size-3" />
)}
- {copied ? "Copied" : "Copy"}
+ {copied ? t("copied") : t("copy")}
</button>
</div>
<p className="rounded-lg bg-white/10 px-3 py-2 text-[12.5px] leading-relaxed text-white/90">
@@ -263,6 +265,7 @@ function VideoBody({
style?: { aspectRatio: number };
onRatio: (ratio: number) => void;
}) {
+ const t = useTranslations("editor.lightbox");
const videoRef = useRef<HTMLVideoElement>(null);
// Playing is what the element reports, never what was asked of it: an
// autoplay the browser blocks fires no `pause`, and a transport that
@@ -342,7 +345,7 @@ function VideoBody({
{blank && (
<span className="pointer-events-none absolute top-3 left-3 flex items-center gap-1.5 rounded-full bg-black/55 px-2.5 py-1 text-[11px] text-white backdrop-blur-sm">
<Loader2 className="size-3 animate-spin" />
- Preparing playback
+ {t("preparingPlayback")}
</span>
)}
<MediaTransport
@@ -463,6 +466,7 @@ function LutBody({ item }: { item: LightboxItem }) {
}
function TextBody({ item }: { item: LightboxItem }) {
+ const t = useTranslations("editor.lightbox");
const { text, failed } = useDocText(item.src);
return (
<div className="flex max-h-[68vh] flex-col overflow-hidden rounded-2xl bg-card shadow-2xl">
@@ -472,7 +476,7 @@ function TextBody({ item }: { item: LightboxItem }) {
</div>
<div className="min-h-0 overflow-y-auto px-4 py-3 text-[12.5px] leading-relaxed">
{failed ? (
- <p className="text-muted-foreground">Could not read the file.</p>
+ <p className="text-muted-foreground">{t("readFailed")}</p>
) : text === null ? (
<Loader2 className="size-4 animate-spin text-muted-foreground" />
) : (
diff --git a/site/src/cut/components/LocaleSync.tsx b/site/src/cut/components/LocaleSync.tsx
new file mode 100644
index 00000000..0ea0b622
--- /dev/null
+++ b/site/src/cut/components/LocaleSync.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { useLocale } from "next-intl";
+import { useEffect, useRef } from "react";
+
+import { bindCreatorLocale } from "@/cut/lib/defaultNames";
+import { switchLocale } from "@/i18n/localeCookie";
+import { useAccountProfile, useUpdateLocale } from "@/queries/accountProfile";
+
+// The account's language follows the person across browsers. This browser's
+// 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.
+export function LocaleSync() {
+ const locale = useLocale();
+ const profile = useAccountProfile();
+ const updateLocale = useUpdateLocale();
+ const recorded = useRef(false);
+ const saved = profile.data?.locale;
+
+ // What the editor creates (an untitled project, a new title) is named in
+ // the language the page draws in.
+ useEffect(() => {
+ void bindCreatorLocale(locale);
+ }, [locale]);
+
+ useEffect(() => {
+ if (!profile.data) {
+ return;
+ }
+ if (saved && saved !== locale) {
+ switchLocale(saved);
+ return;
+ }
+ if (!saved && !recorded.current) {
+ recorded.current = true;
+ updateLocale.mutate(locale);
+ }
+ }, [profile.data, saved, locale, updateLocale]);
+
+ return null;
+}
diff --git a/site/src/cut/components/MediaTransport.tsx b/site/src/cut/components/MediaTransport.tsx
index 3f21accc..0e9ac535 100644
--- a/site/src/cut/components/MediaTransport.tsx
+++ b/site/src/cut/components/MediaTransport.tsx
@@ -2,6 +2,7 @@
import { useRef, useState } from "react";
import { Pause, Play, Volume2, VolumeX } from "lucide-react";
+import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
import { formatElapsed } from "@/cut/lib/time";
@@ -38,6 +39,7 @@ export function MediaTransport({
onSeek: (t: number) => void;
onToggleMute?: () => void;
}) {
+ const t = useTranslations("timeline.media");
const barRef = useRef<HTMLDivElement>(null);
const [scrubbing, setScrubbing] = useState(false);
const pct = duration > 0 ? Math.min(1, Math.max(0, time / duration)) * 100 : 0;
@@ -66,8 +68,8 @@ export function MediaTransport({
<button
type="button"
className="grid size-8 shrink-0 place-items-center rounded-full bg-white/15 text-white backdrop-blur-sm transition-colors hover:bg-white/25"
- aria-label={playing ? "Pause" : "Play"}
- title={playing ? "Pause" : "Play"}
+ aria-label={playing ? t("pause") : t("play")}
+ title={playing ? t("pause") : t("play")}
onClick={onToggle}
>
{playing ? <Pause className="size-4 fill-white" /> : <Play className="size-4 fill-white" />}
@@ -78,7 +80,7 @@ export function MediaTransport({
className="relative h-4 flex-1 cursor-pointer touch-none"
role="slider"
tabIndex={0}
- aria-label="Seek"
+ aria-label={t("seek")}
aria-valuemin={0}
aria-valuemax={Math.max(0, duration)}
aria-valuenow={time}
@@ -114,8 +116,8 @@ export function MediaTransport({
<button
type="button"
className="grid size-7 shrink-0 place-items-center rounded-full text-white/85 transition-colors hover:bg-white/15 hover:text-white"
- aria-label={muted ? "Unmute" : "Mute"}
- title={muted ? "Unmute" : "Mute"}
+ aria-label={muted ? t("unmute") : t("mute")}
+ title={muted ? t("unmute") : t("mute")}
onClick={onToggleMute}
>
{muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}
diff --git a/site/src/cut/components/MicDictation.tsx b/site/src/cut/components/MicDictation.tsx
index 304e94db..03b225d2 100644
--- a/site/src/cut/components/MicDictation.tsx
+++ b/site/src/cut/components/MicDictation.tsx
@@ -2,10 +2,12 @@
import { useEffect } from "react";
import { Check, Mic, X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
import { useCutCaps } from "@/cut/lib/backend/hooks";
import { useMicTranscription, type MicController } from "@/cut/lib/micTranscribe";
import { LiveWaveform } from "./RecordDialog";
+import { useChatError } from "./chatError";
// Shared voice-dictation UI, used by every prompt input (the AI chat composer
// and the image / video / audio generation prompts). The capture + on-device
@@ -33,6 +35,7 @@ export function DictationBody({
mic: MicController;
className?: string;
}) {
+ const t = useTranslations("chat.dictation");
const shown = [text.trim(), mic.partial].filter(Boolean).join(" ");
const finishing = mic.state === "finishing";
// Confirm only means something once capture is live; while the graph is
@@ -61,7 +64,7 @@ export function DictationBody({
<div className={cn("flex min-h-[72px] flex-col", className)}>
<div className="min-h-0 flex-1 overflow-y-auto px-3 pt-2.5">
<p className="text-[12.5px] leading-relaxed text-muted-foreground/80 italic">
- {shown || "Listening…"}
+ {shown || t("listening")}
</p>
</div>
<div className="flex items-center gap-2 px-2 pt-1 pb-2">
@@ -75,12 +78,12 @@ export function DictationBody({
// Without the app the take is transcribed after the stop, which is a
// round trip the meter's empty slot can say out loud.
<div className="flex-1 px-1 text-[11px] text-muted-foreground/70">
- {finishing ? "Transcribing…" : null}
+ {finishing ? t("transcribing") : null}
</div>
)}
<button
type="button"
- title="Cancel"
+ title={t("cancel")}
disabled={finishing}
onClick={mic.cancel}
className="grid size-7 place-items-center rounded-lg bg-muted text-muted-foreground transition-colors hover:bg-muted/70 disabled:opacity-50"
@@ -89,7 +92,7 @@ export function DictationBody({
</button>
<button
type="button"
- title="Use transcription"
+ title={t("useTranscription")}
disabled={!ready}
onClick={() => void mic.confirm()}
className="grid size-7 place-items-center rounded-lg bg-[#0a84ff] text-white transition-colors hover:bg-[#0a84ff]/90 disabled:opacity-50"
@@ -115,8 +118,10 @@ export function DictationControl({
buttonClassName?: string;
disabled?: boolean;
}) {
+ const t = useTranslations("chat.dictation");
+ const chatError = useChatError();
const caps = useCutCaps();
- const mic = useMicTranscription((t) => onResult(appendTranscript(text, t)));
+ const mic = useMicTranscription((transcript) => onResult(appendTranscript(text, transcript)));
if (!caps.liveMic) return null;
return (
<>
@@ -128,7 +133,7 @@ export function DictationControl({
{mic.state === "idle" && (
<button
type="button"
- title="Dictate"
+ title={t("dictate")}
disabled={disabled}
onClick={() => void mic.start()}
className={cn(
@@ -141,7 +146,7 @@ export function DictationControl({
)}
{mic.error && mic.state === "idle" && (
<div className="absolute right-1 bottom-full z-30 mb-1 max-w-[240px] rounded-md bg-popover px-2 py-1 text-[10.5px] leading-snug text-amber-700 shadow-md">
- {mic.error}
+ {chatError(mic.error)}
</div>
)}
</>
diff --git a/site/src/cut/components/MotionControls.tsx b/site/src/cut/components/MotionControls.tsx
index e459afbc..22c0465a 100644
--- a/site/src/cut/components/MotionControls.tsx
+++ b/site/src/cut/components/MotionControls.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useMemo } from "react";
import {
CAMERA_SCALE_MAX,
@@ -7,7 +8,6 @@ import {
CAMERA_WORLD_MAX,
CAMERA_WORLD_MIN,
EASE_IDS,
- EASE_LABELS,
ELEMENT_BLUR_MAX,
hasOverlayKeys,
keyIndexAt,
@@ -31,6 +31,7 @@ import { CUT_MOTION } from "@/cut/lib/motionSettings";
import { usePreviewTime } from "@/cut/lib/playhead";
import { useEditor } from "@/cut/lib/store";
import { clipPoseAt, isEffectOverlay, type Overlay, type VideoClip } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
/**
* The motion rows an element, a selection of elements, and a group's camera
@@ -41,22 +42,24 @@ import { clipPoseAt, isEffectOverlay, type Overlay, type VideoClip } from "@/cut
const st = () => useEditor.getState();
const SLIDER = { sliderClassName: "data-horizontal:w-24", valueClassName: "w-9 text-muted-foreground" };
-const EASE_ITEMS = Object.fromEntries(EASE_IDS.map((id) => [id, EASE_LABELS[id]]));
const local = (o: { start: number; end: number }, now: number) =>
Math.max(0, Math.min(now - o.start, Math.max(0.1, o.end - o.start)));
/** The curve out of the key under the playhead. */
function EaseRow({ ease, onPick }: { ease: EaseId | undefined; onPick: (ease: EaseId | undefined) => void }) {
+ const t = useTranslations("inspector.motion");
+ const easeLabel = useLabels("ease");
+ const easeItems = Object.fromEntries(EASE_IDS.map((id) => [id, easeLabel(id)]));
return (
- <Row label="Ease">
- <Select value={ease ?? "linear"} items={EASE_ITEMS} onValueChange={(id) => onPick(id === "linear" ? undefined : (id as EaseId))}>
+ <Row label={t("ease")}>
+ <Select value={ease ?? "linear"} items={easeItems} onValueChange={(id) => onPick(id === "linear" ? undefined : (id as EaseId))}>
<SelectTrigger className="h-8 w-36 text-[12px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{EASE_IDS.map((id) => (
<SelectItem key={id} value={id} className="text-[12px]">
- {EASE_LABELS[id]}
+ {easeLabel(id)}
</SelectItem>
))}
</SelectContent>
@@ -75,20 +78,21 @@ function MotionBlurRows({
onChange: (motionBlur: number | undefined, phase: "draft" | "commit" | "once") => void;
ck: ReturnType<typeof useSliderCheckpoint>;
}) {
+ const t = useTranslations("inspector.motion");
return (
<>
- <Row label="Motion blur">
- {shutter?.mixed && <Value className="text-muted-foreground italic">Mixed</Value>}
+ <Row label={t("motionBlur")}>
+ {shutter?.mixed && <Value className="text-muted-foreground italic">{t("mixed")}</Value>}
<Switch
checked={!!shutter && !shutter.mixed}
onCheckedChange={(on) => onChange(on ? CUT_MOTION.motionBlur : undefined, "once")}
- aria-label="Motion blur"
+ aria-label={t("motionBlur")}
/>
</Row>
{shutter && (
- <Row label="Shutter">
+ <Row label={t("shutter")}>
<ValueSlider
- label="Shutter"
+ label={t("shutter")}
{...SLIDER}
value={shutter.value}
mixed={shutter.mixed}
@@ -123,10 +127,11 @@ function BlurRow({
onSet: (v: number) => void;
ck: ReturnType<typeof useSliderCheckpoint>;
}) {
+ const t = useTranslations("inspector.motion");
return (
- <Row label="Blur">
+ <Row label={t("blur")}>
<ValueSlider
- label="Blur"
+ label={t("blur")}
{...SLIDER}
value={blur.value}
mixed={blur.mixed}
@@ -245,6 +250,7 @@ export function ClipMotionRows({ clip, tLocal }: { clip: VideoClip; tLocal: numb
* play edits the key at the playhead; with none, it sets the first key.
*/
export function GroupCameraSection({ groupId }: { groupId: string }) {
+ const tr = useTranslations("inspector.motion");
const overlays = useEditor((s) => s.overlays);
const seek = useEditor((s) => s.seek);
const now = usePreviewTime();
@@ -270,7 +276,7 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
};
const keys = view.keys;
return (
- <Section title="Camera">
+ <Section title={tr("camera")}>
<KeyRow
element={{ start: view.start, end: view.end }}
now={now}
@@ -287,12 +293,12 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
}}
onSeek={seek}
/>
- <Row label="Look at">
+ <Row label={tr("lookAt")}>
{(["x", "y"] as const).map((axis) => (
<span key={axis} className="flex items-center gap-1">
<span className="text-[11px] text-muted-foreground/70 uppercase">{axis}</span>
<ScrubValue
- label={`Camera ${axis.toUpperCase()}`}
+ label={tr("cameraAxis", { axis: axis.toUpperCase() })}
className="w-9 text-muted-foreground"
value={pose[axis] * 100}
min={CAMERA_WORLD_MIN * 100}
@@ -315,9 +321,9 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
</span>
))}
</Row>
- <Row label="Zoom">
+ <Row label={tr("zoom")}>
<ValueSlider
- label="Camera zoom"
+ label={tr("cameraZoom")}
{...SLIDER}
valueClassName="w-12 text-muted-foreground"
value={pose.scale}
@@ -341,9 +347,9 @@ export function GroupCameraSection({ groupId }: { groupId: string }) {
}}
/>
</Row>
- <Row label="Roll">
+ <Row label={tr("roll")}>
<ValueSlider
- label="Camera roll"
+ label={tr("cameraRoll")}
{...SLIDER}
value={pose.rotation}
min={-180}
diff --git a/site/src/cut/components/NavStorage.tsx b/site/src/cut/components/NavStorage.tsx
index da51d365..e60bed16 100644
--- a/site/src/cut/components/NavStorage.tsx
+++ b/site/src/cut/components/NavStorage.tsx
@@ -7,6 +7,7 @@
// cloud projects, and the number is the same either way. Pro accounts see
// nothing here — 100 GB is enough that a meter would only take up room.
import { Cloud, Loader2 } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import {
Tooltip,
TooltipContent,
@@ -21,6 +22,8 @@ import { formatBytes } from "@/lib/bytes";
import { usageLabel } from "./StoragePill";
export function NavStorage() {
+ const t = useTranslations("home.navStorage");
+ const locale = useLocale();
const upgrade = useUpgradeToPro();
const pro = useProSubscription();
// The meter has to move as media lands, so this reader polls. Both faces wait
@@ -50,20 +53,20 @@ export function NavStorage() {
<span className="flex items-center gap-1.5 text-muted-foreground">
<Cloud className="size-4" />
<span className={cn("tabular-nums", frac >= 1 && "text-destructive")}>
- {usageLabel(u.bytes, u.quotaBytes)}
+ {usageLabel(u.bytes, u.quotaBytes, locale)}
</span>
</span>
<span className="flex items-center gap-1.5 group-hover:underline">
{upgrade.isPending && <Loader2 className="size-3 animate-spin" />}
- Get 100 GB
+ {t("get100")}
</span>
</TooltipTrigger>
- <TooltipContent>Upgrade for 100 GB + AI credits</TooltipContent>
+ <TooltipContent>{t("upgradeTip")}</TooltipContent>
</Tooltip>
</TooltipProvider>
{u.grace && (
<p className="px-2 pt-1 text-xs leading-snug text-muted-foreground">
- {`Your Pro plan ended. Upgrade or free ${formatBytes(u.grace.overBytes)} before your oldest projects are deleted.`}
+ {t("grace", { size: formatBytes(u.grace.overBytes, locale) })}
</p>
)}
</div>
diff --git a/site/src/cut/components/NavUser.tsx b/site/src/cut/components/NavUser.tsx
index cc0cf1c7..062f7fc9 100644
--- a/site/src/cut/components/NavUser.tsx
+++ b/site/src/cut/components/NavUser.tsx
@@ -1,6 +1,7 @@
"use client";
import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
import {
ChartColumn,
ChevronRight,
@@ -40,6 +41,7 @@ import { useAccountProfile, visibleName } from "@/queries/accountProfile";
// the name and picture the provider gave us, and only until the profile —
// which holds both, and is cached — answers.
export function NavUser() {
+ const t = useTranslations("home.navUser");
const router = useRouter();
const base = useCutBase();
const user = useEngineUser();
@@ -116,22 +118,22 @@ export function NavUser() {
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push(`${base}/settings`)}>
- <CreditCard /> Billing
+ <CreditCard /> {t("billing")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push(`${base}/settings/usage`)}>
- <ChartColumn /> Usage
+ <ChartColumn /> {t("usage")}
</DropdownMenuItem>
{/* The welcome sequence is a full-window overlay mounted in the app
shell, so this asks for it rather than routing anywhere. */}
<DropdownMenuItem onClick={openOnboarding}>
- <Sparkles /> View onboarding
+ <Sparkles /> {t("onboarding")}
</DropdownMenuItem>
<DropdownMenuItem onClick={runLocally}>
- <MonitorDown /> Run locally on Mac
+ <MonitorDown /> {t("runLocally")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={signOut}>
- <LogOut /> Log out
+ <LogOut /> {t("logOut")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/site/src/cut/components/NewProjectButton.tsx b/site/src/cut/components/NewProjectButton.tsx
index 5383c346..368e5ac7 100644
--- a/site/src/cut/components/NewProjectButton.tsx
+++ b/site/src/cut/components/NewProjectButton.tsx
@@ -1,6 +1,7 @@
"use client";
import { ChevronDown, Cloud, Laptop, Plus } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -16,7 +17,8 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useNewProjectTarget } from "@/cut/lib/newProject";
-import { RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";
+import type { Residency } from "@/cut/lib/residency";
+import { useLabels } from "@/i18n/labels";
import { cn } from "@/lib/utils";
const RESIDENCY_ICON: Record<Residency, typeof Cloud> = {
@@ -30,12 +32,11 @@ const RESIDENCY_ICON: Record<Residency, typeof Cloud> = {
// bold. The break is written into the copy rather than left to a width, so the
// sentence reads the same in both shelves. The menu needs no more than the two
// names.
-const RESIDENCY_LEAD = "All projects and media created going";
-const RESIDENCY_SCOPE: Record<Residency, { tail: string; place: string }> = {
- local: { tail: "forward will be stored on", place: "this device" },
- cloud: { tail: "forward will be stored on the", place: "Cloud" },
- browser: { tail: "forward will be stored on", place: "this device" },
-};
+const RESIDENCY_SCOPE = {
+ local: "scopeLocal",
+ cloud: "scopeCloud",
+ browser: "scopeLocal",
+} as const satisfies Record<Residency, string>;
/**
* Make a project, and — where the app keeps the switch — say where things land.
@@ -58,6 +59,8 @@ export function NewProjectButton({
onCreate: (r: Residency) => void;
className?: string;
}) {
+ const t = useTranslations("home.newProject");
+ const residencyLabel = useLabels("residency");
const { target, choices, pick } = useNewProjectTarget();
const r = pinned ?? target;
const Icon = RESIDENCY_ICON[r];
@@ -65,7 +68,7 @@ export function NewProjectButton({
if (!picker || pinned || choices.length < 2) {
return (
<Button className={className} onClick={() => onCreate(r)}>
- <Plus data-icon="inline-start" /> New project
+ <Plus data-icon="inline-start" /> {t("button")}
</Button>
);
}
@@ -76,7 +79,7 @@ export function NewProjectButton({
shelf are separate acts, so they stand apart rather than sharing an
edge. */}
<Button className="min-w-0 flex-1" onClick={() => onCreate(r)}>
- <Plus data-icon="inline-start" /> New project
+ <Plus data-icon="inline-start" /> <span className="truncate">{t("button")}</span>
</Button>
<DropdownMenu>
<TooltipProvider>
@@ -86,7 +89,7 @@ export function NewProjectButton({
<DropdownMenuTrigger
render={
<Button
- aria-label={`Where new projects and media are saved: ${RESIDENCY_LABEL[r]}`}
+ aria-label={t("whereSaved", { place: residencyLabel(r) })}
className="shrink-0 gap-1 px-2"
/>
}
@@ -97,10 +100,11 @@ export function NewProjectButton({
}
/>
<TooltipContent className="flex-col items-start gap-0 py-2 text-left">
- <span>{RESIDENCY_LEAD}</span>
<span>
- {RESIDENCY_SCOPE[r].tail}{" "}
- <span className="font-semibold">{RESIDENCY_SCOPE[r].place}</span>
+ {t.rich(RESIDENCY_SCOPE[r], {
+ br: () => <br />,
+ b: (chunks) => <span className="font-semibold">{chunks}</span>,
+ })}
</span>
</TooltipContent>
</Tooltip>
@@ -111,7 +115,7 @@ export function NewProjectButton({
const ChoiceIcon = RESIDENCY_ICON[c];
return (
<DropdownMenuRadioItem key={c} value={c}>
- <ChoiceIcon /> {RESIDENCY_LABEL[c]}
+ <ChoiceIcon /> {residencyLabel(c)}
</DropdownMenuRadioItem>
);
})}
diff --git a/site/src/cut/components/NoteBodyEditor.tsx b/site/src/cut/components/NoteBodyEditor.tsx
index cadb9cbc..81716cc3 100644
--- a/site/src/cut/components/NoteBodyEditor.tsx
+++ b/site/src/cut/components/NoteBodyEditor.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
+import { useTranslations } from "next-intl";
import { BubbleMenu } from "@tiptap/react/menus";
import StarterKit from "@tiptap/starter-kit";
import { TaskItem, TaskList } from "@tiptap/extension-list";
@@ -14,19 +15,20 @@ import { blocksOf, docOf, dropBlankLines, splitSelection, TextColor } from "@/cu
import { useLocalPref } from "@/cut/lib/uiState";
import { cn } from "@/lib/utils";
-/** What a selection can turn its lines into, the way the toolbar names it. */
-const TURN_INTO: { id: string; label: string; active: (e: Editor) => boolean; run: (e: Editor) => void }[] = [
- { id: "text", label: "Text", active: (e) => e.isActive("paragraph") && !e.isActive("bulletList") && !e.isActive("orderedList") && !e.isActive("taskList") && !e.isActive("blockquote"), run: (e) => toText(e).setParagraph().run() },
+/** What a selection can turn its lines into. The toolbar names each by its id
+ * in the home catalog's turn-into names. */
+type TurnId = "text" | "h1" | "h2" | "h3" | "bullet" | "number" | "todo" | "quote";
+const TURN_INTO: { id: TurnId; active: (e: Editor) => boolean; run: (e: Editor) => void }[] = [
+ { id: "text", active: (e) => e.isActive("paragraph") && !e.isActive("bulletList") && !e.isActive("orderedList") && !e.isActive("taskList") && !e.isActive("blockquote"), run: (e) => toText(e).setParagraph().run() },
...([1, 2, 3] as const).map((level) => ({
- id: `h${level}`,
- label: `Heading ${level}`,
+ id: `h${level}` as const,
active: (e: Editor) => e.isActive("heading", { level }),
run: (e: Editor) => toText(e).setHeading({ level }).run(),
})),
- { id: "bullet", label: "Bulleted list", active: (e) => e.isActive("bulletList"), run: (e) => toList(e).toggleBulletList().run() },
- { id: "number", label: "Numbered list", active: (e) => e.isActive("orderedList"), run: (e) => toList(e).toggleOrderedList().run() },
- { id: "todo", label: "To-do list", active: (e) => e.isActive("taskList"), run: (e) => toList(e).toggleTaskList().run() },
- { id: "quote", label: "Quote", active: (e) => e.isActive("blockquote"), run: (e) => toText(e).setParagraph().toggleBlockquote().run() },
+ { id: "bullet", active: (e) => e.isActive("bulletList"), run: (e) => toList(e).toggleBulletList().run() },
+ { id: "number", active: (e) => e.isActive("orderedList"), run: (e) => toList(e).toggleOrderedList().run() },
+ { id: "todo", active: (e) => e.isActive("taskList"), run: (e) => toList(e).toggleTaskList().run() },
+ { id: "quote", active: (e) => e.isActive("blockquote"), run: (e) => toText(e).setParagraph().toggleBlockquote().run() },
];
/** Lift the selected lines out of any list or quote first, so every turn
* starts from plain lines. */
@@ -98,6 +100,7 @@ export default function NoteBodyEditor({
onChange: (body: string) => void;
onEditor?: (editor: Editor | null) => void;
}) {
+ const t = useTranslations("home.noteEditor");
const [initial] = useState(() => docOf(parseNoteBody(body)));
// The handlers as of the last render; the editor holds the ones it was
// made with.
@@ -120,7 +123,7 @@ export default function NoteBodyEditor({
TaskList,
TaskItem.configure({ nested: true }),
TextColor,
- Placeholder.configure({ placeholder: "Write your note…" }),
+ Placeholder.configure({ placeholder: t("placeholder") }),
],
content: initial,
editorProps: { attributes: { class: "outline-none min-h-[50vh]" }, handlePaste: pasteMarkdown },
@@ -155,6 +158,7 @@ export default function NoteBodyEditor({
/** The selection's toolbar. Every press keeps the editor's focus, so the
* selection it acts on stays put. */
function Toolbar({ editor }: { editor: Editor }) {
+ const t = useTranslations("home.noteEditor");
const [panel, setPanel] = useState<"turn" | "list" | "color" | null>(null);
// The style the list button makes: the last one picked from its menu, kept
// across notes and reloads.
@@ -164,7 +168,7 @@ function Toolbar({ editor }: { editor: Editor }) {
const state = useEditorState({
editor,
selector: ({ editor: e }) => ({
- turn: TURN_INTO.find((t) => t.active(e))?.id ?? "text",
+ turn: TURN_INTO.find((x) => x.active(e))?.id ?? "text",
bold: e.isActive("bold"),
italic: e.isActive("italic"),
underline: e.isActive("underline"),
@@ -174,8 +178,8 @@ function Toolbar({ editor }: { editor: Editor }) {
});
const keep = (e: React.MouseEvent) => e.preventDefault();
const color = NOTE_TEXT_COLORS.find((c) => c.id === state.color);
- const turn = (id: string) => TURN_INTO.find((t) => t.id === id)!.run(editor);
- const label = (id: string) => TURN_INTO.find((t) => t.id === id)!.label;
+ const turn = (id: TurnId) => TURN_INTO.find((x) => x.id === id)!.run(editor);
+ const label = (id: TurnId) => t(`turnInto.${id}`);
const activeList = LIST_STYLES.find((l) => l.id === state.turn);
const list = LIST_STYLES.find((l) => l.id === listStyle)!;
@@ -191,23 +195,23 @@ function Toolbar({ editor }: { editor: Editor }) {
onToggle={() => setPanel(panel === "turn" ? null : "turn")}
trigger={<>{label(state.turn)}<ChevronDown className="size-3.5 opacity-50" /></>}
>
- {TURN_INTO.map((t) => (
- <MenuItem key={t.id} checked={t.id === state.turn} onPick={() => { t.run(editor); setPanel(null); }}>
- {t.label}
+ {TURN_INTO.map((x) => (
+ <MenuItem key={x.id} checked={x.id === state.turn} onPick={() => { x.run(editor); setPanel(null); }}>
+ {label(x.id)}
</MenuItem>
))}
</Menu>
<Divider />
- <Toggle label="Bold" on={state.bold} onPress={() => editor.chain().focus().toggleBold().run()}><Bold className="size-4" /></Toggle>
- <Toggle label="Italic" on={state.italic} onPress={() => editor.chain().focus().toggleItalic().run()}><Italic className="size-4" /></Toggle>
- <Toggle label="Underline" on={state.underline} onPress={() => editor.chain().focus().toggleUnderline().run()}><Underline className="size-4" /></Toggle>
- <Toggle label="Strikethrough" on={state.strike} onPress={() => editor.chain().focus().toggleStrike().run()}><Strikethrough className="size-4" /></Toggle>
+ <Toggle label={t("bold")} on={state.bold} onPress={() => editor.chain().focus().toggleBold().run()}><Bold className="size-4" /></Toggle>
+ <Toggle label={t("italic")} on={state.italic} onPress={() => editor.chain().focus().toggleItalic().run()}><Italic className="size-4" /></Toggle>
+ <Toggle label={t("underline")} on={state.underline} onPress={() => editor.chain().focus().toggleUnderline().run()}><Underline className="size-4" /></Toggle>
+ <Toggle label={t("strikethrough")} on={state.strike} onPress={() => editor.chain().focus().toggleStrike().run()}><Strikethrough className="size-4" /></Toggle>
<Divider />
<Toggle label={label(list.id)} on={state.turn === list.id} onPress={() => turn(state.turn === list.id ? "text" : list.id)}><list.icon className="size-4" /></Toggle>
<Menu
open={panel === "list"}
onToggle={() => setPanel(panel === "list" ? null : "list")}
- label="List style"
+ label={t("listStyle")}
trigger={<ChevronDown className="size-3.5 opacity-50" />}
fit="icon"
>
@@ -221,15 +225,15 @@ function Toolbar({ editor }: { editor: Editor }) {
<Menu
open={panel === "color"}
onToggle={() => setPanel(panel === "color" ? null : "color")}
- label="Text color"
+ label={t("textColor")}
trigger={<><span className="font-semibold" style={{ color: color?.paper }}>A</span><ChevronDown className="size-3.5 opacity-50" /></>}
>
<MenuItem checked={!color} onPick={() => { editor.chain().focus().unsetMark("textColor").run(); setPanel(null); }}>
- <span className="w-4 text-center font-semibold">A</span> Default
+ <span className="w-4 text-center font-semibold">A</span> {t("defaultColor")}
</MenuItem>
{NOTE_TEXT_COLORS.map((c) => (
<MenuItem key={c.id} checked={c.id === state.color} onPick={() => { editor.chain().focus().setMark("textColor", { color: c.id }).run(); setPanel(null); }}>
- <span className="w-4 text-center font-semibold" style={{ color: c.paper }}>A</span> {c.name}
+ <span className="w-4 text-center font-semibold" style={{ color: c.paper }}>A</span> {t(`textColors.${c.id}`)}
</MenuItem>
))}
</Menu>
diff --git a/site/src/cut/components/NoteComposer.tsx b/site/src/cut/components/NoteComposer.tsx
index 217cd24d..d53512ce 100644
--- a/site/src/cut/components/NoteComposer.tsx
+++ b/site/src/cut/components/NoteComposer.tsx
@@ -5,6 +5,7 @@ import type React from "react";
import type { NoteLocation } from "@/cut/lib/noteReference";
import { createPortal } from "react-dom";
import dynamic from "next/dynamic";
+import { useTranslations } from "next-intl";
import type { Editor } from "@tiptap/react";
import { ArrowLeft, Check, ChevronDown, Pencil, Plus, Tag, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -26,6 +27,10 @@ const NOTE_INK = "#201a0d";
// bundle.
const NoteBodyEditor = dynamic(() => import("./NoteBodyEditor"), { ssr: false });
+/** A paper color's name as a key in the home catalog's color names. */
+const colorKey = (name: (typeof NOTE_COLORS)[number]["name"]) =>
+ `colors.${name.toLowerCase() as Lowercase<typeof name>}` as const;
+
export interface NoteDraft {
libraryLocation?: NoteLocation | null;
id: string;
@@ -140,6 +145,7 @@ export function NoteComposer({
onRenameLabel: (id: string, name: string) => void;
onDeleteLabel: (id: string) => void;
}) {
+ const t = useTranslations("home.composer");
const paper = noteColor(draft.colorIndex);
const titleRef = useAutoGrow(draft.title);
const body = useRef<Editor | null>(null);
@@ -198,7 +204,7 @@ export function NoteComposer({
<div
role="dialog"
aria-modal="true"
- aria-label={draft.title.trim() || "Untitled note"}
+ aria-label={draft.title.trim() || t("untitledNote")}
{...KEEP_EVENTS}
// `light` keeps the paper, its controls and its menus light in dark mode.
className="light fixed inset-0 z-50 flex flex-col font-system antialiased"
@@ -223,7 +229,7 @@ export function NoteComposer({
render={
<Button
variant="ghost"
- aria-label="Note color"
+ aria-label={t("noteColor")}
className="hover:bg-black/5 hover:text-current"
style={{ color: NOTE_INK }}
/>
@@ -233,7 +239,7 @@ export function NoteComposer({
className="size-3.5 rounded-full border border-black/10"
style={{ backgroundColor: paper.accent }}
/>
- {paper.name}
+ {t(colorKey(paper.name))}
<ChevronDown className="size-3.5 opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="light w-40">
@@ -247,7 +253,7 @@ export function NoteComposer({
className="size-3.5 rounded-full border border-black/10"
style={{ backgroundColor: c.accent }}
/>
- <span className="flex-1">{c.name}</span>
+ <span className="flex-1">{t(colorKey(c.name))}</span>
{i === draft.colorIndex && <Check className="size-4 opacity-70" />}
</DropdownMenuItem>
))}
@@ -255,11 +261,11 @@ export function NoteComposer({
</DropdownMenu>
<Button
variant="ghost"
- aria-label="Delete note"
+ aria-label={t("deleteNote")}
className="text-destructive hover:bg-black/5 hover:text-destructive"
onClick={onDelete}
>
- <Trash2 data-icon="inline-start" /> Delete
+ <Trash2 data-icon="inline-start" /> {t("delete")}
</Button>
</header>
@@ -273,7 +279,7 @@ export function NoteComposer({
autoFocus
rows={1}
value={draft.title}
- placeholder="Untitled"
+ placeholder={t("titlePlaceholder")}
className="resize-none overflow-hidden bg-transparent text-4xl leading-tight font-semibold tracking-tight outline-none placeholder:opacity-30"
style={{ color: NOTE_INK }}
onChange={(e) => onChange({ ...draft, title: e.target.value.replace(/\n/g, "") })}
@@ -291,7 +297,7 @@ export function NoteComposer({
<button
key={l.id}
className="group flex cursor-pointer items-center gap-1 rounded-full bg-black/10 px-2.5 py-1 text-xs font-medium hover:bg-black/15"
- aria-label={`Remove label ${l.name}`}
+ aria-label={t("removeLabel", { name: l.name })}
onClick={() => toggleLabel(l.id)}
>
{l.name}
@@ -303,12 +309,12 @@ export function NoteComposer({
render={
<button
className="flex cursor-pointer items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium opacity-50 hover:bg-black/10 hover:opacity-80"
- aria-label="Add label"
+ aria-label={t("addLabel")}
/>
}
>
{worn.length === 0 ? <Tag className="size-3.5" /> : <Plus className="size-3.5" />}
- {worn.length === 0 ? "Add label" : "Label"}
+ {worn.length === 0 ? t("addLabel") : t("label")}
</PopoverTrigger>
<PopoverContent align="start" className="light w-64">
<LabelPicker
@@ -354,6 +360,7 @@ function LabelPicker({
onRename: (id: string, name: string) => void;
onDelete: (id: string) => void;
}) {
+ const t = useTranslations("home.labelPicker");
const [query, setQuery] = useState("");
const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(null);
const typed = query.trim();
@@ -386,7 +393,7 @@ function LabelPicker({
<input
autoFocus
value={query}
- placeholder={labels.length === 0 ? "New label…" : "Find or create…"}
+ placeholder={labels.length === 0 ? t("newLabel") : t("findOrCreate")}
className="border-b border-foreground/10 px-3 py-2.5 text-sm outline-none placeholder:text-muted-foreground"
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
@@ -442,14 +449,14 @@ function LabelPicker({
</button>
<button
className="hidden shrink-0 cursor-pointer rounded p-1 text-muted-foreground group-hover:block hover:text-foreground"
- aria-label={`Rename label ${l.name}`}
+ aria-label={t("renameLabel", { name: l.name })}
onClick={() => setRenaming({ id: l.id, name: l.name })}
>
<Pencil className="size-3.5" />
</button>
<button
className="hidden shrink-0 cursor-pointer rounded p-1 pr-2 text-muted-foreground group-hover:block hover:text-destructive"
- aria-label={`Delete label ${l.name}`}
+ aria-label={t("deleteLabel", { name: l.name })}
onClick={() => onDelete(l.id)}
>
<Trash2 className="size-3.5" />
@@ -463,17 +470,17 @@ function LabelPicker({
onClick={commitTyped}
>
<Plus className="size-4 shrink-0 opacity-70" />
- <span className="min-w-0 flex-1 truncate">Create “{typed}”</span>
+ <span className="min-w-0 flex-1 truncate">{t("create", { name: typed })}</span>
</button>
)}
{full && (
<div className="px-2.5 py-2 text-sm text-muted-foreground">
- A note holds {NOTE_LABELS_MAX} labels. Take one off to add another.
+ {t("full", { max: NOTE_LABELS_MAX })}
</div>
)}
{labels.length === 0 && !typed && (
<div className="px-2.5 py-2 text-sm text-muted-foreground">
- Type a name to make your first label.
+ {t("firstLabel")}
</div>
)}
</div>
diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsx
index dc30d0e7..59600202 100644
--- a/site/src/cut/components/NotesView.tsx
+++ b/site/src/cut/components/NotesView.tsx
@@ -3,6 +3,7 @@
import { useEffect, useImperativeHandle, useRef, useState, type Ref } from "react";
import { useSearchParams } from "next/navigation";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
import { FolderPlus, Loader2, Plus, StickyNote, Trash2 } from "lucide-react";
import { useDeleteKey } from "@/cut/hooks/useDeleteKey";
import { useTabTitle } from "@/cut/hooks/useTabTitle";
@@ -35,7 +36,7 @@ import { additiveClick } from "@/cut/lib/hostKeys";
import { PICKED_RING } from "@/cut/lib/assetPick";
import { FolderCrumb, FolderShelf, Marquee, useTilePicks } from "./desktopFolders";
import { CardActionsMenu } from "./CardActionsMenu";
-import { DeleteConfirm, SelectionMenu, foldersGoNote, pickLabel, useSelectionMenu } from "./selectionMenu";
+import { DeleteConfirm, SelectionMenu, usePickWords, useSelectionMenu } from "./selectionMenu";
import { LIBRARY_SQUARE } from "./LibraryCard";
import { NoteComposer, noteChanged, type NoteDraft } from "./NoteComposer";
import { NoteBodyPreview } from "./NoteBodyPreview";
@@ -164,6 +165,8 @@ type Props = {
ref?: Ref<NotesViewHandle>;
};
export function NotesView({ library, ref }: Props = {}) {
+ const t = useTranslations("home");
+ const { pickLabel, foldersGoNote } = usePickWords();
const client = useQueryClient();
const base = useCutBase();
const notes = useNotes();
@@ -250,12 +253,12 @@ export function NotesView({ library, ref }: Props = {}) {
// Inside the library, the library names the folder.
useTabTitle(
draft
- ? draft.title.trim() || "Untitled"
+ ? draft.title.trim() || t("notes.untitled")
: library
? null
: openFolder
? trail.at(-1)?.name
- : "Notes",
+ : t("tabs.notes"),
);
const reload = () => void client.invalidateQueries({ queryKey: notesKey });
@@ -616,7 +619,7 @@ export function NotesView({ library, ref }: Props = {}) {
useDeleteKey(pageRef, pick.length > 0 ? () => setDeletingNotes(pick.map((n) => n.id)) : null);
// What the confirm names: each note by its title.
const deletingNames = (deletingNotes ?? []).map((id) => ({
- name: list.find((n) => n.id === id)?.title.trim() || "Untitled note",
+ name: list.find((n) => n.id === id)?.title.trim() || t("notes.untitledNote"),
}));
return (
@@ -625,14 +628,14 @@ export function NotesView({ library, ref }: Props = {}) {
className={library ? (shown.length > 0 ? "mb-6" : undefined) : "mx-auto w-full max-w-6xl px-10 py-9"}
onContextMenu={ctx.onContextMenu}
>
- {failedDraft && <p role="alert" className="py-3 text-sm text-destructive">Could not save the note. <button className="underline" onClick={() => { edit(failedDraft); openAt(failedDraft.id); setFailedDraft(null); }}>Reopen and retry</button></p>}
+ {failedDraft && <p role="alert" className="py-3 text-sm text-destructive">{t("notes.saveFailed")} <button className="underline" onClick={() => { edit(failedDraft); openAt(failedDraft.id); setFailedDraft(null); }}>{t("notes.reopen")}</button></p>}
{/* One note at a time, over the whole window. The list stays mounted
behind it, so closing comes back to the same scroll position. */}
{draft && (
<NoteComposer
key={draft.id}
draft={draft}
- back={library?.name ?? draftFolderName ?? "All notes"}
+ back={library?.name ?? draftFolderName ?? t("notes.allNotes")}
from={pageRef}
labels={labels}
onChange={change}
@@ -645,10 +648,10 @@ export function NotesView({ library, ref }: Props = {}) {
)}
{!library && <div className="mb-5 flex items-center justify-between gap-4">
{openFolder === null ? (
- <h1 className="text-lg font-semibold tracking-tight">Notes</h1>
+ <h1 className="text-lg font-semibold tracking-tight">{t("tabs.notes")}</h1>
) : (
<FolderCrumb
- root="Notes"
+ root={t("tabs.notes")}
trail={trail}
onRename={renameFolder}
mime={NOTES_MOVE_MIME}
@@ -660,10 +663,10 @@ export function NotesView({ library, ref }: Props = {}) {
)}
<div className="flex items-center gap-2">
<Button variant="outline" onClick={() => setFolderCreating(true)}>
- <FolderPlus data-icon="inline-start" /> New folder
+ <FolderPlus data-icon="inline-start" /> {t("notes.newFolder")}
</Button>
<Button onClick={openNew}>
- <Plus data-icon="inline-start" /> New note
+ <Plus data-icon="inline-start" /> {t("notes.newNote")}
</Button>
</div>
</div>}
@@ -719,7 +722,7 @@ export function NotesView({ library, ref }: Props = {}) {
/>
) : null}
- {notes.isError && <p role="alert" className="py-3 text-sm text-destructive">Could not load notes. <button onClick={reload} className="underline">Retry</button></p>}
+ {notes.isError && <p role="alert" className="py-3 text-sm text-destructive">{t("notes.loadFailed")} <button onClick={reload} className="underline">{t("notes.retry")}</button></p>}
{library && shown.length === 0 ? null : !notes.data && notes.isPending ? (
<div className="grid place-items-center py-24 text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
@@ -731,10 +734,9 @@ export function NotesView({ library, ref }: Props = {}) {
>
<div className="flex flex-col items-center gap-3 text-center">
<StickyNote className="size-8 text-muted-foreground" />
- <div className="text-base font-medium">No notes yet.</div>
+ <div className="text-base font-medium">{t("notes.emptyTitle")}</div>
<p className="text-sm text-muted-foreground">
- Notes sync with the Donkey Cut iOS app — a script written here is ready on the
- phone&apos;s teleprompter.
+ {t("notes.emptyHint")}
</p>
</div>
</button>
@@ -817,13 +819,13 @@ export function NotesView({ library, ref }: Props = {}) {
)}
<SelectionMenu menu={ctxSet.length > 0 ? ctx.menu : null} onClose={ctx.close}>
<DropdownMenuItem variant="destructive" onClick={() => setDeletingNotes(ctxSet.map((n) => n.id))}>
- <Trash2 /> Delete
+ <Trash2 /> {t("notes.delete")}
</DropdownMenuItem>
</SelectionMenu>
<DeleteConfirm
open={deletingNotes !== null}
- title={`Delete ${pickLabel([], deletingNames, ["note", "notes"], 0)}?`}
- description={`${deletingNotes?.length === 1 ? "It is" : "They are"} removed from your phone too.`}
+ title={t("notes.deleteTitle", { what: pickLabel([], deletingNames, "note", 0) })}
+ description={t("notes.removedFromPhone", { count: deletingNotes?.length ?? 0 })}
onClose={() => setDeletingNotes(null)}
onConfirm={() => {
const ids = deletingNotes;
@@ -833,8 +835,8 @@ export function NotesView({ library, ref }: Props = {}) {
/>
<DeleteConfirm
open={deletingFolder !== null}
- title={`Delete “${folders.find((f) => f.id === deletingFolder)?.name ?? "folder"}”?`}
- description={`${foldersGoNote(1, deletingFolder ? folderTakes(deletingFolder).held : 0)}It is removed from your phone too.`}
+ title={t("notes.deleteFolderTitle", { name: folders.find((f) => f.id === deletingFolder)?.name ?? t("notes.folderFallback") })}
+ description={`${foldersGoNote(1, deletingFolder ? folderTakes(deletingFolder).held : 0)}${t("notes.removedFromPhone", { count: 1 })}`}
onClose={() => setDeletingFolder(null)}
onConfirm={() => {
const id = deletingFolder;
diff --git a/site/src/cut/components/NumberField.tsx b/site/src/cut/components/NumberField.tsx
index 679f0d7e..4aea1cdf 100644
--- a/site/src/cut/components/NumberField.tsx
+++ b/site/src/cut/components/NumberField.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -51,6 +52,7 @@ export function NumberField({
* value is typed, dragged or picked, which lands on all of them. */
mixed?: boolean;
}) {
+ const t = useTranslations("inspector.controls");
const show = (v: number) => (mixed ? "" : format(v));
const [entry, setEntry] = useState({ value, mixed: !!mixed, draft: show(value) });
const [open, setOpen] = useState(false);
@@ -83,7 +85,7 @@ export function NumberField({
{icon && (
<span
aria-hidden
- title="Drag to adjust"
+ title={t("dragToAdjust")}
className="grid shrink-0 cursor-ew-resize touch-none place-items-center text-muted-foreground [&_svg]:size-3.5"
onPointerDown={(e) => {
if (e.button !== 0) return;
@@ -117,7 +119,7 @@ export function NumberField({
<input
aria-label={label}
value={entry.draft}
- placeholder={mixed ? "Mixed" : undefined}
+ placeholder={mixed ? t("mixed") : undefined}
inputMode="decimal"
spellCheck={false}
className="w-full min-w-0 bg-transparent font-mono text-[11.5px] tabular-nums outline-none"
@@ -140,7 +142,7 @@ export function NumberField({
{presets && presets.length > 0 && (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
- aria-label={`${label} presets`}
+ aria-label={t("presets", { label })}
className="grid size-6 shrink-0 place-items-center rounded-[5px] text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary/60"
>
<ChevronDown className="size-3.5" />
diff --git a/site/src/cut/components/OfferDialog.tsx b/site/src/cut/components/OfferDialog.tsx
index 26604248..8ce99e58 100644
--- a/site/src/cut/components/OfferDialog.tsx
+++ b/site/src/cut/components/OfferDialog.tsx
@@ -6,10 +6,10 @@
// offer looks the same from anywhere. Every slot keeps its height whether
// or not it has words, so the card stands still as the offer is taken up.
import Image from "next/image";
+import { useFormatter, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
-import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
+import { useCutPro } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
-import { formatCreditExpiry } from "@/lib/credits/top-up";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
// One picture per kind of offer: a gift for credit that comes with Pro, coins
@@ -61,54 +61,71 @@ function useBannerReady(banner: OfferBanner | null): boolean {
return banner === null || loaded === banner;
}
-/** A day as the card names it: "September 30". */
-export function offerDay(iso: string): string {
- return new Date(iso).toLocaleDateString("en-US", { day: "numeric", month: "long" });
-}
-
/** An offer's words: the message, and the terms line under it. */
export type OfferCopy = { body: string; terms: string | null };
-/** How long the credit lasts once it lands, as the card says it; null when
- * it keeps forever. */
-export function creditValidity(offer: { expiresAt: string | null; lifetimeDays: number | null }): string | null {
- if (offer.expiresAt) return `Extra credits are valid through ${offerDay(offer.expiresAt)}.`;
- if (offer.lifetimeDays !== null) return `Extra credits are valid for ${offer.lifetimeDays} days.`;
- return null;
-}
+/** The offer card's words in the page's language: how long landed credit
+ * lasts, the claim's message, and the Pro offer's. */
+export function useOfferCopy() {
+ const t = useTranslations("billing");
+ const format = useFormatter();
+ const pro = useCutPro();
+
+ // How long the credit lasts once it lands; null when it keeps forever.
+ const creditValidity = (offer: { expiresAt: string | null; lifetimeDays: number | null }): string | null => {
+ if (offer.expiresAt) {
+ const date = format.dateTime(new Date(offer.expiresAt), { day: "numeric", month: "long" });
+ return t("offer.validThrough", { date });
+ }
+ if (offer.lifetimeDays !== null) {
+ return t("offer.validFor", { days: offer.lifetimeDays });
+ }
+ return null;
+ };
-/** The claim's words: the credit that is waiting and the last day to take it,
- * then how long it lasts once taken. */
-export function claimOfferCopy(offer: { credits: string; closesAt: string | null; lifetimeDays: number | null }): OfferCopy {
- const by = offer.closesAt ? ` Claim them by ${formatCreditExpiry(new Date(offer.closesAt))}.` : "";
- return {
- body: `You have ${offer.credits} to claim.${by}`,
- terms: offer.lifetimeDays !== null ? `Once claimed, they’re valid for ${offer.lifetimeDays} days.` : null,
+ // The credit that is waiting and the last day to take it, then how long it
+ // lasts once taken.
+ const claimOfferCopy = (offer: {
+ credits: string;
+ closesAt: string | null;
+ lifetimeDays: number | null;
+ }): OfferCopy => {
+ const body = offer.closesAt
+ ? t("offer.claimBodyBy", {
+ credits: offer.credits,
+ date: format.dateTime(new Date(offer.closesAt), { day: "numeric", month: "long", year: "numeric" }),
+ })
+ : t("offer.claimBody", { credits: offer.credits });
+ const terms = offer.lifetimeDays !== null ? t("offer.claimTerms", { days: offer.lifetimeDays }) : null;
+ return { body, terms };
};
-}
-/** The Pro offer's words. The deadline is the countdown's, so the message
- * leaves it out. */
-export function subscribeOfferCopy(offer: {
- credits: string;
- expiresAt: string | null;
- lifetimeDays: number | null;
-}): OfferCopy {
- return {
- body: `Subscribe to Pro for ${CUT_PRO.price} and get an extra ${offer.credits}.`,
- terms: creditValidity(offer),
+ // The Pro offer. The deadline is the countdown's, so the message leaves it
+ // out.
+ const subscribeOfferCopy = (offer: {
+ credits: string;
+ expiresAt: string | null;
+ lifetimeDays: number | null;
+ }): OfferCopy => {
+ return {
+ body: t("offer.subscribeBody", { credits: offer.credits, price: pro.price }),
+ terms: creditValidity(offer),
+ };
};
+
+ return { claimOfferCopy, creditValidity, subscribeOfferCopy };
}
-/** What is left until a moment, as the countdown reads it: hours, minutes
- * and seconds, the hours running past a day. */
-export function countdownLabel(closesAt: string, now: number): string {
+/** What is left until a moment, as the countdown reads it: hours, then
+ * two-digit minutes and seconds, the hours running past a day. */
+export function countdownParts(closesAt: string, now: number): { hours: number; minutes: string; seconds: string } {
const left = Math.max(0, Math.floor((Date.parse(closesAt) - now) / 1000));
- const hours = Math.floor(left / 3600);
- const minutes = Math.floor((left % 3600) / 60);
- const seconds = left % 60;
const two = (n: number) => String(n).padStart(2, "0");
- return `${hours}h ${two(minutes)}m ${two(seconds)}s`;
+ return {
+ hours: Math.floor(left / 3600),
+ minutes: two(Math.floor((left % 3600) / 60)),
+ seconds: two(left % 60),
+ };
}
/** The clock a countdown reads; one tick a second while it is on screen. */
@@ -122,10 +139,11 @@ export function useNow(): number {
}
function Countdown({ closesAt }: { closesAt: string }) {
+ const t = useTranslations("billing.offer");
const now = useNow();
return (
<span className="absolute top-3 left-3 rounded-md bg-foreground/85 px-3 py-1.5 text-sm font-medium tabular-nums text-background">
- Offer expires in {countdownLabel(closesAt, now)}
+ {t("expiresIn", countdownParts(closesAt, now))}
</span>
);
}
diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsx
index 49858f27..24b096de 100644
--- a/site/src/cut/components/OverlayLayer.tsx
+++ b/site/src/cut/components/OverlayLayer.tsx
@@ -1,5 +1,7 @@
"use client";
+import { useTranslations } from "next-intl";
+import { creatorNames } from "@/cut/lib/defaultNames";
import { guideSnapLines } from "@/cut/lib/guides";
import { createContext, Fragment, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties } from "react";
import { createPortal } from "react-dom";
@@ -993,7 +995,9 @@ function OverlayItem({
if (text !== o.text) {
const s = useEditor.getState();
s.pushHistory();
- s.updateOverlayTransient(o.id, { text: text || "Your text" });
+ // An emptied title falls back to the placeholder in the page's language,
+ // read here in the handler so the per-frame item holds no translator.
+ s.updateOverlayTransient(o.id, { text: text || creatorNames().text });
}
};
@@ -2211,6 +2215,20 @@ export function MaskGizmoCore({
writePoints: (points: MaskPoint[]) => void;
begin: () => void;
}) {
+ const t = useTranslations("editor.maskGizmo");
+ // The grips' names, resolved once per locale: the gizmo redraws with the
+ // playhead, and a redraw takes no lookups.
+ const titles = useMemo(
+ () => ({
+ moveCorner: t("moveCorner"),
+ addCorner: t("addCorner"),
+ feather: t("feather"),
+ round: t("round"),
+ rotate: t("rotate"),
+ resize: t("resize"),
+ }),
+ [t]
+ );
const f = maskFrameAt(m, tLocal);
const pen = m.kind === "pen";
const drawing = pen && !penClosed(m);
@@ -2654,7 +2672,7 @@ export function MaskGizmoCore({
return (
<Fragment key={i}>
<span
- title="Drag to move the corner; double-click to remove it"
+ title={titles.moveCorner}
onPointerDown={(e) => dragCorner(e, points, i)}
onDoubleClick={(e) => {
e.stopPropagation();
@@ -2664,7 +2682,7 @@ export function MaskGizmoCore({
style={{ left: p.x * w, top: p.y * h, transform: "translate(-50%, -50%)", ...grip }}
/>
<span
- title="Drag to add a corner here"
+ title={titles.addCorner}
onPointerDown={(e) => addCorner(e, points, i)}
className="pointer-events-auto absolute block size-[7px] cursor-copy rounded-full border-[1.5px] bg-white/70"
style={{
@@ -2692,7 +2710,7 @@ export function MaskGizmoCore({
{/* The grip wears the softness it controls: a ring that blurs
outward, in the mask's amber like every other mask grip. */}
<span
- title="Drag to feather the edge"
+ title={titles.feather}
onPointerDown={featherMask}
className="pointer-events-auto block size-[13px] cursor-ns-resize rounded-full border-[2.5px] bg-white"
style={{
@@ -2719,7 +2737,7 @@ export function MaskGizmoCore({
</span>
)}
<span
- title="Drag to round the corners"
+ title={titles.round}
onPointerDown={roundMask}
className="pointer-events-auto grid size-[16px] cursor-nwse-resize place-items-center rounded-full border-[2.5px] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]"
style={{ borderColor: "#ff9f0a" }}
@@ -2774,8 +2792,8 @@ export function MaskGizmoCore({
rotation={rotation + f.rotation}
angle={spin}
rotateCursor={rotateCursor(rotation + f.rotation)}
- rotateTitle="Drag to rotate the mask"
- resizeTitle="Drag to resize the mask"
+ rotateTitle={titles.rotate}
+ resizeTitle={titles.resize}
frame={{
left: `calc(50% + ${cx}px)`,
top: `calc(50% + ${cy}px)`,
diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsx
index a5f4f274..96472468 100644
--- a/site/src/cut/components/PlatformPreview.tsx
+++ b/site/src/cut/components/PlatformPreview.tsx
@@ -1,6 +1,7 @@
"use client";
import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
@@ -35,8 +36,8 @@ export interface ExportItem {
type Platform = "original" | "tiktok" | "instagram" | "youtube";
-const PLATFORMS: { id: Platform; label: string }[] = [
- { id: "original", label: "Original" },
+const PLATFORMS: { id: Platform; label?: string }[] = [
+ { id: "original" },
{ id: "tiktok", label: "TikTok" },
{ id: "instagram", label: "Instagram" },
{ id: "youtube", label: "YouTube" },
@@ -57,6 +58,7 @@ export function PlatformPreviewDialog({
item: ExportItem;
onClose: () => void;
}) {
+ const t = useTranslations("editor.platformPreview");
const publish = useEditor((s) => s.publish);
const aspect = useEditor((s) => s.aspect);
const [platform, setPlatform] = useState<Platform>("original");
@@ -89,10 +91,10 @@ export function PlatformPreviewDialog({
};
const url = exportFileUrl(projectId, item);
- const handle = publish.handle.trim().replace(/^@+/, "") || "you";
+ const handle = publish.handle.trim().replace(/^@+/, "") || t("defaultHandle");
const caption = publish.caption.trim();
const tagsLine = normalizeTags(publish.tags);
- const sound = publish.soundTitle.trim() || `original sound - ${handle}`;
+ const sound = publish.soundTitle.trim() || t("originalSound", { handle });
const original = platform === "original";
return (
@@ -106,7 +108,7 @@ export function PlatformPreviewDialog({
<div className="relative flex max-h-full flex-col items-center gap-4 overflow-hidden rounded-2xl bg-card px-10 py-5 shadow-2xl">
<button
className="absolute top-3 right-3 grid size-7 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- aria-label="Close preview"
+ aria-label={t("close")}
onClick={onClose}
>
<X className="size-4" />
@@ -125,7 +127,7 @@ export function PlatformPreviewDialog({
aria-pressed={platform === p.id}
onClick={() => setPlatform(p.id)}
>
- {p.label}
+ {p.label ?? t("original")}
</button>
))}
</div>
@@ -179,7 +181,7 @@ export function PlatformPreviewDialog({
<button
className="absolute top-3.5 left-3.5 z-20 grid size-7 place-items-center rounded-full bg-black/40 text-white"
- aria-label={muted ? "Unmute" : "Mute"}
+ aria-label={muted ? t("unmute") : t("mute")}
onClick={() => setMuted((m) => !m)}
>
{muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}
@@ -191,11 +193,11 @@ export function PlatformPreviewDialog({
time={time}
duration={duration}
onToggle={togglePlay}
- onSeek={(t) => {
+ onSeek={(at) => {
const v = videoRef.current;
if (!v) return;
- v.currentTime = t;
- setTime(t);
+ v.currentTime = at;
+ setTime(at);
}}
/>
)}
@@ -251,6 +253,7 @@ function RailItem({
}
function TikTokChrome({ handle, caption, tags, sound }: ChromeProps) {
+ const t = useTranslations("editor.platformPreview");
return (
<div className="preview-tiktok pointer-events-none absolute inset-0 z-10">
<div
@@ -259,9 +262,9 @@ function TikTokChrome({ handle, caption, tags, sound }: ChromeProps) {
shadow
)}
>
- <span className="opacity-75">Following</span>
+ <span className="opacity-75">{t("following")}</span>
<span className="relative font-semibold">
- For You
+ {t("forYou")}
<span className="absolute -bottom-1.5 left-1/2 h-0.5 w-5 -translate-x-1/2 rounded bg-white" />
</span>
<Search className="absolute right-4 size-4.5 text-white" />
@@ -280,7 +283,7 @@ function TikTokChrome({ handle, caption, tags, sound }: ChromeProps) {
label="1,842"
/>
<RailItem icon={<Bookmark className="size-6.5 fill-white text-white" />} label="12.3K" />
- <RailItem icon={<Share2 className="size-6.5 fill-white text-white" />} label="Share" />
+ <RailItem icon={<Share2 className="size-6.5 fill-white text-white" />} label={t("share")} />
<span className="mt-0.5 grid size-9 animate-[spin_5s_linear_infinite] place-items-center rounded-full bg-neutral-900 ring-4 ring-neutral-800">
<Music2 className="size-3.5 text-white" />
</span>
@@ -307,6 +310,7 @@ function TikTokChrome({ handle, caption, tags, sound }: ChromeProps) {
}
function ReelsChrome({ handle, caption, tags, sound }: ChromeProps) {
+ const t = useTranslations("editor.platformPreview");
return (
<div className="preview-instagram pointer-events-none absolute inset-0 z-10">
<div className="absolute top-4 inset-x-0 flex items-center justify-between px-4">
@@ -332,7 +336,7 @@ function ReelsChrome({ handle, caption, tags, sound }: ChromeProps) {
{handle}
</span>
<span className="rounded-md border border-white/80 px-1.5 py-0.5 text-[11px] font-medium text-white">
- Follow
+ {t("follow")}
</span>
</div>
{(caption || tags) && (
@@ -340,7 +344,7 @@ function ReelsChrome({ handle, caption, tags, sound }: ChromeProps) {
{caption}
{caption && tags ? " " : ""}
{tags}
- <span className="text-white/60"> … more</span>
+ <span className="text-white/60"> {t("more")}</span>
</p>
)}
<div className="flex max-w-full items-center gap-1.5 self-start rounded-full border border-white/25 bg-black/35 px-2.5 py-1 backdrop-blur-sm">
@@ -355,6 +359,7 @@ function ReelsChrome({ handle, caption, tags, sound }: ChromeProps) {
}
function ShortsChrome({ handle, caption, tags, sound }: ChromeProps) {
+ const t = useTranslations("editor.platformPreview");
return (
<div className="preview-youtube pointer-events-none absolute inset-0 z-10">
<div className="absolute top-4 inset-x-0 flex items-center justify-between px-4">
@@ -367,10 +372,10 @@ function ShortsChrome({ handle, caption, tags, sound }: ChromeProps) {
</div>
<div className="absolute right-2.5 bottom-14 flex flex-col items-center gap-4">
- <RailItem icon={<ThumbsUp className="size-6 text-white" />} label="Like" />
- <RailItem icon={<ThumbsDown className="size-6 text-white" />} label="Dislike" />
+ <RailItem icon={<ThumbsUp className="size-6 text-white" />} label={t("like")} />
+ <RailItem icon={<ThumbsDown className="size-6 text-white" />} label={t("dislike")} />
<RailItem icon={<MessageCircle className="size-6 -scale-x-100 text-white" />} label="1.2K" />
- <RailItem icon={<Share2 className="size-6 text-white" />} label="Share" />
+ <RailItem icon={<Share2 className="size-6 text-white" />} label={t("share")} />
<span className="grid size-9 animate-[spin_6s_linear_infinite] place-items-center rounded-lg bg-neutral-900 ring-2 ring-white/20">
<Music2 className="size-3.5 text-white" />
</span>
@@ -383,7 +388,7 @@ function ShortsChrome({ handle, caption, tags, sound }: ChromeProps) {
@{handle}
</span>
<span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-black">
- Subscribe
+ {t("subscribe")}
</span>
</div>
{(caption || tags) && (
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index 75c24f46..9f348371 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type RefObject } from "react";
import { Check, Copy, Loader2, ZoomIn, ZoomOut } from "lucide-react";
+import { useTranslations } from "next-intl";
import { usePlayback } from "@/cut/hooks/usePlayback";
import { startDrag } from "@/cut/lib/drag";
import { isPreviewSelectionModifier, startSelectionDrag, togglePreviewSelection } from "@/cut/components/previewSelectionDrag";
@@ -140,6 +141,7 @@ function pictureInPane(
/** While the Cutout panel's Original toggle is on, the stage says so — the
* cutout looks gone otherwise. Clicking the badge brings the cutout back. */
function OriginalPeekBadge() {
+ const t = useTranslations("editor.preview");
const peeking = useEditor((st) => !!st.removalPeek);
if (!peeking) return null;
return (
@@ -149,7 +151,7 @@ function OriginalPeekBadge() {
className="clip-peek-badge rounded-full bg-black/55 px-3 py-1 text-[11.5px] font-medium text-white shadow-lg transition-colors hover:bg-black/70"
onClick={() => useEditor.setState({ removalPeek: null })}
>
- Showing the original — click to see the cutout
+ {t("showingOriginal")}
</button>
</div>
);
@@ -170,6 +172,7 @@ function BufferingBadge() {
}
export function Preview() {
+ const t = useTranslations("editor.preview");
const canvasRef = useRef<HTMLCanvasElement>(null);
// The extended-range canvas the HDR picture is presented on, over the
// composite canvas; shown only while the stage is in HDR.
@@ -667,7 +670,7 @@ export function Preview() {
</StagePictureFx>
{hdr === "sdr" && (
<span className="pointer-events-none absolute top-2 left-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white">
- Previewing SDR
+ {t("previewingSdr")}
</span>
)}
<BufferingBadge />
@@ -756,12 +759,12 @@ export function Preview() {
<Copy className="size-3.5 text-muted-foreground" />
)}
{copyState === "working"
- ? "Copying frame…"
+ ? t("copyingFrame")
: copyState === "done"
- ? "Copied"
+ ? t("copied")
: copyState === "failed"
- ? "Couldn't copy the frame"
- : "Copy frame"}
+ ? t("copyFrameFailed")
+ : t("copyFrame")}
</DropdownMenuItem>
</DropdownMenuContent>
)}
@@ -793,6 +796,7 @@ function ZoomHud({
onReset: () => void;
onHold: (held: boolean) => void;
}) {
+ const t = useTranslations("editor.preview");
const Icon = zoom < 0.999 ? ZoomOut : ZoomIn;
return (
<div
@@ -821,7 +825,7 @@ function ZoomHud({
</span>
<button
type="button"
- title="Zoom out"
+ title={t("zoomOut")}
onClick={() => onZoom(-1)}
className="grid size-7 place-items-center rounded-full text-foreground hover:bg-accent"
>
@@ -829,7 +833,7 @@ function ZoomHud({
</button>
<button
type="button"
- title="Zoom in"
+ title={t("zoomIn")}
onClick={() => onZoom(1)}
className="grid size-7 place-items-center rounded-full text-foreground hover:bg-accent"
>
@@ -840,12 +844,12 @@ function ZoomHud({
onClick={onReset}
className="ml-1 rounded-full border px-2.5 py-1 text-xs font-medium hover:bg-accent"
>
- Reset
+ {t("reset")}
</button>
</div>
<button
type="button"
- title={`Zoom ${Math.round(zoom * 100)}%`}
+ title={t("zoomLevel", { percent: Math.round(zoom * 100) })}
onClick={onToggle}
className="grid size-9 shrink-0 place-items-center rounded-full border bg-background/95 text-foreground shadow-md backdrop-blur hover:bg-accent"
>
@@ -917,6 +921,10 @@ function ClipSelectionGizmos({ stage }: { stage: Stage }) {
/** `grouped`: one of several selected items — the box still moves the set,
* and the selection frame carries the grips for all of them. */
function ClipTransformGizmo({ stage, selectedClip, grouped }: { stage: Stage; selectedClip: VideoClip; grouped: boolean }) {
+ const t = useTranslations("editor.preview");
+ // The grips' names, resolved once per locale: the gizmo redraws with the
+ // playhead, and a redraw takes no lookups.
+ const titles = useMemo(() => ({ pan: t("panPicture"), zoom: t("zoomPicture") }), [t]);
const assets = useEditor((s) => s.assets);
const skimTime = useSkim();
const layerRef = useRef<HTMLDivElement>(null);
@@ -1266,7 +1274,7 @@ function ClipTransformGizmo({ stage, selectedClip, grouped }: { stage: Stage; se
overflows && "pointer-events-auto cursor-grab active:cursor-grabbing"
)}
style={picBox}
- title={overflows ? "Drag to pan the picture" : undefined}
+ title={overflows ? titles.pan : undefined}
onPointerDown={overflows ? onPanPicture : undefined}
>
{overflows && !grouped && (
@@ -1275,7 +1283,7 @@ function ClipTransformGizmo({ stage, selectedClip, grouped }: { stage: Stage; se
handles={CORNER_HANDLES}
rotation={rotation}
onResize={(_h, e) => onZoom(e)}
- resizeTitle="Drag to zoom the picture"
+ resizeTitle={titles.zoom}
/>
)}
</div>
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 0b7b5378..adb3cfca 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { useLocale, useTranslations } from "next-intl";
import { useRouter, useSearchParams } from "next/navigation";
import {
Cloud,
@@ -44,7 +45,7 @@ import { additiveClick, newTabClick } from "@/cut/lib/hostKeys";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { capturePosterWhenReady, readPoster } from "@/cut/lib/posterCache";
import { apiJson } from "@/cut/lib/api";
-import { quotaErrorMessage } from "@/cut/lib/backend/cloud";
+import { quotaError } from "@/cut/lib/backend/cloud";
import {
useCloudUsage,
useCutMode,
@@ -73,6 +74,7 @@ import { clearProjectThreads } from "@/cut/lib/chatThreads";
import { useGenerate } from "@/cut/lib/generate";
import { useGenScene } from "@/cut/lib/genScene";
import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";
+import { creatorLocale, creatorNames } from "@/cut/lib/defaultNames";
import { dropLocalProjectCopy, localMediaUrl } from "@/cut/lib/mediaSync";
import { copyProjectAcross } from "@/cut/lib/projectCopy";
import { newProjectAllowed } from "@/cut/lib/projectLimit";
@@ -89,6 +91,7 @@ import { setObjectDragImage } from "@/cut/lib/assetDrag";
import { childrenOf, folderTrail, folderWithin, parentOf, subtreeOf } from "@/cut/lib/folderTree";
import { PICKED_RING } from "@/cut/lib/assetPick";
import { projectsHomeView } from "@/cut/lib/projectsHomeView";
+import { errorFromBody } from "@/cut/lib/userError";
import {
FolderCrumb,
FolderMenuItems,
@@ -101,11 +104,11 @@ import {
import {
DeleteConfirm,
SelectionMenu,
- foldersGoNote,
- pickLabel,
+ usePickWords,
useSelectionMenu,
} from "./selectionMenu";
import { formatBytes } from "@/lib/bytes";
+import { useDescribeError } from "@/i18n/describeError";
type View = "gallery" | "list";
const viewListeners = new Set<() => void>();
@@ -150,9 +153,8 @@ const NO_PICK: DeleteSet = { folders: [], projects: [] };
// MouseEvent.button for the middle (wheel) button.
const MIDDLE_BUTTON = 1;
-// What a shelf's refusal says, when it says anything.
-const errorOf = async (res: Response | null) =>
- res ? (await apiJson<object>(res)).error : undefined;
+// A shelf's refusal: its reply body, whose code and words the failure keeps.
+const refusalOf = async (res: Response | null) => (res ? await apiJson<object>(res) : null);
// A dragged selection is carried as a JSON array of project ids, so one drag can
// move a whole marquee-selected collection into a folder.
@@ -164,12 +166,11 @@ const PROJECT_FOLDER_MIME = "application/x-cut-project-folder";
// than repeating the shelf heading it sits under. A local project the Donkey
// app isn't answering for says that instead: it is the reason its card can't
// be renamed or moved.
-const RESIDENCY_HINT: Record<Residency, string> = {
- local: "This is a local project",
- cloud: "This is a cloud project",
- browser: "This is a local project",
-};
-const OFFLINE_HINT = "This is a local project — open the Donkey app to edit it";
+const RESIDENCY_HINT = {
+ local: "badgeLocal",
+ cloud: "badgeCloud",
+ browser: "badgeLocal",
+} as const satisfies Record<Residency, string>;
function ResidencyBadge({
residency,
@@ -180,6 +181,7 @@ function ResidencyBadge({
offline?: boolean;
className?: string;
}) {
+ const t = useTranslations("home.projects");
const Icon = residency === "cloud" ? Cloud : Laptop;
return (
<TooltipProvider>
@@ -187,7 +189,7 @@ function ResidencyBadge({
<TooltipTrigger render={<span />} className={className}>
<Icon className="size-3" />
</TooltipTrigger>
- <TooltipContent>{offline ? OFFLINE_HINT : RESIDENCY_HINT[residency]}</TooltipContent>
+ <TooltipContent>{offline ? t("badgeOffline") : t(RESIDENCY_HINT[residency])}</TooltipContent>
</Tooltip>
</TooltipProvider>
);
@@ -196,6 +198,8 @@ function ResidencyBadge({
/** After a Pro plan ends, an over-cap account has a countdown before the daily
* sweep reclaims its oldest projects. Say so where the projects are. */
function GraceBanner({ enabled }: { enabled: boolean }) {
+ const t = useTranslations("home.projects");
+ const locale = useLocale();
// A deletion deadline moves once a day; one read per visit is plenty.
const usage = useCloudUsage(enabled, { poll: false });
const checkout = useStartCheckout();
@@ -213,9 +217,7 @@ function GraceBanner({ enabled }: { enabled: boolean }) {
return (
<div className="mb-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<span className="text-destructive">
- Your Pro plan ended and you&rsquo;re over the free storage limit. Your oldest cloud projects
- will be deleted {days === 0 ? "today" : `in ${days} day${days === 1 ? "" : "s"}`} unless you
- upgrade or free {formatBytes(grace.overBytes)}.
+ {t("grace", { days, size: formatBytes(grace.overBytes, locale) })}
</span>
<Button
variant="link"
@@ -232,13 +234,17 @@ function GraceBanner({ enabled }: { enabled: boolean }) {
}
}}
>
- Upgrade to Pro
+ {t("upgradeToPro")}
</Button>
</div>
);
}
export function ProjectsHome() {
+ const t = useTranslations("home");
+ const locale = useLocale();
+ const describeError = useDescribeError();
+ const { pickLabel, foldersGoNote } = usePickWords();
const router = useRouter();
const base = useCutBase();
const mode = useCutMode();
@@ -409,7 +415,7 @@ export function ProjectsHome() {
.catch(() => null);
if (!res?.ok) {
void refresh(r);
- throw new Error((await errorOf(res)) ?? "Could not delete the folder.");
+ throw errorFromBody(await refusalOf(res), t("projects.deleteFolderFailed"));
}
for (const p of held) purgeProject(p.id, r);
};
@@ -511,7 +517,7 @@ export function ProjectsHome() {
const create = async (r: Residency) => {
setBusy(true);
try {
- await openNewProject(r, name.trim() || "Untitled", openFolder);
+ await openNewProject(r, name.trim() || creatorNames().untitled, openFolder);
} finally {
setBusy(false);
}
@@ -520,7 +526,7 @@ export function ProjectsHome() {
// Make a new project in the folder that's open (root when none), then jump
// straight into it — no naming step.
const newProjectHere = (r: Residency, folderId: string | null = openFolder) =>
- openNewProject(r, "Untitled", folderId);
+ openNewProject(r, creatorNames().untitled, folderId);
// Turn a batch of desktop files into projects filed under `folderId`. Each
// becomes its own project and pops into the grid the moment it's ready.
@@ -577,14 +583,13 @@ export function ProjectsHome() {
try {
const res = await backendFor(r).fetch(`/api/cut/projects/${p.id}/duplicate`, {
method: "POST",
+ body: JSON.stringify({ locale: creatorLocale() }),
});
const body = (await res.json().catch(() => null)) as
| { jobId?: string; error?: string }
| null;
if (!res.ok) {
- throw new Error(
- quotaErrorMessage(res.status, body) ?? body?.error ?? "Could not duplicate the project."
- );
+ throw quotaError(res.status, body) ?? errorFromBody(body, t("projects.duplicateFailed"));
}
// Cloud duplicates queue (copies drain one at a time); poll until this
// one lands. The engine answers with the finished summary instead.
@@ -592,19 +597,17 @@ export function ProjectsHome() {
for (;;) {
await new Promise((done) => setTimeout(done, 2000));
const st = await backendFor(r).fetch(`/api/cut/copy-jobs/${body.jobId}`);
- if (!st.ok) throw new Error("Could not duplicate the project.");
+ if (!st.ok) throw new Error(t("projects.duplicateFailed"));
const job = (await st.json()) as { state: string; error?: string };
if (job.state === "done") break;
if (job.state === "error") {
- throw new Error(job.error || "Could not duplicate the project.");
+ throw errorFromBody(job, t("projects.duplicateFailed"));
}
}
}
await refresh(r);
} catch (e) {
- setDupError(
- e instanceof Error && e.message ? e.message : "Could not duplicate the project."
- );
+ setDupError(describeError(e, t("projects.duplicateFailed")));
} finally {
setBusy(false);
}
@@ -628,7 +631,7 @@ export function ProjectsHome() {
if (source === "cloud") void dropLocalProjectCopy(p.id);
await Promise.all([refresh(source), refresh(dest)]);
} catch (e) {
- setDupError(e instanceof Error && e.message ? e.message : "Could not move the project.");
+ setDupError(describeError(e, t("projects.moveFailed")));
} finally {
setBusy(false);
}
@@ -649,7 +652,7 @@ export function ProjectsHome() {
const removeOne = async (id: string, residency: Residency) => {
const res = await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
- if (!res.ok) throw new Error((await errorOf(res)) ?? "Could not delete the project.");
+ if (!res.ok) throw errorFromBody(await refusalOf(res), t("projects.deleteProjectFailed"));
purgeProject(id, residency);
patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));
};
@@ -672,7 +675,7 @@ export function ProjectsHome() {
]);
setSelected(new Set());
} catch (e) {
- setDupError(e instanceof Error && e.message ? e.message : "Could not delete.");
+ setDupError(describeError(e, t("projects.deleteFailed")));
} finally {
setDeleting(null);
setBusy(false);
@@ -681,7 +684,7 @@ export function ProjectsHome() {
// The way down to the open folder, for the crumb.
const trail = folderOwner ? folderTrail(data[folderOwner].folders, openFolder) : [];
- useTabTitle(openFolder ? trail.at(-1)?.name : "Projects");
+ useTabTitle(openFolder ? trail.at(-1)?.name : t("tabs.projects"));
// A folder pins where a new project lands, but only a shelf that answers can
// take one: inside a folder on an unreachable shelf, New project goes where
// the picker points instead.
@@ -921,7 +924,7 @@ export function ProjectsHome() {
)}
</div>
<div className="mt-2 px-0.5 text-xs text-muted-foreground">
- {formatBytes(p.sizeBytes ?? 0)} · edited {formatDate(p.updatedAt)}
+ {t("projects.cardMeta", { size: formatBytes(p.sizeBytes ?? 0, locale), date: formatDate(p.updatedAt, locale, t("justNow")) })}
</div>
</div>
);
@@ -944,10 +947,10 @@ export function ProjectsHome() {
const renderList = (shown: { p: ProjectSummary; r: Residency }[]) => (
<div className="overflow-hidden rounded-xl border border-border bg-card">
<div className="grid grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border bg-muted/50 px-4 py-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">
- <span>Name</span>
- <span>Length</span>
- <span>Size</span>
- <span>Edited</span>
+ <span className="truncate">{t("projects.columnName")}</span>
+ <span className="truncate">{t("projects.columnLength")}</span>
+ <span className="truncate">{t("projects.columnSize")}</span>
+ <span className="truncate">{t("projects.columnEdited")}</span>
<span />
</div>
{shown.map(({ p, r }) => (
@@ -978,10 +981,10 @@ export function ProjectsHome() {
{formatTime(p.duration)}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
- {formatBytes(p.sizeBytes ?? 0)}
+ {formatBytes(p.sizeBytes ?? 0, locale)}
</span>
<span className="text-xs text-muted-foreground">
- {formatDate(p.updatedAt)}
+ {formatDate(p.updatedAt, locale, t("justNow"))}
</span>
{live(r) ? (
<ProjectMenu
@@ -1005,7 +1008,7 @@ export function ProjectsHome() {
onClick={() => void newProjectHere(newTarget)}
className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
>
- <Plus className="size-4" /> New project
+ <Plus className="size-4" /> {t("newProject.button")}
</button>
</div>
);
@@ -1061,17 +1064,19 @@ export function ProjectsHome() {
<div className="pointer-events-none fixed right-6 bottom-6 z-50 flex items-center gap-2 rounded-full bg-foreground/90 px-3.5 py-2.5 text-background shadow-lg">
<Loader2 className="size-5 animate-spin" />
<span className="text-xs font-medium">
- Importing… <LiveElapsed className="tabular-nums" />
+ {t.rich("projects.importing", {
+ elapsed: () => <LiveElapsed className="tabular-nums" />,
+ })}
</span>
</div>
)}
{showHeader && (
<div className="mb-5 flex items-center justify-between">
{openFolder === null ? (
- <h1 className="text-lg font-semibold tracking-tight">Projects</h1>
+ <h1 className="text-lg font-semibold tracking-tight">{t("tabs.projects")}</h1>
) : (
<FolderCrumb
- root="Projects"
+ root={t("tabs.projects")}
trail={trail}
onRename={folderOwner && live(folderOwner) ? (id, name) => renameFolder(folderOwner, id, name) : undefined}
mime={PROJECT_MIME}
@@ -1090,7 +1095,7 @@ export function ProjectsHome() {
be answering. */}
{(openFolder === null || pinnedTarget) && (
<Button variant="outline" onClick={() => setFolderCreating(folderTarget)}>
- <FolderPlus data-icon="inline-start" /> New folder
+ <FolderPlus data-icon="inline-start" /> {t("projects.newFolder")}
</Button>
)}
<NewProjectButton
@@ -1102,7 +1107,7 @@ export function ProjectsHome() {
<Button
variant="ghost"
size="icon-sm"
- aria-label="Gallery view"
+ aria-label={t("projects.galleryView")}
aria-pressed={view === "gallery"}
className={cn(view === "gallery" && "bg-muted text-foreground")}
onClick={() => switchView("gallery")}
@@ -1112,7 +1117,7 @@ export function ProjectsHome() {
<Button
variant="ghost"
size="icon-sm"
- aria-label="List view"
+ aria-label={t("projects.listView")}
aria-pressed={view === "list"}
className={cn(view === "list" && "bg-muted text-foreground")}
onClick={() => switchView("list")}
@@ -1135,7 +1140,7 @@ export function ProjectsHome() {
</div>
) : homeView === "failed" ? (
<p className="py-24 text-center text-sm text-muted-foreground">
- Couldn&rsquo;t load these projects.
+ {t("projects.loadFailed")}
</p>
) : homeView === "empty" ? (
<div className="grid min-h-[60vh] place-items-center">
@@ -1144,7 +1149,7 @@ export function ProjectsHome() {
<Film className="size-7 text-muted-foreground" />
</div>
<h1 className="text-lg font-semibold tracking-tight">
- Create a new project to get started
+ {t("projects.emptyTitle")}
</h1>
<NewProjectButton
pinned={pinnedTarget}
@@ -1161,7 +1166,7 @@ export function ProjectsHome() {
(r) =>
data[r].error && (
<p key={r} className="mb-4 text-sm text-muted-foreground">
- Couldn&rsquo;t load {r === "cloud" ? "cloud projects" : "the projects on this Mac"}.
+ {r === "cloud" ? t("projects.loadFailedCloud") : t("projects.loadFailedLocal")}
</p>
)
)}
@@ -1173,7 +1178,7 @@ export function ProjectsHome() {
<Dialog open={createIn !== null} onOpenChange={(o) => !o && setCreateIn(null)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>New project</DialogTitle>
+ <DialogTitle>{t("newProject.title")}</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
@@ -1183,14 +1188,14 @@ export function ProjectsHome() {
>
<Input
autoFocus
- placeholder="Project name"
+ placeholder={t("newProject.placeholder")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<DialogFooter className="mt-4">
<Button type="submit" disabled={busy} className="w-full">
{busy && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Create project
+ {t("newProject.create")}
</Button>
</DialogFooter>
</form>
@@ -1200,7 +1205,7 @@ export function ProjectsHome() {
<Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>Rename project</DialogTitle>
+ <DialogTitle>{t("projects.renameTitle")}</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
@@ -1211,7 +1216,7 @@ export function ProjectsHome() {
<Input autoFocus value={name} onChange={(e) => setName(e.target.value)} />
<DialogFooter className="mt-4">
<Button type="submit" disabled={busy} className="w-full">
- Rename
+ {t("projects.rename")}
</Button>
</DialogFooter>
</form>
@@ -1256,26 +1261,20 @@ export function ProjectsHome() {
open={!!deleting}
title={
deleting
- ? `Delete ${pickLabel(deleting.folders, deleting.projects.map((x) => x.project), ["project", "projects"], deletingHeld)}?`
+ ? t("projects.deleteTitle", { what: pickLabel(deleting.folders, deleting.projects.map((x) => x.project), "project", deletingHeld) })
: ""
}
description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${
deletingTotal === 0
- ? deleting?.folders.length === 1
- ? "The folder is empty."
- : "The folders are empty."
- : deletingTotal === 1
- ? "This deletes the whole project folder, including its media files and exports."
- : "This deletes each project’s whole folder, including its media files and exports."
- } This can’t be undone.`}
+ ? t("projects.foldersEmpty", { count: deleting?.folders.length ?? 0 })
+ : t("projects.deletesFolders", { count: deletingTotal })
+ } ${t("projects.cannotUndo")}`}
action={
!deleting || deleting.folders.length === 0
- ? deleting && deleting.projects.length > 1
- ? "Delete projects"
- : "Delete project"
+ ? t("projects.deleteProjects", { count: deleting && deleting.projects.length > 1 ? deleting.projects.length : 1 })
: deleting.projects.length === 0 && deleting.folders.length === 1
- ? "Delete folder"
- : "Delete"
+ ? t("projects.deleteFolder")
+ : t("projects.delete")
}
busy={busy}
onClose={() => setDeleting(null)}
@@ -1448,11 +1447,11 @@ function useCardPoster(
return poster;
}
-const MOVE_DEST: Record<Residency, { Icon: typeof Cloud; label: string }> = {
- local: { Icon: Laptop, label: "Move to Local" },
- cloud: { Icon: Cloud, label: "Move to Cloud" },
- browser: { Icon: Laptop, label: "Move to Local" },
-};
+const MOVE_DEST = {
+ local: { Icon: Laptop, label: "moveToLocal" },
+ cloud: { Icon: Cloud, label: "moveToCloud" },
+ browser: { Icon: Laptop, label: "moveToLocal" },
+} as const satisfies Record<Residency, { Icon: typeof Cloud; label: string }>;
/** The actions on a project, or on a set of them: Rename and Duplicate take
* one project, so a set offers only the moves every member can make and
@@ -1469,29 +1468,30 @@ function ProjectMenuItems({
moveTo?: { target: Residency; run: () => void }[];
onDelete: () => void;
}) {
+ const t = useTranslations("home.projects");
return (
<>
{onRename && (
<DropdownMenuItem onClick={onRename}>
- <Pencil /> Rename
+ <Pencil /> {t("rename")}
</DropdownMenuItem>
)}
{onDuplicate && (
<DropdownMenuItem onClick={onDuplicate}>
- <Copy /> Duplicate
+ <Copy /> {t("duplicate")}
</DropdownMenuItem>
)}
{moveTo?.map(({ target, run }) => {
const { Icon, label } = MOVE_DEST[target];
return (
<DropdownMenuItem key={target} onClick={run}>
- <Icon /> {label}
+ <Icon /> {t(label)}
</DropdownMenuItem>
);
})}
{(onRename || onDuplicate || (moveTo?.length ?? 0) > 0) && <DropdownMenuSeparator />}
<DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
</>
);
@@ -1511,6 +1511,7 @@ function ProjectMenu({
moveTo?: { target: Residency; run: () => void }[];
onDelete: () => void;
}) {
+ const t = useTranslations("home.projects");
return (
<DropdownMenu>
<DropdownMenuTrigger
@@ -1518,7 +1519,7 @@ function ProjectMenu({
<Button
variant="ghost"
size="icon-sm"
- aria-label="Project actions"
+ aria-label={t("actions")}
className={cn("bg-black/40 text-white hover:bg-black/60 hover:text-white", className)}
onClick={(e) => e.stopPropagation()}
/>
diff --git a/site/src/cut/components/RecordDialog.tsx b/site/src/cut/components/RecordDialog.tsx
index 82eef70c..25ab9650 100644
--- a/site/src/cut/components/RecordDialog.tsx
+++ b/site/src/cut/components/RecordDialog.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import { Mic, Square, UserRound, Video, X } from "lucide-react";
import {
BufferTarget,
@@ -48,6 +49,17 @@ function stamp() {
type DeviceOption = { id: string; label: string };
+// What the dialog says in place of the preview, as keys of
+// `editor.recordDialog`: the state holds the key, the render words it.
+type RecordMessage =
+ | "deviceFallback"
+ | "cameraBlocked"
+ | "micBlocked"
+ | "cameraStartFailed"
+ | "startFailed"
+ | "saveFailed"
+ | "emptyRecording";
+
// Remembers the last device pick per kind so reopening the dialog restores it.
// Chrome keeps deviceIds stable per-origin once permission is granted.
const STORE_KEY = { videoinput: "cut.record.cameraId", audioinput: "cut.record.micId" };
@@ -68,11 +80,15 @@ function saveDeviceId(kind: "videoinput" | "audioinput", id: string | null) {
}
}
-function toOptions(devices: MediaDeviceInfo[], kind: MediaDeviceKind, fallback: string) {
+function toOptions(
+ devices: MediaDeviceInfo[],
+ kind: MediaDeviceKind,
+ fallback: (n: number) => string,
+) {
return devices
.filter((d) => d.kind === kind && d.deviceId)
.sort((a, b) => Number(b.deviceId === "default") - Number(a.deviceId === "default"))
- .map((d, i) => ({ id: d.deviceId, label: d.label || `${fallback} ${i + 1}` }));
+ .map((d, i) => ({ id: d.deviceId, label: d.label || fallback(i + 1) }));
}
export function RecordDialog({
@@ -84,9 +100,10 @@ export function RecordDialog({
onClose: () => void;
onUse: (file: File) => void;
}) {
+ const t = useTranslations("editor.recordDialog");
const [stream, setStream] = useState<MediaStream | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [notice, setNotice] = useState<string | null>(null);
+ const [error, setError] = useState<RecordMessage | null>(null);
+ const [notice, setNotice] = useState<RecordMessage | null>(null);
const [recording, setRecording] = useState(false);
const [elapsed, setElapsed] = useState(0);
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
@@ -176,13 +193,11 @@ export function RecordDialog({
setMicId(null);
saveDeviceId("videoinput", null);
saveDeviceId("audioinput", null);
- setNotice("That device could not be started — switched back to the default.");
+ setNotice("deviceFallback");
return;
}
setError(
- mode === "camera"
- ? "Camera access was blocked. Allow camera and microphone for this site in Chrome, then try again."
- : "Microphone access was blocked. Allow the microphone for this site in Chrome, then try again."
+ mode === "camera" ? "cameraBlocked" : "micBlocked"
);
});
return () => {
@@ -249,9 +264,7 @@ export function RecordDialog({
setRecording(true);
} catch {
setError(
- mode === "camera"
- ? "This browser could not start a camera recording. Check that no other app is using the camera, then try again."
- : "This browser could not start a recording. Try again."
+ mode === "camera" ? "cameraStartFailed" : "startFailed"
);
} finally {
startingRef.current = false;
@@ -266,14 +279,12 @@ export function RecordDialog({
try {
await output.finalize();
} catch {
- setError("The recording could not be saved. Try again.");
+ setError("saveFailed");
return;
}
const buffer = output.target.buffer;
if (!buffer || buffer.byteLength === 0) {
- setError(
- "The recording came back empty. Check that no other app is using the camera, then try again."
- );
+ setError("emptyRecording");
return;
}
// An MP4 holding only sound takes the audio extension and MIME, so it
@@ -300,8 +311,8 @@ export function RecordDialog({
saveDeviceId("audioinput", id);
};
- const cameras = toOptions(devices, "videoinput", "Camera");
- const mics = toOptions(devices, "audioinput", "Microphone");
+ const cameras = toOptions(devices, "videoinput", (n) => t("cameraN", { n }));
+ const mics = toOptions(devices, "audioinput", (n) => t("micN", { n }));
const activeCameraId =
cameraId ?? stream?.getVideoTracks()[0]?.getSettings().deviceId ?? "";
const activeMicId =
@@ -324,21 +335,21 @@ export function RecordDialog({
>
{/* Kept for accessibility; the dialog reads as its own preview. */}
<DialogTitle className="sr-only">
- {mode === "camera" ? "Record camera" : "Record audio"}
+ {mode === "camera" ? t("titleCamera") : t("titleAudio")}
</DialogTitle>
{/* Custom close so it stays legible over the full-bleed video. */}
<button
type="button"
onClick={onClose}
- aria-label="Close"
- title="Close"
+ aria-label={t("close")}
+ title={t("close")}
className="absolute top-3 right-3 z-20 grid size-9 place-items-center rounded-full bg-black/45 text-white backdrop-blur-sm transition-colors hover:bg-black/65"
>
<X className="size-4" />
</button>
{error ? (
- <p className="p-6 text-sm text-muted-foreground">{error}</p>
+ <p className="p-6 text-sm text-muted-foreground">{t(error)}</p>
) : (
<>
{mode === "camera" ? (
@@ -363,7 +374,7 @@ export function RecordDialog({
<div className="absolute inset-0 grid place-items-center">
<div className="flex flex-col items-center gap-3 text-white/60">
<UserRound className="size-12" strokeWidth={1.25} />
- <span className="text-xs">{notice ?? "Waiting for permission…"}</span>
+ <span className="text-xs">{notice ? t(notice) : t("waiting")}</span>
</div>
</div>
)}
@@ -371,7 +382,7 @@ export function RecordDialog({
{stream && notice && !recording && (
<p className="absolute inset-x-0 bottom-24 z-10 text-center">
<span className="rounded-md bg-black/60 px-2 py-1 text-xs text-white">
- {notice}
+ {t(notice)}
</span>
</p>
)}
@@ -424,7 +435,7 @@ export function RecordDialog({
{stream && notice && !recording && (
<p className="absolute inset-x-0 top-3 z-10 text-center">
<span className="rounded-md bg-black/60 px-2 py-1 text-xs text-white">
- {notice}
+ {t(notice)}
</span>
</p>
)}
@@ -463,7 +474,7 @@ export function RecordDialog({
/>
) : (
<span className="min-w-0 flex-1 text-center text-xs text-white/60">
- {notice ?? "Waiting for permission…"}
+ {notice ? t(notice) : t("waiting")}
</span>
)}
<span className="font-mono text-sm text-white/70 tabular-nums">
@@ -490,10 +501,11 @@ function RecordButton({
onStart: () => void;
onStop: () => void;
}) {
+ const t = useTranslations("editor.recordDialog");
return !recording ? (
<button
className="grid size-14 place-items-center rounded-full bg-white shadow-md transition-transform hover:scale-105 disabled:opacity-60"
- title="Start recording"
+ title={t("start")}
disabled={disabled}
onClick={onStart}
>
@@ -502,7 +514,7 @@ function RecordButton({
) : (
<button
className="grid size-14 place-items-center rounded-full bg-white shadow-md transition-transform hover:scale-105"
- title="Stop and use recording"
+ title={t("stop")}
onClick={onStop}
>
<Square className="size-6 fill-red-500 stroke-none" />
diff --git a/site/src/cut/components/RemovalPanel.tsx b/site/src/cut/components/RemovalPanel.tsx
index 45b97d13..9a686ed4 100644
--- a/site/src/cut/components/RemovalPanel.tsx
+++ b/site/src/cut/components/RemovalPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import { Loader2 } from "lucide-react";
import {
Select,
@@ -33,7 +34,6 @@ import {
import {
removalActive,
removalFingerprint,
- STROKE_STYLE_LABELS,
STROKE_STYLES,
type ClipRemoval,
type StrokeStyleId,
@@ -47,6 +47,7 @@ import { parseNumberInput } from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useLabels } from "@/i18n/labels";
/**
* The clip panel's Cutout view: one flat pane. A segmented Remove control
@@ -64,13 +65,8 @@ import { ScrollArea } from "@/components/ui/scroll-area";
/** The one choice: what goes, and how the selection is found. Background and
* Subject share the person matte and differ only in direction; Custom is the
* brush flow, where the paint marks what stays. */
-const TARGETS = [
- { id: "off", label: "Off" },
- { id: "background", label: "Background" },
- { id: "subject", label: "Subject" },
- { id: "custom", label: "Custom" },
-] as const;
-type Target = (typeof TARGETS)[number]["id"];
+const TARGETS = ["off", "background", "subject", "custom"] as const;
+type Target = (typeof TARGETS)[number];
/** Shared write path: transiently while a gesture is live, committed at its
* end, one checkpoint per gesture. */
@@ -88,6 +84,7 @@ function useRemovalWriter(clip: VideoClip) {
}
export function RemovalPanel({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const scroll = useRememberedScroll(clip.id, "cutout");
const removal = clip.removal;
const { commit } = useRemovalWriter(clip);
@@ -125,7 +122,7 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
<div className="flex min-h-0 flex-1 flex-col">
<div className="shrink-0 bg-card pb-2">
<div className="flex h-10 shrink-0 items-center px-3.5 text-sm font-semibold tracking-tight">
- Cutout
+ {t("title")}
</div>
</div>
<ScrollArea
@@ -136,7 +133,7 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
>
<RemovalView clip={clip} />
{removalActive(removal) && (
- <Row label="Original">
+ <Row label={t("original")}>
<button
type="button"
aria-pressed={peeking}
@@ -148,7 +145,7 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
)}
onClick={() => useEditor.setState({ removalPeek: peeking ? null : clip.id })}
>
- {peeking ? "Hide" : "Show"}
+ {peeking ? t("hide") : t("show")}
</button>
</Row>
)}
@@ -156,8 +153,8 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
{removal && removalActive(removal) && (
<>
<Section
- title="Stroke"
- info="Ink drawn around the cutout's silhouette — pick a style, color, and width."
+ title={t("stroke")}
+ info={t("strokeInfo")}
enabled={!!removal.stroke}
onEnabledChange={(v) =>
commit({ ...removal, stroke: v ? { style: "solid", color: "#ffffff" } : undefined })
@@ -166,8 +163,8 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
<StrokeView clip={clip} />
</Section>
<Section
- title="Fill"
- info="A color or image painted into the removed area, inside the clip's own frame."
+ title={t("fill")}
+ info={t("fillInfo")}
enabled={!!removal.backdrop && removal.backdrop.kind !== "none"}
onEnabledChange={(v) =>
commit({ ...removal, backdrop: v ? { kind: "color", color: "#101014" } : undefined })
@@ -192,6 +189,7 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
* direction and a baked matte carries over. Custom opens the brush flow,
* where the paint marks what stays. */
function ModePicker({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const { commit } = useRemovalWriter(clip);
const removal = clip.removal;
// One job at a time: while a bake runs, the other choices wait — Cancel is
@@ -228,30 +226,30 @@ function ModePicker({ clip }: { clip: VideoClip }) {
return (
<div className="pb-1">
- <div className="pb-1.5 text-[13px] text-muted-foreground">Remove</div>
+ <div className="pb-1.5 text-[13px] text-muted-foreground">{t("remove")}</div>
<div className="clip-removal-target flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
- {TARGETS.map((o) => (
+ {TARGETS.map((id) => (
<button
- key={o.id}
+ key={id}
type="button"
- aria-pressed={target === o.id}
- disabled={running && target !== o.id}
+ aria-pressed={target === id}
+ disabled={running && target !== id}
className={cn(
- `clip-removal-target-${o.id} whitespace-nowrap rounded-md px-2 py-1 transition-colors`,
+ `clip-removal-target-${id} whitespace-nowrap rounded-md px-2 py-1 transition-colors`,
// Every label carries the same padding, sized so all four fit
// the pane at their natural width — a squeezed row would shrink
// the last segment's padding. The real options grow from their
// own width, so leftover space spreads evenly and Off stays at
// its size.
- o.id !== "off" && "grow",
- target === o.id
+ id !== "off" && "grow",
+ target === id
? "bg-neutral-900 text-white"
: "text-muted-foreground hover:text-foreground",
"disabled:pointer-events-none disabled:opacity-40"
)}
- onClick={() => pick(o.id)}
+ onClick={() => pick(id)}
>
- {o.label}
+ {t(`targets.${id}`)}
</button>
))}
</div>
@@ -281,19 +279,20 @@ function BakeStatus({
label: string;
onCancel?: () => void;
}) {
+ const t = useTranslations("panels.removal");
if (!job) return null;
if (job.status === "error")
return (
<div className="flex items-start justify-between gap-2 pt-1 text-[11.5px] text-muted-foreground">
<span className="min-w-0">
- <HostedErrorText error={job.error ?? "The cutout could not be prepared."} />
+ <HostedErrorText error={job} fallback={t("prepareFailed")} />
</span>
<button
type="button"
className="clip-removal-retry shrink-0 rounded-md border border-input px-2 py-0.5 font-medium transition-colors hover:text-foreground"
onClick={() => retryMatteBake(clipId)}
>
- Retry
+ {t("retry")}
</button>
</div>
);
@@ -310,7 +309,7 @@ function BakeStatus({
className="clip-removal-cancel rounded-md border border-input px-2 py-0.5 font-medium transition-colors hover:text-foreground"
onClick={onCancel}
>
- Cancel
+ {t("cancel")}
</button>
)}
<span className="font-mono tabular-nums">
@@ -351,6 +350,7 @@ function TickingEta({ secondsLeft, etaAt }: { secondsLeft: number; etaAt: number
}
function CustomControls({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const tool = useBrushUi((s) => s.tool);
const size = useBrushUi((s) => s.size);
const erasing = tool === "erase";
@@ -361,13 +361,13 @@ function CustomControls({ clip }: { clip: VideoClip }) {
// frame the clip no longer plays would land off the clip.
const seeds = clip.removal?.seeds;
const strokeTimes = Array.from(new Set((seeds?.paint ?? []).map((s) => s.t)))
- .filter((t) => t >= clip.in - 0.05 && t <= clip.out + 0.05)
+ .filter((at) => at >= clip.in - 0.05 && at <= clip.out + 0.05)
.sort((a, b) => a - b);
const showStrokes = () => {
if (!strokeTimes.length) return;
const rt = retimeOf(clip);
const srcNow = rt.srcAt(Math.max(0, playheadAt() - clip.start));
- const next = strokeTimes.find((t) => t > srcNow + 0.05) ?? strokeTimes[0];
+ const next = strokeTimes.find((at) => at > srcNow + 0.05) ?? strokeTimes[0];
const end = clip.start + rt.len;
useEditor
.getState()
@@ -376,8 +376,8 @@ function CustomControls({ clip }: { clip: VideoClip }) {
return (
<>
<Row
- label="Tool"
- info={clip.removal?.invert ? "Paint to pick what goes" : "Paint to pick what stays"}
+ label={t("tool")}
+ info={clip.removal?.invert ? t("paintGoes") : t("paintStays")}
>
<div className="clip-brush-tool flex rounded-lg border border-input p-0.5">
{([false, true] as const).map((erase) => (
@@ -397,15 +397,15 @@ function CustomControls({ clip }: { clip: VideoClip }) {
useBrushUi.getState().setTool(tool);
}}
>
- {erase ? "Erase" : "Brush"}
+ {erase ? t("erase") : t("brush")}
</button>
))}
</div>
</Row>
<div className="clip-brush-size-row">
- <Row label="Size">
+ <Row label={t("size")}>
<ValueSlider
- label="Size"
+ label={t("size")}
sliderClassName="clip-brush-size data-horizontal:w-24"
valueClassName="w-12 text-muted-foreground"
value={Math.round(size * 1080)}
@@ -420,13 +420,13 @@ function CustomControls({ clip }: { clip: VideoClip }) {
</Row>
</div>
{strokeTimes.length > 0 && (
- <Row label="Strokes">
+ <Row label={t("strokes")}>
<button
type="button"
className="clip-brush-strokes rounded-md border border-input px-2 py-0.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
onClick={showStrokes}
>
- Show
+ {t("show")}
</button>
</Row>
)}
@@ -438,6 +438,7 @@ function CustomControls({ clip }: { clip: VideoClip }) {
* on its own — Apply starts each rung: auto's free person matte, then the
* hosted quality pass; custom's tracked bake for the painted selection. */
function RemovalActions({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const job = useMatteBakes((s) => s.jobs[clip.id]);
const { commit } = useRemovalWriter(clip);
const r = clip.removal;
@@ -445,7 +446,7 @@ function RemovalActions({ clip }: { clip: VideoClip }) {
const custom = r.mode === "custom";
// Paint outside the clip's current trim can't seed this bake (the tracker
// drops it), so it doesn't count as a selection.
- const inTrim = (t: number) => t >= clip.in - 0.05 && t <= clip.out + 0.05;
+ const inTrim = (at: number) => at >= clip.in - 0.05 && at <= clip.out + 0.05;
const hasSelection =
custom &&
!!(
@@ -490,10 +491,10 @@ function RemovalActions({ clip }: { clip: VideoClip }) {
job={job}
label={
custom
- ? "Tracking the selection…"
+ ? t("tracking")
: job?.quality === "hq"
- ? "Refining the person matte…"
- : "Finding the person…"
+ ? t("refining")
+ : t("finding")
}
onCancel={cancel}
/>
@@ -512,7 +513,7 @@ function RemovalActions({ clip }: { clip: VideoClip }) {
})
}
>
- Reset
+ {t("reset")}
</button>
)}
<button
@@ -523,7 +524,7 @@ function RemovalActions({ clip }: { clip: VideoClip }) {
)}
onClick={start}
>
- Apply
+ {t("apply")}
</button>
</div>
)}
@@ -567,6 +568,7 @@ function StrokeTile({
selected: boolean;
onPick: () => void;
}) {
+ const strokeStyleLabel = useLabels("strokeStyle");
const ref = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = ref.current;
@@ -612,13 +614,14 @@ function StrokeTile({
selected && PICKED_RING
)}
/>
- <span className="leading-none">{STROKE_STYLE_LABELS[style]}</span>
+ <span className="leading-none">{strokeStyleLabel(style)}</span>
</button>
);
}
/** The Stroke section, rendered only under an active cutout. */
function StrokeView({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const { draft, commit } = useRemovalWriter(clip);
const removal = clip.removal;
if (!removal) return null;
@@ -644,7 +647,7 @@ function StrokeView({ clip }: { clip: VideoClip }) {
</div>
{stroke && (
<>
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={color}
onBegin={() => {}}
@@ -652,9 +655,9 @@ function StrokeView({ clip }: { clip: VideoClip }) {
onCommit={(hex) => setStroke({ color: hex })}
/>
</Row>
- <Row label="Width">
+ <Row label={t("width")}>
<ValueSlider
- label="Width"
+ label={t("width")}
sliderClassName="clip-stroke-width data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={stroke.width ?? STROKE_DEFAULT_WIDTH}
@@ -667,9 +670,9 @@ function StrokeView({ clip }: { clip: VideoClip }) {
onCommit={(v) => setStroke({ width: v })}
/>
</Row>
- <Row label="Feather">
+ <Row label={t("feather")}>
<ValueSlider
- label="Feather"
+ label={t("feather")}
sliderClassName="clip-stroke-feather data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={stroke.feather ?? 0}
@@ -685,9 +688,9 @@ function StrokeView({ clip }: { clip: VideoClip }) {
</Row>
{stroke.style === "offset" && (
<>
- <Row label="Horizontal">
+ <Row label={t("horizontal")}>
<ValueSlider
- label="Horizontal"
+ label={t("horizontal")}
sliderClassName="clip-stroke-offset-x data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={stroke.offsetX ?? 0}
@@ -701,9 +704,9 @@ function StrokeView({ clip }: { clip: VideoClip }) {
onCommit={(v) => setStroke({ offsetX: v || undefined })}
/>
</Row>
- <Row label="Vertical">
+ <Row label={t("vertical")}>
<ValueSlider
- label="Vertical"
+ label={t("vertical")}
sliderClassName="clip-stroke-offset-y data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={stroke.offsetY ?? 0}
@@ -747,6 +750,7 @@ function BackdropImageOption({ asset, thumb }: { asset: MediaAsset; thumb: strin
/** The Fill section, rendered only under an active cutout. */
function BackgroundView({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("panels.removal");
const { draft, commit } = useRemovalWriter(clip);
const removal = clip.removal;
const assets = useEditor((s) => s.assets);
@@ -778,11 +782,11 @@ function BackgroundView({ clip }: { clip: VideoClip }) {
return (
<>
<div className="flex shrink-0 rounded-lg bg-muted p-0.5 text-[11.5px] font-medium">
- {pill("color", "Color")}
- {pill("image", "Image")}
+ {pill("color", t("color"))}
+ {pill("image", t("image"))}
</div>
{kind === "color" && (
- <Row label="Color">
+ <Row label={t("color")}>
<ColorField
value={backdrop?.color ?? "#101014"}
onBegin={() => {}}
@@ -794,10 +798,10 @@ function BackgroundView({ clip }: { clip: VideoClip }) {
{kind === "image" &&
(images.length === 0 ? (
<p className="pt-2 text-[12px] text-muted-foreground">
- Import an image into Media to use it as the background.
+ {t("importImage")}
</p>
) : (
- <Row label="Image">
+ <Row label={t("image")}>
<Select
value={backdrop?.assetId ?? images[0].id}
onValueChange={(id) => setBackdrop({ kind: "image", assetId: id as string })}
diff --git a/site/src/cut/components/RenameInput.tsx b/site/src/cut/components/RenameInput.tsx
index 1e33948c..4f31fe91 100644
--- a/site/src/cut/components/RenameInput.tsx
+++ b/site/src/cut/components/RenameInput.tsx
@@ -1,6 +1,7 @@
"use client";
import { useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
@@ -17,6 +18,7 @@ export function RenameInput({
onDone: (name?: string) => void;
className?: string;
}) {
+ const t = useTranslations("home.rename");
const [draft, setDraft] = useState(value);
const done = useRef(false);
const finish = (keep: boolean) => {
@@ -29,7 +31,7 @@ export function RenameInput({
<Input
autoFocus
value={draft}
- aria-label="Name"
+ aria-label={t("name")}
className={cn("h-6 w-full px-1.5 text-[12px]", className)}
onFocus={(e) => e.currentTarget.select()}
onChange={(e) => setDraft(e.target.value)}
diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsx
index 7e816263..8c614ac0 100644
--- a/site/src/cut/components/SceneCard.tsx
+++ b/site/src/cut/components/SceneCard.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import {
Check,
ChevronRight,
@@ -34,22 +35,14 @@ import { MEDIA_CORS } from "@/cut/lib/mediaCors";
// editor bridge; this is the control surface — approve the plan, watch shots
// land, redo one by clicking its chip.
-const STATUS_LABEL: Record<SceneRun["status"], string> = {
- planning: "Planning",
- awaiting_approval: "Storyboard ready",
- generating: "Rendering",
- done: "Done",
- failed: "Failed",
-};
-
/** mm:ss for a frame count at the plan's fixed rate. */
function fmt(frames: number): string {
return formatDuration((frames / GEN_FPS) * 1000);
}
-/** A single shot's own length in seconds, for the filmstrip badge ("3.2s"). */
+/** A single shot's own length in seconds, for the filmstrip badge ("3.2"). */
function shotSecs(sh: Shot): string {
- return `${((sh.endFrame - sh.startFrame) / GEN_FPS).toFixed(1)}s`;
+ return ((sh.endFrame - sh.startFrame) / GEN_FPS).toFixed(1);
}
/** The shot statuses that mean a render is actively in flight. */
@@ -61,6 +54,7 @@ function describe(sh: Shot): string {
}
export function SceneCard({ threadId }: { threadId: string }) {
+ const t = useTranslations("chat.sceneCard");
const run = useGenScene((s) => s.run);
const projectId = useEditor((s) => s.projectId);
const [open, setOpen] = useState(true);
@@ -104,9 +98,9 @@ export function SceneCard({ threadId }: { threadId: string }) {
// it is the one the user can act on.
const creditsReason = run.shots.find(
(sh) => sh.status === "failed" && sh.error === NO_CREDITS_MESSAGE
- )?.error;
+ );
const stillReason =
- creditsReason ?? run.shots.find((sh) => sh.status === "failed" && sh.error)?.error;
+ creditsReason ?? run.shots.find((sh) => sh.status === "failed" && sh.error);
// Elapsed clock: planning counts from the run start, rendering from approval;
// it stops at the end. Hidden while waiting for the user at the gate.
const clockAnchor = run.status === "planning" ? run.startedAt : run.renderStartedAt ?? run.startedAt;
@@ -117,10 +111,10 @@ export function SceneCard({ threadId }: { threadId: string }) {
<div className="ai-scene-card mt-2 mb-3 text-[11.5px]">
<div className="flex items-center gap-1.5">
<Clapperboard className="size-3.5 text-[#0a84ff]" />
- <span className="font-semibold">Generate video</span>
+ <span className="font-semibold">{t("title")}</span>
<span className="ml-auto flex items-center gap-1 text-[10.5px] text-muted-foreground">
{inFlight && <CircleDashed className="size-3 animate-spin" />}
- {STATUS_LABEL[run.status]}
+ {t(`status.${run.status}`)}
{elapsed && <span className="tabular-nums">· {elapsed}</span>}
</span>
</div>
@@ -140,13 +134,13 @@ export function SceneCard({ threadId }: { threadId: string }) {
<ChevronRight
className={`size-3 shrink-0 transition-transform ${open ? "rotate-90" : ""}`}
/>
- <span className="font-medium text-foreground">Plan</span>
+ <span className="font-medium text-foreground">{t("plan")}</span>
<span>
- {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} · {fmt(totalFrames)}
+ {t("planSummary", { count: run.shots.length, length: fmt(totalFrames) })}
</span>
{showProgress && (
<span className="ml-auto tabular-nums text-[10.5px]">
- {run.placed}/{run.total} placed
+ {t("placed", { placed: run.placed, total: run.total })}
</span>
)}
</button>
@@ -164,9 +158,9 @@ export function SceneCard({ threadId }: { threadId: string }) {
// before its frames): the tiles would be blank placeholders, so state
// the plan as a line and let shots appear as they actually render.
<p className="mt-2 flex items-center gap-1.5">
- <span className="font-medium">Plan</span>
+ <span className="font-medium">{t("plan")}</span>
<span className="text-muted-foreground">
- {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} · {fmt(totalFrames)}
+ {t("planSummary", { count: run.shots.length, length: fmt(totalFrames) })}
</span>
</p>
))}
@@ -184,7 +178,7 @@ export function SceneCard({ threadId }: { threadId: string }) {
<p className="mt-2 flex items-start gap-1.5 text-amber-700">
<TriangleAlert className="mt-px size-3 shrink-0" />
<span>
- <HostedErrorText error={run.error} link={false} />
+ <HostedErrorText error={run} link={false} />
</span>
</p>
)}
@@ -197,13 +191,16 @@ export function SceneCard({ threadId }: { threadId: string }) {
<span className="flex items-start gap-1 text-[10.5px] text-amber-700">
<TriangleAlert className="mt-px size-3 shrink-0" />
<span>
- {stillCount} of {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} held a
- still —{" "}
- {stillReason ? (
- <HostedErrorText error={stillReason} link={false} />
- ) : (
- "video generation failed"
- )}
+ {t.rich("stillsHeld", {
+ held: stillCount,
+ count: run.shots.length,
+ reason: () =>
+ stillReason ? (
+ <HostedErrorText error={stillReason} link={false} />
+ ) : (
+ t("videoFailed")
+ ),
+ })}
</span>
</span>
)}
@@ -214,7 +211,7 @@ export function SceneCard({ threadId }: { threadId: string }) {
className="h-7 flex-1 text-[11.5px]"
onClick={() => useGenScene.getState().approve()}
>
- Approve &amp; render{run.shots.length ? ` (${run.shots.length})` : ""}
+ {t("approve", { count: run.shots.length })}
</Button>
)}
{run.status === "failed" && (
@@ -225,12 +222,12 @@ export function SceneCard({ threadId }: { threadId: string }) {
className="h-7 flex-1 text-[11.5px]"
onClick={() => useGenScene.getState().retryRun()}
>
- Retry
+ {t("retry")}
</Button>
)}
{run.status === "done" && stillCount === 0 && (
<span className="flex flex-1 items-center gap-1 text-emerald-600">
- <Check className="size-3.5" /> Video ready
+ <Check className="size-3.5" /> {t("ready")}
</span>
)}
{run.status === "done" && stillCount > 0 && (
@@ -239,7 +236,7 @@ export function SceneCard({ threadId }: { threadId: string }) {
className="h-7 flex-1 text-[11.5px]"
onClick={() => useGenScene.getState().retryFailedShots()}
>
- Retry {stillCount} shot{stillCount === 1 ? "" : "s"}
+ {t("retryShots", { count: stillCount })}
</Button>
)}
</div>
@@ -306,6 +303,7 @@ function ShotTile({
redoable: boolean;
atGate: boolean;
}) {
+ const t = useTranslations("chat.sceneCard");
const clip = shot.clip ? assets.find((a) => a.id === shot.clip) : undefined;
const frame = shot.startKeyframe ? assets.find((a) => a.id === shot.startKeyframe) : undefined;
const media = clip ?? frame;
@@ -318,7 +316,7 @@ function ShotTile({
<div className="flex min-w-0 flex-col gap-1">
<div
onClick={view}
- title={`Shot ${n} — ${describe(shot)}`}
+ title={t("shotHint", { n, description: describe(shot) })}
className={cn(
"group/tile relative w-full overflow-hidden rounded-md bg-muted transition-opacity",
ref ? "cursor-zoom-in hover:opacity-95" : "cursor-default"
@@ -361,18 +359,18 @@ function ShotTile({
)}
{shot.status === "failed" && (
<span className="absolute top-1 left-1 rounded bg-amber-500/90 px-1 text-[8.5px] font-medium text-white">
- still
+ {t("still")}
</span>
)}
<span className="absolute right-1 bottom-1 rounded bg-black/65 px-1 font-mono text-[9px] text-white tabular-nums">
- {shotSecs(shot)}
+ {t("shotSeconds", { seconds: shotSecs(shot) })}
</span>
{redoable && (
<button
type="button"
- title={atGate ? "Redraw this frame" : "Redo this shot"}
+ title={atGate ? t("redraw") : t("redo")}
onClick={(e) => {
e.stopPropagation();
useGenScene.getState().regenerateShot(n);
@@ -387,7 +385,7 @@ function ShotTile({
)}
</div>
<div className="min-w-0">
- <div className="truncate text-[9.5px] font-medium text-foreground">Shot {n}</div>
+ <div className="truncate text-[9.5px] font-medium text-foreground">{t("shot", { n })}</div>
<p className="line-clamp-2 text-[9px] leading-snug text-muted-foreground">{describe(shot)}</p>
</div>
</div>
@@ -399,6 +397,7 @@ function ShotTile({
* Nothing the run does is internal: this is the same story the agent would
* tell in chat. */
function RunActivity({ run, inFlight }: { run: SceneRun; inFlight: boolean }) {
+ const t = useTranslations("chat.sceneCard");
// Feed thumbnails resolve against the open project's media (the run's
// assets are project assets, chat-owned).
const assets = useEditor((s) => s.assets);
@@ -418,7 +417,7 @@ function RunActivity({ run, inFlight }: { run: SceneRun; inFlight: boolean }) {
return (
<div className="ai-scene-activity mt-2 flex flex-col gap-1.5">
- <div className="text-[10.5px] font-medium text-muted-foreground">Activity</div>
+ <div className="text-[10.5px] font-medium text-muted-foreground">{t("activity")}</div>
{run.feed.map((f, i) => {
const asset = f.mediaId ? assets.find((a) => a.id === f.mediaId) : undefined;
const ref = asset ? refFromAsset(asset) : undefined;
@@ -452,6 +451,7 @@ function FeedEntry({
asset?: MediaAsset;
pulse: boolean;
}) {
+ const t = useTranslations("chat.sceneCard");
const [expanded, setExpanded] = useState(false);
const { ref: videoRef, handlers: hoverPlay } = useHoverPlay();
const inPlace = item?.kind === "image" || item?.kind === "video";
@@ -476,7 +476,7 @@ function FeedEntry({
<div
className="group/tile relative cursor-zoom-out overflow-hidden rounded-xl border border-border bg-muted"
style={{ width, aspectRatio: ratio }}
- title={`${item.name} — click to minimize`}
+ title={t("minimizeHint", { name: item.name })}
onClick={() => setExpanded(false)}
{...(item.kind === "video" ? hoverPlay : {})}
>
@@ -500,7 +500,7 @@ function FeedEntry({
</span>
)}
<button
- title="Expand"
+ title={t("expand")}
className={cn(
scrimIconButton,
"absolute top-1 right-1 opacity-0 transition-opacity group-hover/tile:opacity-100"
@@ -523,7 +523,7 @@ function FeedEntry({
{item && (
<button
type="button"
- title={`${item.name} — click to view`}
+ title={t("viewHint", { name: item.name })}
className="shrink-0"
onClick={() =>
inPlace
diff --git a/site/src/cut/components/ScrubValue.tsx b/site/src/cut/components/ScrubValue.tsx
index 74c2058e..1438a6d4 100644
--- a/site/src/cut/components/ScrubValue.tsx
+++ b/site/src/cut/components/ScrubValue.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { snapNear } from "@/lib/snap";
@@ -53,6 +54,7 @@ export function ScrubValue({
* is where a scrub starts from. */
mixed?: boolean;
}) {
+ const t = useTranslations("inspector.controls");
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState("");
const [preview, setPreview] = useState<number | null>(null);
@@ -157,7 +159,7 @@ export function ScrubValue({
type="button"
disabled={disabled}
aria-label={label}
- title={disabled ? undefined : "Drag to adjust · click to type"}
+ title={disabled ? undefined : t("dragOrType")}
className={cn(
"touch-none select-none text-right font-mono text-[11.5px] tabular-nums underline decoration-transparent decoration-dotted underline-offset-3 transition-colors",
disabled
@@ -216,7 +218,7 @@ export function ScrubValue({
}
}}
>
- {preview != null ? format(preview) : mixed ? <span className="font-sans italic">Mixed</span> : format(value)}
+ {preview != null ? format(preview) : mixed ? <span className="font-sans italic">{t("mixed")}</span> : format(value)}
</button>
);
}
diff --git a/site/src/cut/components/SearchSuggestions.tsx b/site/src/cut/components/SearchSuggestions.tsx
index a5a0d1df..62b35d2b 100644
--- a/site/src/cut/components/SearchSuggestions.tsx
+++ b/site/src/cut/components/SearchSuggestions.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { toolDisplayOf } from "@/cut/lib/toolDisplay";
@@ -30,6 +31,7 @@ export function SearchSuggestions({ output }: { output: unknown }) {
}
function SuggestionFrame({ html }: { html: string }) {
+ const t = useTranslations("chat.searchSuggestions");
const ref = useRef<HTMLIFrameElement>(null);
const [height, setHeight] = useState(0);
@@ -60,7 +62,7 @@ function SuggestionFrame({ html }: { html: string }) {
return (
<iframe
ref={ref}
- title="Google Search suggestions"
+ title={t("frameTitle")}
srcDoc={`<!doctype html><html><head>${FRAME_HEAD}</head><body>${html}</body></html>`}
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
referrerPolicy="no-referrer"
diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsx
index f838f794..c8dd3f01 100644
--- a/site/src/cut/components/ShareDialog.tsx
+++ b/site/src/cut/components/ShareDialog.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { Check, ChevronDown, Globe, Link as LinkIcon, Lock, X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -24,7 +25,9 @@ import { requestSharing, type ShareResource } from "@/cut/lib/sharingClient";
import { librarySharePath, shareEmailSchema, type ShareSettings as AccessSettings } from "@/cut/lib/librarySharing";
import { refreshShareCard, refreshShareLadder } from "@/cut/lib/exportClient";
import { useCutBase } from "@/cut/lib/nav";
-import { isTimelineId, TIMELINE_IDS, TIMELINE_LABELS, type ShareFeatures, type TimelineId } from "@/cut/lib/types";
+import { isTimelineId, TIMELINE_IDS, type ShareFeatures, type TimelineId } from "@/cut/lib/types";
+import { useDescribeError } from "@/i18n/describeError";
+import { useLabels } from "@/i18n/labels";
// One sharing dialog for projects, library folders, and assets. Changes save immediately.
@@ -42,13 +45,9 @@ const NO_FEATURES: ShareFeatures = {
type FeatureKey = Exclude<keyof ShareFeatures, "timeline">;
-const FEATURE_ROWS: { key: FeatureKey; label: string; hint: string }[] = [
- { key: "chat", label: "Chat", hint: "AI chat threads and their cards" },
- { key: "media", label: "Media", hint: "Uploaded files beyond the timeline" },
- { key: "genai", label: "AI generations", hint: "Generated video, image, and audio" },
- { key: "subtitles", label: "Subtitles", hint: "The transcript panel" },
- { key: "details", label: "Details", hint: "Caption, tags, and notes" },
-];
+// The switches under "Also share", in order; each names itself through
+// `features.<key>` in the editor catalog.
+const FEATURE_ROWS: FeatureKey[] = ["chat", "media", "genai", "subtitles", "details"];
/** The share link for a share id: the viewer route lives beside the app
* subtree, so the app base minus its /app segment is the share base. */
@@ -57,6 +56,9 @@ function shareLink(base: string, shareId: string): string {
}
export function ShareDialog(props: ShareResource & { onClose: () => void }) {
+ const t = useTranslations("editor.shareDialog");
+ const describeError = useDescribeError();
+ const timelineLabel = useLabels("timeline");
const { onClose } = props;
const projectId = "projectId" in props ? props.projectId : null;
const libraryTarget = "libraryTarget" in props ? props.libraryTarget : null;
@@ -94,7 +96,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
setError(null);
try {
const body = await requestSharing(props, "PUT", next);
- if (!body.share) throw new Error("Could not save sharing.");
+ if (!body.share) throw new Error(t("saveFailed"));
const saved = { ...body.share, features: body.share.features ?? NO_FEATURES };
// Sharing for the first time: build the link's preview card now, so the
// first person to open the link sees the cut rather than a placeholder,
@@ -109,7 +111,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
if (seq === saveSeq.current) setShare(saved);
return saved;
} catch {
- setError("Could not save sharing.");
+ setError(t("saveFailed"));
return null;
} finally {
mutationBusy.current = false;
@@ -133,7 +135,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
const email = draft.trim().toLowerCase();
if (!email) return;
if (!shareEmailSchema.safeParse(email).success) {
- setError("That doesn't look like an email address.");
+ setError(t("invalidEmail"));
return;
}
setDraft("");
@@ -178,7 +180,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
- setError("Could not copy the link. Try again.");
+ setError(t("copyFailed"));
}
};
@@ -191,7 +193,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
await requestSharing(props, "DELETE");
setShare(null);
} catch {
- setError("Could not remove the share.");
+ setError(t("removeFailed"));
} finally {
mutationBusy.current = false;
setSaving(false);
@@ -204,17 +206,17 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>Share {libraryTarget?.kind ?? "project"}</DialogTitle>
+ <DialogTitle>{t("title", { kind: libraryTarget?.kind ?? "project" })}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
- People
+ {t("people")}
</span>
<input
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring disabled:opacity-60"
type="email"
- placeholder="Invite by email, press Enter"
+ placeholder={t("invitePlaceholder")}
disabled={busy}
value={draft}
onChange={(e) => setDraft(e.target.value)}
@@ -235,7 +237,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
{email}
<button
disabled={busy}
- aria-label={`Remove ${email}`}
+ aria-label={t("removeEmail", { email })}
className="grid size-4 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
onClick={() => removeEmail(email)}
>
@@ -249,7 +251,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
<div className="flex flex-col gap-1.5">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
- General access
+ {t("generalAccess")}
</span>
<DropdownMenu>
<DropdownMenuTrigger
@@ -263,12 +265,12 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
)}
<span className="min-w-0 flex-1">
<span className="block font-medium">
- {current.access === "public" ? "Anyone with the link" : "Restricted"}
+ {current.access === "public" ? t("public") : t("restricted")}
</span>
<span className="block text-[11px] text-muted-foreground">
{current.access === "public"
- ? "Anyone can view — no sign-in needed"
- : "Only people you invite can view, signed in"}
+ ? t("publicHint")
+ : t("restrictedHint")}
</span>
</span>
<ChevronDown className="size-3.5 text-muted-foreground" />
@@ -277,9 +279,9 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
<DropdownMenuItem onClick={() => setAccess("restricted")}>
<Lock />
<span className="flex-1">
- Restricted
+ {t("restricted")}
<span className="block text-[10.5px] text-muted-foreground">
- Only people you invite can view, signed in
+ {t("restrictedHint")}
</span>
</span>
{current.access === "restricted" && (
@@ -289,9 +291,9 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
<DropdownMenuItem onClick={() => setAccess("public")}>
<Globe />
<span className="flex-1">
- Anyone with the link
+ {t("public")}
<span className="block text-[10.5px] text-muted-foreground">
- Anyone can view — no sign-in needed
+ {t("publicHint")}
</span>
</span>
{current.access === "public" && (
@@ -305,8 +307,8 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
{projectId && (
<div className="flex min-h-9 items-center justify-between gap-2.5">
<span className="text-[13px]">
- Timeline
- <span className="block text-[10.5px] text-muted-foreground">What viewers watch</span>
+ {t("timeline")}
+ <span className="block text-[10.5px] text-muted-foreground">{t("timelineHint")}</span>
</span>
<Select
value={current.features.timeline ?? "main"}
@@ -315,13 +317,13 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
if (isTimelineId(v)) void setTimeline(v);
}}
>
- <SelectTrigger className="w-fit min-w-28" aria-label="Timeline">
+ <SelectTrigger className="w-fit min-w-28" aria-label={t("timeline")}>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{TIMELINE_IDS.map((id) => (
<SelectItem key={id} value={id}>
- {TIMELINE_LABELS[id]}
+ {timelineLabel(id)}
</SelectItem>
))}
</SelectContent>
@@ -332,23 +334,22 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
{projectId ? <details className="group">
<summary className="cursor-pointer list-none text-[11px] font-medium tracking-wide text-muted-foreground uppercase select-none">
<span className="inline-flex items-center gap-1">
- Also share
+ {t("alsoShare")}
<ChevronDown className="size-3 transition-transform group-open:rotate-180" />
</span>
</summary>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
- Viewers always get the preview and timeline, read-only. Switch
- on anything else they should see.
+ {t("alsoShareHint")}
</p>
<div className="mt-1 flex flex-col">
- {FEATURE_ROWS.map(({ key, label, hint }) => (
+ {FEATURE_ROWS.map((key) => (
<label
key={key}
className="flex min-h-9 cursor-pointer items-center justify-between gap-2.5"
>
<span className="text-[13px]">
- {label}
- <span className="block text-[10.5px] text-muted-foreground">{hint}</span>
+ {t(`features.${key}.label`)}
+ <span className="block text-[10.5px] text-muted-foreground">{t(`features.${key}.hint`)}</span>
</span>
<Switch
checked={current.features[key]}
@@ -361,23 +362,23 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
</details> : (
<p className="text-[11px] leading-relaxed text-muted-foreground">
{libraryTarget?.kind === "folder"
- ? "Viewers can browse and download this folder’s contents, including subfolders. Changes to the folder appear on the shared link."
- : "Viewers can preview and download this asset."}
+ ? t("folderHint")
+ : t("assetHint")}
</p>
)}
- {(error || query.error) && <p role="alert" className="text-sm text-red-600">{error ?? query.error?.message}</p>}
- {query.isError && <Button variant="outline" onClick={() => void query.refetch()}>Try again</Button>}
+ {(error || query.error) && <p role="alert" className="text-sm text-red-600">{error ?? describeError(query.error)}</p>}
+ {query.isError && <Button variant="outline" onClick={() => void query.refetch()}>{t("tryAgain")}</Button>}
</div>
<DialogFooter className="mt-1 flex-col gap-2 sm:flex-col">
<Button className="w-full" disabled={busy} onClick={() => void copyLink()}>
{copied ? (
<>
- <Check data-icon="inline-start" /> Copied
+ <Check data-icon="inline-start" /> {t("copied")}
</>
) : (
<>
- <LinkIcon data-icon="inline-start" /> Copy link
+ <LinkIcon data-icon="inline-start" /> {t("copyLink")}
</>
)}
</Button>
@@ -391,7 +392,7 @@ export function ShareDialog(props: ShareResource & { onClose: () => void }) {
disabled={busy || !share}
onClick={() => void removeShare()}
>
- Stop sharing
+ {t("stopSharing")}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/site/src/cut/components/SharedLibraryView.tsx b/site/src/cut/components/SharedLibraryView.tsx
index 3a28b985..02542c01 100644
--- a/site/src/cut/components/SharedLibraryView.tsx
+++ b/site/src/cut/components/SharedLibraryView.tsx
@@ -3,6 +3,7 @@
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { Download, Folder, Loader2 } from "lucide-react";
+import { useTranslations } from "next-intl";
import { buttonVariants } from "@/components/ui/button";
import { useSharedLibrary } from "@/queries/sharing";
import { ApiError } from "@/queries/apiClient";
@@ -25,6 +26,7 @@ function Asset({ asset, token }: { asset: SharedLibraryAsset; token: string }) {
}
export function SharedLibraryView() {
+ const t = useTranslations("home.sharedLibrary");
const { token } = useParams<{ token: string }>();
const params = useSearchParams();
const folder = params.get("folder");
@@ -45,16 +47,16 @@ export function SharedLibraryView() {
<div className="mx-auto max-w-6xl px-5 py-9 sm:px-10">
<header className="mb-8 flex items-center justify-between gap-4">
<Link href={base} className="text-lg font-semibold">Donkey Cut</Link>
- <span className="text-xs text-muted-foreground">Shared library · View only</span>
+ <span className="text-xs text-muted-foreground">{t("viewOnly")}</span>
</header>
- {query.isPending ? <div role="status" className="grid min-h-64 place-items-center"><Loader2 aria-label="Loading shared library" className="size-5 animate-spin" /></div>
+ {query.isPending ? <div role="status" className="grid min-h-64 place-items-center"><Loader2 aria-label={t("loading")} className="size-5 animate-spin" /></div>
: query.isError ? <div className="flex min-h-64 flex-col items-center justify-center gap-4 text-center">
- <p role="alert" className="text-sm text-muted-foreground">{status === 401 ? "Sign in to view this share." : status === 403 ? "You don’t have access to this share. Ask the owner to invite you." : status === 404 ? "This share link is no longer available." : "Could not load this share."}</p>
+ <p role="alert" className="text-sm text-muted-foreground">{status === 401 ? t("signInToView") : status === 403 ? t("noAccess") : status === 404 ? t("gone") : t("loadFailed")}</p>
{status === 401 || status === 403
- ? <Link href={authHrefFor("/sign-in", href(folder, offset))} className={buttonVariants()}>Sign in</Link>
- : status !== 404 && <button onClick={() => void query.refetch()} className={buttonVariants({ variant: "outline" })}>Try again</button>}
+ ? <Link href={authHrefFor("/sign-in", href(folder, offset))} className={buttonVariants()}>{t("signIn")}</Link>
+ : status !== 404 && <button onClick={() => void query.refetch()} className={buttonVariants({ variant: "outline" })}>{t("tryAgain")}</button>}
</div> : data && <>
- <nav aria-label="Folder breadcrumb" className="mb-5 flex flex-wrap items-center gap-2 text-lg font-semibold">
+ <nav aria-label={t("breadcrumb")} className="mb-5 flex flex-wrap items-center gap-2 text-lg font-semibold">
{data.trail.length ? data.trail.map((f, i) => <span key={f.id} className="flex items-center gap-2">
{i > 0 && <span className="text-muted-foreground">/</span>}
{i === data.trail.length - 1 ? <span>{f.name}</span> : <Link href={href(f.id)} className="text-muted-foreground hover:text-foreground">{f.name}</Link>}
@@ -68,15 +70,15 @@ export function SharedLibraryView() {
<div className="flex flex-wrap items-start gap-4">
{data.assets.map((asset) => <Asset key={asset.id} asset={asset} token={token} />)}
</div>
- {data.templates.map((t) => <section key={t.id} className="mt-5 rounded-xl border p-4">
- <h2 className="mb-2 text-sm font-medium">{t.name}</h2>
- <p className="mb-2 text-xs text-muted-foreground">Template media</p>
- {t.files.map((f, i) => <a key={i} className="flex items-center gap-2 py-1 text-sm hover:underline" href={`/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(t.id)}?${new URLSearchParams({ template: t.id, file: f.fileName, download: "1" })}`}><Download className="size-3" />{f.name}</a>)}
+ {data.templates.map((tpl) => <section key={tpl.id} className="mt-5 rounded-xl border p-4">
+ <h2 className="mb-2 text-sm font-medium">{tpl.name}</h2>
+ <p className="mb-2 text-xs text-muted-foreground">{t("templateMedia")}</p>
+ {tpl.files.map((f, i) => <a key={i} className="flex items-center gap-2 py-1 text-sm hover:underline" href={`/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(tpl.id)}?${new URLSearchParams({ template: tpl.id, file: f.fileName, download: "1" })}`}><Download className="size-3" />{f.name}</a>)}
</section>)}
- {!data.folders.length && !data.assets.length && !data.templates.length && <p className="py-16 text-center text-sm text-muted-foreground">This folder is empty.</p>}
- <nav aria-label="Pages" className="mt-6 flex justify-between">
- {offset > 0 ? <Link href={href(folder)} className={buttonVariants({ variant: "outline" })}>First page</Link> : <span />}
- {data.next !== null && <Link href={href(folder, data.next)} className={buttonVariants({ variant: "outline" })}>Next page</Link>}
+ {!data.folders.length && !data.assets.length && !data.templates.length && <p className="py-16 text-center text-sm text-muted-foreground">{t("emptyFolder")}</p>}
+ <nav aria-label={t("pages")} className="mt-6 flex justify-between">
+ {offset > 0 ? <Link href={href(folder)} className={buttonVariants({ variant: "outline" })}>{t("firstPage")}</Link> : <span />}
+ {data.next !== null && <Link href={href(folder, data.next)} className={buttonVariants({ variant: "outline" })}>{t("nextPage")}</Link>}
</nav>
</>}
</div>
diff --git a/site/src/cut/components/ShelfBadge.tsx b/site/src/cut/components/ShelfBadge.tsx
index d65e5153..5fa1d45c 100644
--- a/site/src/cut/components/ShelfBadge.tsx
+++ b/site/src/cut/components/ShelfBadge.tsx
@@ -1,5 +1,7 @@
import { Cloud, Laptop } from "lucide-react";
-import { RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";
+import { useTranslations } from "next-intl";
+import { useLabels } from "@/i18n/labels";
+import type { Residency } from "@/cut/lib/residency";
/** Which shelf an item sits on, on its card. The library merges both, so the
* badge is how you tell a clip on this Mac from one in the cloud — and, when
@@ -13,13 +15,15 @@ export function ShelfBadge({
offline?: boolean;
className?: string;
}) {
+ const t = useTranslations("home.shelfBadge");
+ const residencyLabel = useLabels("residency");
const Icon = residency === "cloud" ? Cloud : Laptop;
return (
<span
title={
offline
- ? "Local — open the Donkey app to use it"
- : RESIDENCY_LABEL[residency]
+ ? t("offline")
+ : residencyLabel(residency)
}
className={className}
>
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 9d8fa0bd..55cbcea4 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -6,6 +6,7 @@ import { LibraryImportCard } from "@/cut/components/LibraryImportCard";
import { libraryFolderRef, projectFolderRef } from "@/cut/lib/folderReference";
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
+import { useFormatter, useLocale, useTranslations } from "next-intl";
import { Captions, Check, Clapperboard, ClipboardList, Copy, Download, Ellipsis, Film, FolderOpen, FolderPlus, Image as ImageIcon, Loader2, Music, Shapes, Sparkles, Trash2, Upload, X, Blend } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -129,9 +130,7 @@ import {
import {
DeleteConfirm,
SelectionMenu,
- foldersGoNote,
- phoneGoNote,
- pickLabel,
+ usePickWords,
useSelectionMenu,
} from "./selectionMenu";
import { TemplateCard } from "./TemplateCard";
@@ -173,16 +172,16 @@ const railGroup = (id: Tab): "files" | "gen" | "finish" =>
: id === "subtitles" || id === "publish" ? "finish"
: "files";
-const TABS: { id: Tab; label: string; icon: typeof Film }[] = [
- { id: "media", label: "Media", icon: Clapperboard },
- { id: "elements", label: "Elements", icon: Shapes },
- { id: "effects", label: "Effects", icon: Sparkles },
- { id: "transitions", label: "Transitions", icon: Blend },
- { id: "video", label: "Video", icon: Film },
- { id: "image", label: "Image", icon: ImageIcon },
- { id: "audio", label: "Audio", icon: Music },
- { id: "subtitles", label: "Subtitles", icon: Captions },
- { id: "publish", label: "Details", icon: ClipboardList },
+const TABS: { id: Tab; icon: typeof Film }[] = [
+ { id: "media", icon: Clapperboard },
+ { id: "elements", icon: Shapes },
+ { id: "effects", icon: Sparkles },
+ { id: "transitions", icon: Blend },
+ { id: "video", icon: Film },
+ { id: "image", icon: ImageIcon },
+ { id: "audio", icon: Music },
+ { id: "subtitles", icon: Captions },
+ { id: "publish", icon: ClipboardList },
];
export function SidePanel({
@@ -194,6 +193,7 @@ export function SidePanel({
onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
+ const t = useTranslations("media.sidePanel");
// A shared view opens only the surfaces the share opted in. The rail still
// shows every tab so the viewer sees what the editor has; a tab the share
// withholds sits locked, and hovering it says why. The Library is the
@@ -219,7 +219,7 @@ export function SidePanel({
// `null` collapses the panel: clicking the active tab unselects it, leaving
// just the icon rail so the video canvas takes the freed width.
const [tabPref, setTab] = useLocalPref<Tab | null>("cut-side-tab", "media", (v) =>
- v === null || TABS.some((t) => t.id === v)
+ v === null || TABS.some((x) => x.id === v)
);
// The remembered tab may be hidden in this share — the viewer's own last tab
// in their own editor, which this share never offered. A share opens on what
@@ -336,7 +336,7 @@ export function SidePanel({
)}
contentClassName="flex flex-col items-center gap-1 py-3"
>
- {railTabs.map(({ id, label, icon: Icon }, tabIndex) => {
+ {railTabs.map(({ id, icon: Icon }, tabIndex) => {
const locked = !offered(id);
// The open tab never badges — its completions are already on screen.
const unseenCount = isGenTab(id) && id !== tab ? unseen[id].length : 0;
@@ -368,7 +368,7 @@ export function SidePanel({
tab === id && "text-foreground"
)}
>
- {label}
+ {t(`tabs.${id}`)}
</span>
</>
);
@@ -384,7 +384,7 @@ export function SidePanel({
{inner}
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
- View only. Ask the owner for edit access.
+ {t("viewOnly")}
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -562,11 +562,12 @@ function forDrags(props: DragProps, takesRef: (ref: AssetRef) => boolean): DragP
* face keeps it legible where the column scrolls beneath it. Same action as
* clicking the active rail tile. */
function ClosePanelButton({ onClose }: { onClose: () => void }) {
+ const t = useTranslations("media.sidePanel");
return (
<button
type="button"
- aria-label="Close panel"
- title="Close panel"
+ aria-label={t("closePanel")}
+ title={t("closePanel")}
className="absolute top-2.5 right-2.5 z-10 grid size-7 place-items-center rounded-md bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
onClick={onClose}
>
@@ -592,11 +593,12 @@ function useLibraryFold(key: string) {
* middle, a small gap right of the panel border. The hit target is wider than
* the pill so it stays easy to grab. */
function LibraryKnob({ open, onToggle }: { open: boolean; onToggle: () => void }) {
+ const t = useTranslations("media.sidePanel");
return (
<button
type="button"
- aria-label={open ? "Hide library" : "Show library"}
- title={open ? "Hide library" : "Show library"}
+ aria-label={open ? t("hideLibrary") : t("showLibrary")}
+ title={open ? t("hideLibrary") : t("showLibrary")}
className="group absolute top-1/2 -right-[16px] z-20 flex h-16 w-4 -translate-y-1/2 items-center justify-center outline-none"
onClick={onToggle}
>
@@ -624,6 +626,12 @@ function TileStatus({ count, busy }: { count: number; busy: boolean }) {
return null;
}
+/** A file size in megabytes with one decimal, in the page's number style:
+ * 12582912 bytes → "12.0" (the message adds the unit). */
+function megabytes(format: ReturnType<typeof useFormatter>, bytes: number): string {
+ return format.number(bytes / (1024 * 1024), { minimumFractionDigits: 1, maximumFractionDigits: 1 });
+}
+
function PanelHead({ title }: { title: string }) {
return (
<div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">
@@ -680,6 +688,7 @@ function ExportThumb({
* owns, and a render this tab is doing itself, which is how a cloud or browser
* project exports and which carries its progress on its own local row. */
function ExportingRow({ row, settling = false }: { row: ExportRow; settling?: boolean }) {
+ const t = useTranslations("media.exports");
const { status } = row.data;
const running = !settling && (status === "running" || status === "rendering");
const cancelable = !settling && exportCancelable(row);
@@ -693,15 +702,17 @@ function ExportingRow({ row, settling = false }: { row: ExportRow; settling?: bo
<Loader2 className="size-3.5 animate-spin text-primary" />
</div>
<span className="min-w-0 flex-1">
- <span className="block truncate text-[11.5px] font-medium">Exporting…</span>
+ <span className="block truncate text-[11.5px] font-medium">{t("exporting")}</span>
<span className="block text-[10.5px] text-muted-foreground tabular-nums">
{settling
- ? "Finishing…"
+ ? t("finishing")
: running
- ? `${pct}%${elapsed ? ` · ${elapsed}` : ""}`
+ ? elapsed
+ ? t("progressElapsed", { pct, elapsed })
+ : t("progress", { pct })
: status === "preparing"
- ? "Preparing…"
- : "Queued"}
+ ? t("preparing")
+ : t("queued")}
</span>
</span>
{cancelable && (
@@ -711,7 +722,7 @@ function ExportingRow({ row, settling = false }: { row: ExportRow; settling?: bo
className="shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => useExports.getState().cancel(row.data.id)}
>
- Cancel
+ {t("cancel")}
</Button>
)}
{running && (
@@ -737,6 +748,7 @@ function MediaPanel({
onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
+ const t = useTranslations("media.mediaPanel");
// A shared view shows only the project's own files — the Library is the
// viewer's cross-project shelf, so the toggle drops and a plain head stays.
const sharedFeatures = useEditor((s) => s.sharedFeatures);
@@ -756,15 +768,15 @@ function MediaPanel({
return (
<>
{sharedFeatures ? (
- <PanelHead title="Media" />
+ <PanelHead title={t("media")} />
) : (
/* PanelHead's height, so the side panel's floating close button lands
on the toggle's centerline; the right padding keeps clear of it. */
<div className="flex h-12 shrink-0 items-center pr-12 pl-3.5">
<SubTabs
tabs={[
- { id: "project", label: "Project Files" },
- { id: "library", label: "Library" },
+ { id: "project", label: t("projectFiles") },
+ { id: "library", label: t("library") },
]}
value={view}
onChange={setSub}
@@ -796,6 +808,10 @@ function ProjectFilesPanel({
onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
importing: boolean;
}) {
+ const t = useTranslations("media.projectFiles");
+ const te = useTranslations("media.exports");
+ const { pickLabel, foldersGoNote } = usePickWords();
+ const format = useFormatter();
const caps = useCutCaps();
// Only user-imported media lives here; anything Cut created (recordings, AI
// generations, voiceovers, freeze frames, stock adds) is tagged with an
@@ -1016,7 +1032,7 @@ function ProjectFilesPanel({
{!readOnly && (
<div className="px-3.5 pb-3">
<Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>
- <Upload data-icon="inline-start" /> Upload
+ <Upload data-icon="inline-start" /> {t("upload")}
</Button>
<input
ref={inputRef}
@@ -1038,10 +1054,10 @@ function ProjectFilesPanel({
<div className="flex h-9 shrink-0 items-center px-2 pb-1.5">
<FolderCrumb
className="text-sm"
- root="Project Files"
+ root={t("root")}
onRename={!readOnly ? (id, name) => useEditor.getState().renameMediaFolder(id, name) : undefined}
trail={[
- { id: openFolder, name: folders.find((f) => f.id === openFolder)?.name ?? "Folder" },
+ { id: openFolder, name: folders.find((f) => f.id === openFolder)?.name ?? t("folder") },
]}
mime={MEDIA_MOVE_MIME}
onGo={() => setOpenFolder(null)}
@@ -1100,23 +1116,23 @@ function ProjectFilesPanel({
{openFolder === null && templates.length > 0 && (
<div className="grid grid-cols-2 gap-2.5 px-3.5 pb-3">
- {templates.map((t) => (
+ {templates.map((tpl) => (
<TemplateCard
- key={t.id}
+ key={tpl.id}
tile="fill"
- template={t}
+ template={tpl}
mediaSrc={(f) => mediaUrl(projectId, f)}
- drag={{ scope: "project", template: t }}
- addTitle="Add to timeline"
- onAdd={() => void addProjectTemplateToTimeline(projectId, t)}
- onRename={(name) => useEditor.getState().renameTemplate(t.id, name)}
- onDelete={() => useEditor.getState().removeTemplate(t.id)}
+ drag={{ scope: "project", template: tpl }}
+ addTitle={t("addToTimeline")}
+ onAdd={() => void addProjectTemplateToTimeline(projectId, tpl)}
+ onRename={(name) => useEditor.getState().renameTemplate(tpl.id, name)}
+ onDelete={() => useEditor.getState().removeTemplate(tpl.id)}
onRefDrop={(r) => {
- if (r.scope === "project") useEditor.getState().addAssetToTemplate(t.id, r.id);
+ if (r.scope === "project") useEditor.getState().addAssetToTemplate(tpl.id, r.id);
}}
extraMenu={
- <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>
- <FolderPlus /> Add to Library
+ <DropdownMenuItem onClick={() => void saveTemplate(projectId, tpl)}>
+ <FolderPlus /> {t("addToLibrary")}
</DropdownMenuItem>
}
/>
@@ -1126,7 +1142,7 @@ function ProjectFilesPanel({
{order.length === 0 && !importing ? (
openFolder !== null ? (
<div className="px-3.5 py-6 text-center text-xs text-muted-foreground">
- Empty folder
+ {t("emptyFolder")}
</div>
) : assets.length === 0 && folders.length === 0 ? (
<div className="px-2 py-7 text-center text-xs leading-relaxed text-balance text-muted-foreground">
@@ -1134,8 +1150,7 @@ function ProjectFilesPanel({
<Film className="size-5" />
<Music className="size-5" />
</div>
- Drop videos, audio and images assets here. They are only available in
- this project.
+ {t("empty")}
</div>
) : null
) : (
@@ -1161,7 +1176,7 @@ function ProjectFilesPanel({
<div className="flex aspect-square flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-input text-[11px] text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
<span>
- Importing… <LiveElapsed />
+ {t("importing")} <LiveElapsed />
</span>
</div>
)}
@@ -1170,7 +1185,7 @@ function ProjectFilesPanel({
{openFolder === null && exports.length + exporting.length + settling.length > 0 && (
<div className="mt-5 px-3.5">
- <div className="mb-2 text-[13px] font-semibold tracking-tight">Exports</div>
+ <div className="mb-2 text-[13px] font-semibold tracking-tight">{te("title")}</div>
<div className="flex flex-col gap-1.5">
{exporting.map((row) => (
<ExportingRow key={row.data.id} row={row} />
@@ -1195,7 +1210,7 @@ function ProjectFilesPanel({
<span className="min-w-0 flex-1">
<span className="block truncate text-[11.5px] font-medium">{it.file}</span>
<span className="block text-[10.5px] text-muted-foreground">
- {(it.size / (1024 * 1024)).toFixed(1)} MB · WAV stems · ZIP
+ {te("stemsMeta", { size: megabytes(format, it.size) })}
</span>
</span>
</div>
@@ -1203,7 +1218,7 @@ function ProjectFilesPanel({
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-2.5 text-left"
- title={unplayable.has(it.file) ? "Master file" : "Preview as a post"}
+ title={unplayable.has(it.file) ? te("masterFile") : te("previewAsPost")}
onClick={() => !unplayable.has(it.file) && setPreview(it)}
>
<ExportThumb
@@ -1223,7 +1238,7 @@ function ProjectFilesPanel({
/>
<span className="min-w-0 flex-1">
<span className="block truncate text-[11.5px] font-medium">
- {new Date(it.mtime).toLocaleString([], {
+ {format.dateTime(new Date(it.mtime), {
month: "short",
day: "numeric",
hour: "numeric",
@@ -1231,7 +1246,7 @@ function ProjectFilesPanel({
})}
</span>
<span className="block text-[10.5px] text-muted-foreground">
- {(it.size / (1024 * 1024)).toFixed(1)} MB · {containerOfName(it.file).label}
+ {te("fileMeta", { size: megabytes(format, it.size), container: containerOfName(it.file).label })}
</span>
</span>
</button>
@@ -1241,8 +1256,8 @@ function ProjectFilesPanel({
<Button
variant="ghost"
size="icon-xs"
- aria-label="Show in Finder"
- title="Show in Finder"
+ aria-label={te("showInFinder")}
+ title={te("showInFinder")}
onClick={() => void revealExport(projectId, it.file).catch(() => {})}
>
<FolderOpen />
@@ -1251,8 +1266,8 @@ function ProjectFilesPanel({
<Button
variant="ghost"
size="icon-xs"
- aria-label="Download export"
- title="Download"
+ aria-label={te("downloadExport")}
+ title={te("download")}
onClick={() => downloadProjectExport(projectId, it)}
>
<Download />
@@ -1261,8 +1276,8 @@ function ProjectFilesPanel({
<Button
variant="ghost"
size="icon-xs"
- aria-label="Delete export"
- title="Delete export"
+ aria-label={te("deleteExport")}
+ title={te("deleteExport")}
className="text-muted-foreground hover:text-destructive"
onClick={() => setDeletingExport(it)}
>
@@ -1286,14 +1301,11 @@ function ProjectFilesPanel({
<AlertDialog open={!!deletingExport} onOpenChange={(o) => !o && setDeletingExport(null)}>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>Delete this export?</AlertDialogTitle>
- <AlertDialogDescription>
- The rendered file leaves the project’s exports folder. Your cut is untouched — you
- can export it again anytime.
- </AlertDialogDescription>
+ <AlertDialogTitle>{te("deleteTitle")}</AlertDialogTitle>
+ <AlertDialogDescription>{te("deleteDescription")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogCancel>{te("cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive/10 text-destructive hover:bg-destructive/20"
onClick={(e) => {
@@ -1301,7 +1313,7 @@ function ProjectFilesPanel({
void removeExport();
}}
>
- Delete
+ {te("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1310,7 +1322,7 @@ function ProjectFilesPanel({
<SelectionMenu menu={ctx.menu} onClose={ctx.close}>
{ctx.menu?.ids.length === 0 ? (
<DropdownMenuItem onClick={() => setCreatingIds([])}>
- <FolderPlus /> New folder
+ <FolderPlus /> {t("newFolder")}
</DropdownMenuItem>
) : ctx.menu && splitPick(ctx.menu.ids).folders.length === 1 && ctx.menu.ids.length === 1 ? (
// A menu over one folder offers the folder's own actions.
@@ -1332,13 +1344,13 @@ function ProjectFilesPanel({
setOpenFolder(null);
}}
>
- <FolderPlus /> New folder
+ <FolderPlus /> {t("newFolder")}
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
<DropdownMenuItem variant="destructive" onClick={() => removeMany(ctx.menu!.ids)}>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
</>
)}
@@ -1348,11 +1360,11 @@ function ProjectFilesPanel({
open={deletingIds !== null}
title={
deletingFolders.length === 0 && deletingFiles.length === 1
- ? "Remove this file from the project?"
- : `Remove ${pickLabel(deletingFolders, deletingFiles, ["file", "files"], deletingHeld)} from the project?`
+ ? t("removeOneTitle")
+ : t("removeManyTitle", { label: pickLabel(deletingFolders, deletingFiles, "file", deletingHeld) })
}
- description={`${foldersGoNote(deletingFolders.length, deletingHeld)}Timeline clips made from them are removed too.`}
- action="Remove"
+ description={`${foldersGoNote(deletingFolders.length, deletingHeld)}${t("clipsRemovedToo")}`}
+ action={t("remove")}
onClose={() => setDeletingIds(null)}
onConfirm={() => {
deleteNow(deletingIds ?? []);
@@ -1367,12 +1379,13 @@ function ProjectFilesPanel({
* the way: a line across the bottom of the tile while the bytes go out, and a
* message only if they don't arrive. */
function UploadState({ asset }: { asset: MediaAsset }) {
+ const t = useTranslations("media.uploadState");
const upload = asset.upload;
if (!upload) return null;
if (upload.error) {
return (
<div className="absolute inset-x-0 bottom-0 flex items-center gap-1.5 bg-black/70 px-1.5 py-1 text-[10px] text-white">
- <span className="min-w-0 flex-1 truncate">Upload failed</span>
+ <span className="min-w-0 flex-1 truncate">{t("failed")}</span>
<button
type="button"
className="shrink-0 font-medium underline underline-offset-2"
@@ -1381,7 +1394,7 @@ function UploadState({ asset }: { asset: MediaAsset }) {
retryUpload(asset.id);
}}
>
- Retry
+ {t("retry")}
</button>
</div>
);
@@ -1432,6 +1445,8 @@ function AssetCard({
/** A drop that landed leaves nothing to keep picked. */
onDragLanded?: () => void;
}) {
+ const t = useTranslations("media.assetCard");
+ const locale = useLocale();
const caps = useCutCaps();
const [saved, setSaved] = useState(false);
// Number of timeline items that would be cascade-deleted; null = no prompt.
@@ -1563,7 +1578,7 @@ function AssetCard({
: "bottom-1 left-1 rounded-[5px] bg-black/65 px-1 py-px text-[9.5px] text-white"
)}
>
- {formatBytes(sizeBytes)}
+ {formatBytes(sizeBytes, locale)}
</span>
)}
<CardActionsMenu
@@ -1576,13 +1591,13 @@ function AssetCard({
extra={
<>
<DropdownMenuItem onClick={saveToLibrary} disabled={!!asset.upload}>
- <FolderPlus /> Save to library
+ <FolderPlus /> {t("saveToLibrary")}
</DropdownMenuItem>
{caps.revealInFinder && (
<DropdownMenuItem
onClick={() => void revealMedia(projectId, asset.fileName).catch(() => {})}
>
- <FolderOpen /> Show in Finder
+ <FolderOpen /> {t("showInFinder")}
</DropdownMenuItem>
)}
</>
@@ -1618,10 +1633,10 @@ function AssetCard({
<AlertDialog open={confirmUses !== null} onOpenChange={(o) => !o && setConfirmUses(null)}>
<AlertDialogContent aria-describedby={undefined}>
<AlertDialogHeader>
- <AlertDialogTitle>Remove “{asset.name}” from the project?</AlertDialogTitle>
+ <AlertDialogTitle>{t("removeTitle", { name: asset.name })}</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive/10 text-destructive hover:bg-destructive/20"
onClick={(e) => {
@@ -1630,7 +1645,7 @@ function AssetCard({
setConfirmUses(null);
}}
>
- Remove
+ {t("remove")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1651,6 +1666,8 @@ function LibraryPanel({ projectId, onImport }: {
projectId: string;
onImport: (files: FileList | File[], opts?: { mediaOnly?: boolean; folderId?: string }) => void;
}) {
+ const t = useTranslations("media.library");
+ const { pickLabel, foldersGoNote, phoneGoNote } = usePickWords();
const client = useQueryClient();
// One cached listing serves every library surface (lib/queries.ts), and it
// stays live while this panel is open: the shelf re-reads on a timer and
@@ -1837,7 +1854,7 @@ function LibraryPanel({ projectId, onImport }: {
// holds no folders.
const cameraRoll: LibraryFolder & { locked?: boolean } = {
id: CAMERA_ROLL_FOLDER,
- name: "Camera Roll",
+ name: t("cameraRoll"),
createdAt: 0,
residency: "cloud",
locked: true,
@@ -1953,7 +1970,7 @@ function LibraryPanel({ projectId, onImport }: {
<div className="flex h-9 shrink-0 items-center px-2 pb-1.5">
<FolderCrumb
className="text-sm"
- root="Library"
+ root={t("root")}
trail={trail}
onRename={openFolder !== CAMERA_ROLL_FOLDER ? renameFolder : undefined}
mime={LIBRARY_MOVE_MIME}
@@ -2017,26 +2034,26 @@ function LibraryPanel({ projectId, onImport }: {
{shownTemplates.length > 0 && (
<div className="shrink-0 px-3.5 pb-3">
<div className="grid grid-cols-2 gap-2.5">
- {shownTemplates.map((t) => (
+ {shownTemplates.map((tpl) => (
<TemplateCard
- key={t.id}
+ key={tpl.id}
tile="fill"
- template={t}
- mediaSrc={(f) => libraryMediaUrl(f, t.residency)}
- drag={{ scope: "library", template: t }}
+ template={tpl}
+ mediaSrc={(f) => libraryMediaUrl(f, tpl.residency)}
+ drag={{ scope: "library", template: tpl }}
onDragStartExtra={(e) => {
- e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([t.id]));
+ e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([tpl.id]));
e.dataTransfer.effectAllowed = "copyMove";
}}
- addTitle="Add to this project"
- onAdd={() => void addTemplateToProject(projectId, t)}
- onRename={(name) => void commitTemplateRename(t.residency, t.id, name)}
- onDelete={() => void removeTemplate(t.residency, t.id)}
+ addTitle={t("addToProject")}
+ onAdd={() => void addTemplateToProject(projectId, tpl)}
+ onRename={(name) => void commitTemplateRename(tpl.residency, tpl.id, name)}
+ onDelete={() => void removeTemplate(tpl.residency, tpl.id)}
onRefDrop={(r) => {
if (r.scope !== "project") return;
const asset = useEditor.getState().assets.find((a) => a.id === r.id);
if (!asset) return;
- void addAssetToLibraryTemplate(projectId, t, asset)
+ void addAssetToLibraryTemplate(projectId, tpl, asset)
.then((updated) =>
patch((d) => ({
...d,
@@ -2057,12 +2074,11 @@ function LibraryPanel({ projectId, onImport }: {
// content — the invitation is only for a truly empty library.
openFolder !== null ? (
shownTemplates.length === 0 ? (
- <div className="px-3.5 py-6 text-center text-xs text-muted-foreground">Empty folder</div>
+ <div className="px-3.5 py-6 text-center text-xs text-muted-foreground">{t("emptyFolder")}</div>
) : null
) : all.length === 0 && folders.length === 0 && templates.length === 0 ? (
<div className="text-balance px-3.5 py-6 text-center text-xs text-muted-foreground">
- Drag video, audio, image and font files here. Library assets are shared across all
- projects.
+ {t("empty")}
</div>
) : null
) : (
@@ -2110,7 +2126,7 @@ function LibraryPanel({ projectId, onImport }: {
/>
) : (
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
)}
</SelectionMenu>
@@ -2118,10 +2134,10 @@ function LibraryPanel({ projectId, onImport }: {
<DeleteConfirm
open={!!deleting}
title={
- deleting ? `Delete ${pickLabel(deleting.folders, deleting.items, ["item", "items"], deletingHeld)}?` : ""
+ deleting ? t("deleteTitle", { label: pickLabel(deleting.folders, deleting.items, "item", deletingHeld) }) : ""
}
- description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}
- action="Remove"
+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}${t("keepCopy", { count: deletingTotal })}`}
+ action={t("remove")}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && void remove(deleting)}
/>
@@ -2134,12 +2150,13 @@ function LibraryPanel({ projectId, onImport }: {
type LibraryDeleteSet = { folders: LibraryFolder[]; items: LibraryAsset[] };
function CopyChip({ text, label }: { text: string; label: string }) {
+ const t = useTranslations("media.publish");
const [copied, setCopied] = useState(false);
return (
<button
className="copy-chip inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
disabled={!text}
- title={`Copy ${label}`}
+ title={label}
onClick={() => {
void navigator.clipboard.writeText(text).then(() => {
setCopied(true);
@@ -2148,12 +2165,14 @@ function CopyChip({ text, label }: { text: string; label: string }) {
}}
>
{copied ? <Check className="size-3 text-emerald-600" /> : <Copy className="size-3" />}
- {copied ? "Copied" : "Copy"}
+ {copied ? t("copied") : t("copy")}
</button>
);
}
function PublishPanel() {
+ const t = useTranslations("media.publish");
+ const format = useFormatter();
const readOnly = useEditor((s) => s.readOnly);
const publish = useEditor((s) => s.publish);
const setPublish = useEditor((s) => s.setPublish);
@@ -2166,16 +2185,16 @@ function PublishPanel() {
return (
<>
- <PanelHead title="Details" />
+ <PanelHead title={t("title")} />
<ScrollArea className="min-h-0" contentClassName="flex flex-col gap-4 px-3.5 pb-4">
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
- <SectionTitle>Caption</SectionTitle>
- <CopyChip text={publish.caption.trim()} label="caption" />
+ <SectionTitle>{t("caption")}</SectionTitle>
+ <CopyChip text={publish.caption.trim()} label={t("copyCaption")} />
</div>
<textarea
className="publish-caption min-h-[110px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
- placeholder={"What's happening in this video?\n\nHooks read best in the first line."}
+ placeholder={t("captionPlaceholder")}
value={publish.caption}
readOnly={readOnly}
onChange={(e) => setPublish({ caption: e.target.value })}
@@ -2184,38 +2203,38 @@ function PublishPanel() {
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
- <SectionTitle>Tags</SectionTitle>
- <CopyChip text={tagsLine} label="tags" />
+ <SectionTitle>{t("tags")}</SectionTitle>
+ <CopyChip text={tagsLine} label={t("copyTags")} />
</div>
<input
className="publish-tags w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"
- placeholder="fyp howto cut"
+ placeholder={t("tagsPlaceholder")}
value={publish.tags}
readOnly={readOnly}
onChange={(e) => setPublish({ tags: e.target.value })}
/>
{tagsLine && (
<div className="publish-tag-preview flex flex-wrap gap-1">
- {tagsLine.split(" ").map((t) => (
- <span key={t} className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10.5px]">
- {t}
+ {tagsLine.split(" ").map((tag) => (
+ <span key={tag} className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10.5px]">
+ {tag}
</span>
))}
</div>
)}
<p className="text-[11px] leading-relaxed text-muted-foreground">
- 3–5 focused tags work best. Tags count toward the caption limit.
+ {t("tagsHint")}
</p>
</div>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
- <SectionTitle>Sound title</SectionTitle>
- <CopyChip text={publish.soundTitle.trim()} label="sound title" />
+ <SectionTitle>{t("soundTitle")}</SectionTitle>
+ <CopyChip text={publish.soundTitle.trim()} label={t("copySoundTitle")} />
</div>
<input
className="publish-sound w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"
- placeholder="My track — artist"
+ placeholder={t("soundTitlePlaceholder")}
value={publish.soundTitle}
readOnly={readOnly}
onChange={(e) => setPublish({ soundTitle: e.target.value })}
@@ -2223,9 +2242,9 @@ function PublishPanel() {
</div>
<div className="flex flex-col gap-1.5 border-t border-border pt-4">
- <SectionTitle>Notes</SectionTitle>
+ <SectionTitle>{t("notes")}</SectionTitle>
<label className="flex items-center justify-between gap-2 text-[12px] text-muted-foreground">
- Published
+ {t("published")}
<input
type="date"
className="notes-date rounded-lg border border-input bg-transparent px-2 py-1 text-[12px] outline-none focus:border-ring"
@@ -2236,14 +2255,14 @@ function PublishPanel() {
</label>
<textarea
className="notes-links min-h-[54px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-[11.5px] leading-relaxed outline-none focus:border-ring"
- placeholder={"Links, one per line\nhttps://tiktok.com/…"}
+ placeholder={t("linksPlaceholder")}
value={notes.links.join("\n")}
readOnly={readOnly}
onChange={(e) => setNotes({ links: e.target.value.split("\n") })}
/>
<textarea
className="notes-text min-h-[70px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
- placeholder="Anything worth remembering about this cut…"
+ placeholder={t("notesPlaceholder")}
value={notes.text}
readOnly={readOnly}
onChange={(e) => setNotes({ text: e.target.value })}
@@ -2263,11 +2282,11 @@ function PublishPanel() {
>
{copiedAll ? (
<>
- <Check data-icon="inline-start" /> Copied
+ <Check data-icon="inline-start" /> {t("copied")}
</>
) : (
<>
- <Copy data-icon="inline-start" /> Copy caption + tags
+ <Copy data-icon="inline-start" /> {t("copyAll")}
</>
)}
</Button>
@@ -2277,7 +2296,7 @@ function PublishPanel() {
count > CAPTION_LIMIT ? "font-semibold text-red-600" : "text-muted-foreground"
)}
>
- {count.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}
+ {t("count", { count: format.number(count), limit: format.number(CAPTION_LIMIT) })}
</p>
</div>
</ScrollArea>
diff --git a/site/src/cut/components/SpeedCurveStrip.tsx b/site/src/cut/components/SpeedCurveStrip.tsx
index 1419d4aa..af53196a 100644
--- a/site/src/cut/components/SpeedCurveStrip.tsx
+++ b/site/src/cut/components/SpeedCurveStrip.tsx
@@ -2,6 +2,7 @@
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { ChevronDown, Minus, Plus, RotateCcw, X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
flatSpeedCurve,
@@ -92,6 +93,11 @@ export function SpeedCurveStrip() {
}
function Strip({ clip }: { clip: VideoClip }) {
+ const t = useTranslations("timeline.speedCurve");
+ // A preset's name and hint by its id; the kit's list keeps its English for
+ // the model.
+ const presetText = (id: string, part: "label" | "hint") =>
+ t(`presets.${id}.${part}` as Parameters<typeof t>[0]);
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const picked = useEditor((s) =>
s.selectedKey?.track === "speed" && s.selectedKey.id === clip.id
@@ -458,7 +464,7 @@ function Strip({ clip }: { clip: VideoClip }) {
>
{pickedRate != null && (
<span className="tabular-nums text-foreground/70">
- node {fmtRate(pickedRate)} at {fmtSec(rt.tAt(picked!))}
+ {t("node", { rate: fmtRate(pickedRate), time: fmtSec(rt.tAt(picked!)) })}
</span>
)}
<span className="flex-1" />
@@ -468,13 +474,13 @@ function Strip({ clip }: { clip: VideoClip }) {
<Button
variant="outline"
size="xs"
- title={preset?.hint ?? "Pick a preset curve"}
+ title={preset ? presetText(preset.id, "hint") : t("pickPreset")}
className="gap-1.5 pl-1.5 font-normal"
/>
}
>
<Sparkline shape={shape} />
- <span>{preset?.label ?? "Custom"}</span>
+ <span>{preset ? presetText(preset.id, "label") : t("custom")}</span>
<ChevronDown className="size-3 text-muted-foreground" />
</DropdownMenuTrigger>
<DropdownMenuContent
@@ -489,7 +495,7 @@ function Strip({ clip }: { clip: VideoClip }) {
{SPEED_CURVE_PRESETS.map((p) => (
<DropdownMenuItem
key={p.id}
- title={p.hint}
+ title={presetText(p.id, "hint")}
className={cn(
"relative block h-20 w-40 overflow-hidden rounded-xl border border-border bg-muted/40 p-0 focus:bg-muted",
p.id === presetId && PICKED_RING,
@@ -504,7 +510,7 @@ function Strip({ clip }: { clip: VideoClip }) {
<Sparkline shape={p.shape} w={140} h={48} grid />
</span>
<span className="absolute bottom-1.5 left-2.5 text-[11.5px] font-medium">
- {p.label}
+ {presetText(p.id, "label")}
</span>
</DropdownMenuItem>
))}
@@ -531,24 +537,24 @@ function Strip({ clip }: { clip: VideoClip }) {
aria-pressed={!!clip.smoothSlow}
onClick={() => useEditor.getState().setClipSmoothSlow(clip.id, !clip.smoothSlow)}
>
- Smooth Slow-mo
+ {t("smoothSlow")}
</Button>
- <InfoTip label="Smooth Slow-mo" side="top">
- When on, everything under 1× is smoothed on export.
+ <InfoTip label={t("smoothSlow")} side="top">
+ {t("smoothSlowInfo")}
</InfoTip>
<span className="mx-1 h-4 w-px bg-border" />
- <IconButton title="Add a node at the playhead" onClick={addAtPlayhead}>
+ <IconButton title={t("addNode")} onClick={addAtPlayhead}>
<Plus className="size-3.5" />
</IconButton>
<IconButton
- title="Remove the picked node (Delete)"
+ title={t("removeNode")}
disabled={picked === null || nodes.length <= 1}
onClick={removePicked}
>
<Minus className="size-3.5" />
</IconButton>
<IconButton
- title="Flatten to 1×"
+ title={t("flatten")}
onClick={() => {
pick(null);
setDraft(null);
@@ -560,7 +566,7 @@ function Strip({ clip }: { clip: VideoClip }) {
<RotateCcw className="size-3.5" />
</IconButton>
<IconButton
- title="Close (Esc)"
+ title={t("close", { key: "Esc" })}
onClick={() => panelState.set(clip.id, "speedCurve", false)}
>
<X className="size-3.5" />
diff --git a/site/src/cut/components/Stickers.tsx b/site/src/cut/components/Stickers.tsx
index dab6e0e3..697b728e 100644
--- a/site/src/cut/components/Stickers.tsx
+++ b/site/src/cut/components/Stickers.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useMemo, useState } from "react";
+import { useTranslations } from "next-intl";
import { Copy, Loader2, Plus, Sparkles, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -27,6 +28,7 @@ import { CopyHandlePill, MentionTextarea, RefChips } from "./AssetRefs";
import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
import { DictationControl } from "./MicDictation";
import { HostedErrorText } from "./hostedError";
+import { useDescribeError } from "@/i18n/describeError";
/**
* The project's sticker images — generated cutouts, all tagged origin
@@ -70,6 +72,7 @@ export function StickerTile({
handle?: string;
readOnly: boolean;
}) {
+ const t = useTranslations("media.stickers");
const { picked, pick } = useAssetPick(a.id);
const lottie = isLottieAsset(a);
return (
@@ -115,8 +118,8 @@ export function StickerTile({
{!readOnly && (
<div className="pointer-events-auto flex shrink-0 items-center gap-1">
<button
- title="Add to timeline"
- aria-label={`Add ${a.name}`}
+ title={t("addToTimeline")}
+ aria-label={t("addNamed", { name: a.name })}
className={ROUND_ACTION}
onClick={() =>
useEditor
@@ -138,7 +141,7 @@ export function StickerTile({
.catch(() => {})
}
>
- <Copy /> Copy reference
+ <Copy /> {t("copyReference")}
</DropdownMenuItem>
}
after={
@@ -146,7 +149,7 @@ export function StickerTile({
variant="destructive"
onClick={() => useEditor.getState().removeAsset(a.id)}
>
- <Trash2 /> Delete
+ <Trash2 /> {t("delete")}
</DropdownMenuItem>
}
/>
@@ -157,12 +160,6 @@ export function StickerTile({
);
}
-const STAGE_LABEL: Record<StickerStage, string> = {
- generating: "Drawing…",
- cutting: "Cutting out…",
- saving: "Saving…",
-};
-
/**
* "Create a sticker": prompt → hosted image generation → background removal
* (the plain-backdrop knockout first, then matting) → white die-cut outline →
@@ -171,6 +168,8 @@ const STAGE_LABEL: Record<StickerStage, string> = {
* so the two read as one way of asking for a picture.
*/
export function CreateSticker({ projectId }: { projectId: string }) {
+ const t = useTranslations("media");
+ const describeError = useDescribeError();
const [prompt, setPrompt] = useState("");
const [refs, setRefs] = useState<AssetRef[]>([]);
const [stage, setStage] = useState<StickerStage | null>(null);
@@ -204,7 +203,7 @@ export function CreateSticker({ projectId }: { projectId: string }) {
setPrompt("");
setRefs([]);
} catch (err) {
- setError(err instanceof Error ? err.message : "Could not create the sticker.");
+ setError(describeError(err, t("stickers.createFailed")));
} finally {
setStage(null);
}
@@ -233,7 +232,7 @@ export function CreateSticker({ projectId }: { projectId: string }) {
/>
<MentionTextarea
className="min-h-[100px] w-full resize-y bg-transparent px-2.5 py-2 pr-9 text-[12.5px] leading-relaxed outline-none"
- placeholder="A corgi in sunglasses… Drop an image in or type @ to reference one."
+ placeholder={t("stickers.placeholder")}
value={prompt}
onChange={setPrompt}
candidates={candidates}
@@ -266,17 +265,19 @@ export function CreateSticker({ projectId }: { projectId: string }) {
) : (
<Sparkles data-icon="inline-start" />
)}
- {stage ? STAGE_LABEL[stage] : "Create sticker"}
+ {stage ? t(`stickers.stage.${stage}`) : t("stickers.create")}
</Button>
</div>
{signedIn === false && (
<p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- Generating runs on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("signInToGenerate", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
)}
diff --git a/site/src/cut/components/StockImagesPanel.tsx b/site/src/cut/components/StockImagesPanel.tsx
index dbb275d8..cf592b0a 100644
--- a/site/src/cut/components/StockImagesPanel.tsx
+++ b/site/src/cut/components/StockImagesPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import { useTranslations } from "next-intl";
import { ChevronLeft, ChevronRight, Maximize2, Search } from "lucide-react";
import { clearRefDrag, refFromStock, setRefDragData } from "@/cut/lib/assetRef";
import { useRefCopy } from "@/cut/lib/refCopy";
@@ -34,6 +35,7 @@ const chip = (active: boolean) =>
);
export function StockImagesPanel() {
+ const t = useTranslations("media");
const [view, setView] = useState<View>("all");
const [query, setQuery] = useState("");
@@ -52,7 +54,7 @@ export function StockImagesPanel() {
!q ||
item.prompt.toLowerCase().includes(q) ||
item.category.toLowerCase().includes(q) ||
- item.tags.some((t) => t.includes(q));
+ item.tags.some((tag) => tag.includes(q));
const stock = STOCK_IMAGES.filter(matches);
@@ -62,7 +64,7 @@ export function StockImagesPanel() {
<span className="flex min-w-0 items-center gap-1 text-sm font-semibold tracking-tight">
{view !== "all" && (
<button
- title="All stock images"
+ title={t("stockImages.allImages")}
className="grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground hover:text-foreground"
onClick={() => setView("all")}
>
@@ -70,7 +72,7 @@ export function StockImagesPanel() {
</button>
)}
<span className={cn("truncate", view === "all" && "pl-1.5")}>
- {view === "all" ? "Stock Images" : view}
+ {view === "all" ? t("stockImages.title") : t(`stockCategory.${view}`)}
</span>
</span>
</div>
@@ -80,7 +82,7 @@ export function StockImagesPanel() {
<Search className="size-3.5 shrink-0 text-muted-foreground" />
<input
className="w-full bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"
- placeholder="Search…"
+ placeholder={t("stockImages.search")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -88,11 +90,11 @@ export function StockImagesPanel() {
<div className="flex shrink-0 flex-wrap gap-1">
<button className={chip(view === "all")} onClick={() => setView("all")}>
- All
+ {t("stockImages.all")}
</button>
{STOCK_CATEGORIES.map((c) => (
<button key={c} className={chip(view === c)} onClick={() => setView(c)}>
- {c}
+ {t(`stockCategory.${c}`)}
</button>
))}
</div>
@@ -104,7 +106,7 @@ export function StockImagesPanel() {
if (items.length === 0) return null;
return (
<section key={c} className="shrink-0">
- <SectionHead title={c} onViewAll={items.length > 6 ? () => setView(c) : undefined} />
+ <SectionHead title={t(`stockCategory.${c}`)} onViewAll={items.length > 6 ? () => setView(c) : undefined} />
<div className="grid grid-cols-2 gap-1.5">
{items.slice(0, 6).map((i) => (
<StockTile key={i.id} item={i} />
@@ -135,6 +137,7 @@ export function StockImagesPanel() {
}
function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => void }) {
+ const t = useTranslations("media.stockImages");
return (
<div className="mb-1.5 flex items-center justify-between">
<span className="text-[12px] font-semibold">{title}</span>
@@ -143,7 +146,7 @@ function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => vo
className="flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground"
onClick={onViewAll}
>
- View all
+ {t("viewAll")}
<ChevronRight className="size-3" />
</button>
)}
@@ -155,6 +158,7 @@ function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => vo
* and it drags as an asset ref (chat attachment, generation reference). */
function StockTile({ item }: { item: StockImage }) {
const { flash, attachReveal } = useRevealFlash("stock", item.id);
+ const t = useTranslations("media.stockImages");
const copyRef = useRefCopy(() => [refFromStock(item)]);
return (
<div
@@ -191,7 +195,7 @@ function StockTile({ item }: { item: StockImage }) {
/>
<div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
<button
- title="Expand"
+ title={t("expand")}
className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"
onClick={() =>
useLightbox.getState().open({
@@ -213,5 +217,6 @@ function StockTile({ item }: { item: StockImage }) {
}
function Empty() {
- return <p className="text-[11px] text-muted-foreground">No matches.</p>;
+ const t = useTranslations("media.stockImages");
+ return <p className="text-[11px] text-muted-foreground">{t("noMatches")}</p>;
}
diff --git a/site/src/cut/components/StockMusicPanel.tsx b/site/src/cut/components/StockMusicPanel.tsx
index b5a1c756..299e3b8e 100644
--- a/site/src/cut/components/StockMusicPanel.tsx
+++ b/site/src/cut/components/StockMusicPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import { Pause, Play, Plus } from "lucide-react";
import { PeakStrip } from "@/cut/components/AudioPanel";
import { clearRefDrag, refFromStockMusic, setRefDragData } from "@/cut/lib/assetRef";
@@ -31,6 +32,7 @@ const remix = (s: StockMusic) =>
* loads its prompt into the generator, and it drags onto the timeline or the
* prompt box. */
export function SampleLibrary({ projectId }: { projectId: string }) {
+ const t = useTranslations("media");
// Its own handle on the app-wide preview player, so a sample and a generated
// row never play at once; leaving the tab silences this column's preview.
const playingUrl = usePreviewAudio((s) => s.url);
@@ -59,11 +61,11 @@ export function SampleLibrary({ projectId }: { projectId: string }) {
<div className="shrink-0 pt-4 pr-12 pb-3 pl-3.5">
<div className="flex flex-wrap gap-1.5">
<Chip active={cat === "all"} onClick={() => setCat("all")}>
- All
+ {t("stockMusic.all")}
</Chip>
{STOCK_MUSIC_CATEGORIES.map((c) => (
<Chip key={c} active={cat === c} onClick={() => setCat(c)}>
- {c}
+ {t(`musicCategory.${c}`)}
</Chip>
))}
</div>
@@ -71,7 +73,7 @@ export function SampleLibrary({ projectId }: { projectId: string }) {
<ScrollArea className="min-h-0 flex-1" contentClassName="flex flex-col gap-4 px-3.5 pb-4">
{sections.map(({ category, items }) => (
<div key={category} className="flex flex-col gap-2">
- <div className="text-[13px] font-semibold tracking-tight">{category}</div>
+ <div className="text-[13px] font-semibold tracking-tight">{t(`musicCategory.${category}`)}</div>
<div className="grid grid-cols-2 gap-2">
{items.map((s) => (
<SampleCard
@@ -116,6 +118,7 @@ function SampleCard({
onTogglePlay: () => void;
onAdd: () => void;
}) {
+ const t = useTranslations("media.stockMusic");
const copyRef = useRefCopy(() => [refFromStockMusic(sample)]);
return (
<div
@@ -128,7 +131,7 @@ function SampleCard({
}}
onDragEnd={clearRefDrag}
onClick={() => remix(sample)}
- title="Click to load its prompt · drag onto the timeline or the prompt box"
+ title={t("cardHint")}
>
<div className="relative h-14">
<PeakStrip
@@ -137,8 +140,8 @@ function SampleCard({
/>
<button
type="button"
- title={playing ? "Pause" : "Play"}
- aria-label={playing ? "Pause" : "Play"}
+ title={playing ? t("pause") : t("play")}
+ aria-label={playing ? t("pause") : t("play")}
onClick={(e) => {
e.stopPropagation();
onTogglePlay();
@@ -152,8 +155,8 @@ function SampleCard({
</span>
<button
type="button"
- title="Add at the playhead"
- aria-label="Add at the playhead"
+ title={t("addAtPlayhead")}
+ aria-label={t("addAtPlayhead")}
onClick={(e) => {
e.stopPropagation();
onAdd();
diff --git a/site/src/cut/components/StockVideosPanel.tsx b/site/src/cut/components/StockVideosPanel.tsx
index cf0f243a..6d483ec3 100644
--- a/site/src/cut/components/StockVideosPanel.tsx
+++ b/site/src/cut/components/StockVideosPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import { useTranslations } from "next-intl";
import { ChevronRight, Maximize2, Search } from "lucide-react";
import { clearRefDrag, refFromStockVideo, setRefDragData } from "@/cut/lib/assetRef";
import { useRefCopy } from "@/cut/lib/refCopy";
@@ -46,6 +47,7 @@ const chip = (active: boolean) =>
);
export function StockVideosPanel() {
+ const t = useTranslations("media");
const [view, setView] = useState<View>("root");
const [cat, setCat] = useState<"all" | StockCategory>("all");
const [query, setQuery] = useState("");
@@ -75,7 +77,7 @@ export function StockVideosPanel() {
!q ||
item.prompt.toLowerCase().includes(q) ||
item.category.toLowerCase().includes(q) ||
- item.tags.some((t) => t.includes(q));
+ item.tags.some((tag) => tag.includes(q));
// The root shows every section unfiltered; the query and category chips
// apply once drilled in.
@@ -88,11 +90,11 @@ export function StockVideosPanel() {
const chips = (
<div className="flex min-w-0 flex-wrap gap-1">
<button className={chip(cat === "all")} onClick={() => setCat("all")}>
- All
+ {t("stockVideos.all")}
</button>
{FOOTAGE_CATEGORIES.map((c) => (
<button key={c} className={chip(cat === c)} onClick={() => setCat(c)}>
- {c}
+ {t(`stockCategory.${c}`)}
</button>
))}
</div>
@@ -102,14 +104,14 @@ export function StockVideosPanel() {
<ScrollArea className="min-h-0 flex-1" contentClassName="flex flex-col gap-3 px-3.5 pt-3 pb-4">
{STOCK_VIDEOS.length === 0 ? (
<p className="text-[11px] leading-relaxed text-muted-foreground">
- No stock videos are bundled yet.
+ {t("stockVideos.empty")}
</p>
) : view === "root" ? (
<>
{characters.length > 0 && (
<section className="shrink-0">
<SectionHead
- title="Talking Characters"
+ title={t("stockVideos.characters")}
onViewAll={
characters.length > SECTION_PREVIEW ? () => go("characters") : undefined
}
@@ -119,7 +121,7 @@ export function StockVideosPanel() {
)}
<section className="mt-3 shrink-0">
<SectionHead
- title="Stock Videos"
+ title={t("stockVideos.videos")}
onViewAll={footage.length > SECTION_PREVIEW ? () => go("videos") : undefined}
/>
{footage.length > 0 ? (
@@ -132,14 +134,16 @@ export function StockVideosPanel() {
) : (
<>
<Crumb
- title={view === "characters" ? "Talking Characters" : "Stock Videos"}
+ title={view === "characters" ? t("stockVideos.characters") : t("stockVideos.videos")}
onBack={() => go("root")}
/>
<label className="flex shrink-0 items-center gap-2 rounded-lg border border-input px-2.5 py-1.5 focus-within:border-ring">
<Search className="size-3.5 shrink-0 text-muted-foreground" />
<input
className="w-full bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"
- placeholder={view === "characters" ? "Search characters…" : "Search videos…"}
+ placeholder={
+ view === "characters" ? t("stockVideos.searchCharacters") : t("stockVideos.searchVideos")
+ }
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -158,10 +162,11 @@ export function StockVideosPanel() {
/** Drilled-section header: a breadcrumb back to the root plus the title. */
function Crumb({ title, onBack }: { title: string; onBack: () => void }) {
+ const t = useTranslations("media.stockVideos");
return (
<div className="flex shrink-0 items-center gap-1 text-[12px]">
<button className="text-muted-foreground transition-colors hover:text-foreground" onClick={onBack}>
- All
+ {t("all")}
</button>
<ChevronRight className="size-3 text-muted-foreground" />
<span className="font-semibold">{title}</span>
@@ -187,12 +192,13 @@ function SectionHead({
}
function ViewAllButton({ onClick }: { onClick: () => void }) {
+ const t = useTranslations("media.stockVideos");
return (
<button
className="flex shrink-0 items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground"
onClick={onClick}
>
- View all
+ {t("viewAll")}
<ChevronRight className="size-3" />
</button>
);
@@ -214,6 +220,7 @@ function Grid({ items }: { items: StockVideo[] }) {
function StockTile({ item }: { item: StockVideo }) {
const { ref: videoRef, handlers: hoverPlay } = useHoverPlay(0);
const { flash, attachReveal } = useRevealFlash("stock", item.id);
+ const t = useTranslations("media.stockVideos");
const copyRef = useRefCopy(() => [refFromStockVideo(item)]);
return (
<div
@@ -254,7 +261,7 @@ function StockTile({ item }: { item: StockVideo }) {
</button>
{/* Clip lengths are single-digit seconds; "8s" reads better than "0:08". */}
<span className="pointer-events-none absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">
- {Math.round(item.duration)}s
+ {t("seconds", { count: Math.round(item.duration) })}
</span>
<RefHandlePill
token={`@${item.id}`}
@@ -262,7 +269,7 @@ function StockTile({ item }: { item: StockVideo }) {
/>
<div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
<button
- title="Expand"
+ title={t("expand")}
className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"
onClick={() =>
useLightbox.getState().open({
@@ -285,5 +292,6 @@ function StockTile({ item }: { item: StockVideo }) {
}
function Empty() {
- return <p className="text-[11px] text-muted-foreground">No matches.</p>;
+ const t = useTranslations("media.stockVideos");
+ return <p className="text-[11px] text-muted-foreground">{t("noMatches")}</p>;
}
diff --git a/site/src/cut/components/StoragePill.tsx b/site/src/cut/components/StoragePill.tsx
index f67e1eb3..9b3d5bc0 100644
--- a/site/src/cut/components/StoragePill.tsx
+++ b/site/src/cut/components/StoragePill.tsx
@@ -7,6 +7,7 @@
// lives).
import { type ReactNode } from "react";
import { Loader2 } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import {
Tooltip,
TooltipContent,
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
import { useAccountConfig } from "@/queries/accountConfig";
import { useOpenBillingPortal, useProSubscription } from "@/queries/billing";
import { formatBytes } from "@/lib/bytes";
+import type { Locale } from "@/i18n/locales";
const PILL =
"flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium shadow-xs transition-colors";
@@ -29,9 +31,9 @@ const PILL =
/** "278 / 250 MB" — the pill sits in a crowded top bar, so a unit is spelled
* out only where it carries information: repeat it just when the two numbers
* land on different ones ("1.2 GB / 250 MB"). */
-export function usageLabel(bytes: number, quotaBytes: number): string {
- const used = formatBytes(bytes);
- const cap = formatBytes(quotaBytes);
+export function usageLabel(bytes: number, quotaBytes: number, locale: Locale): string {
+ const used = formatBytes(bytes, locale);
+ const cap = formatBytes(quotaBytes, locale);
const unit = cap.slice(cap.lastIndexOf(" ") + 1);
const short = used.endsWith(` ${unit}`) ? used.slice(0, -(unit.length + 1)) : used;
return `${short} / ${cap}`;
@@ -44,6 +46,8 @@ export function StoragePill() {
}
function CloudStoragePill() {
+ const t = useTranslations("billing.storagePill");
+ const locale = useLocale();
const pro = useProSubscription();
// The meter has to move as media lands, so this reader is the polling one.
const usage = useCloudUsage(pro.data?.isActive === false, { poll: true });
@@ -62,7 +66,7 @@ function CloudStoragePill() {
config.data?.settings.proEndingNotice.daysBefore ?? SETTINGS.proEndingNotice.default.daysBefore;
if (days >= daysBefore) return null;
return (
- <PillTooltip message="Your Pro plan is set to cancel. Resume it to keep your cloud storage.">
+ <PillTooltip message={t("cancelTooltip")}>
<TooltipTrigger
className={cn(PILL, "text-muted-foreground hover:bg-muted hover:text-foreground")}
disabled={portal.isPending}
@@ -77,7 +81,7 @@ function CloudStoragePill() {
}}
>
{portal.isPending && <Loader2 className="size-3 animate-spin" />}
- Pro · {days === 0 ? "ends today" : `ends in ${days} day${days === 1 ? "" : "s"}`}
+ {t("ends", { days })}
</TooltipTrigger>
</PillTooltip>
);
@@ -90,10 +94,10 @@ function CloudStoragePill() {
// an over-quota account has to learn that uploads are being turned away, and
// that it is fixable, without clicking first.
const message = u.grace
- ? "Your Pro plan ended and you're over the free limit. Upgrade or free up space before your oldest projects are deleted."
+ ? t("graceTooltip")
: frac >= 1
- ? "You've run out of cloud storage. Upgrade or free up space to keep uploading."
- : `${formatBytes(u.bytes)} of ${formatBytes(u.quotaBytes)} of cloud storage used.`;
+ ? t("fullTooltip")
+ : t("usedTooltip", { used: formatBytes(u.bytes, locale), quota: formatBytes(u.quotaBytes, locale) });
return (
<PillTooltip message={message}>
<TooltipTrigger
@@ -113,7 +117,7 @@ function CloudStoragePill() {
});
}}
>
- {usageLabel(u.bytes, u.quotaBytes)}
+ {usageLabel(u.bytes, u.quotaBytes, locale)}
</TooltipTrigger>
</PillTooltip>
);
diff --git a/site/src/cut/components/StorageUpgradeDialog.tsx b/site/src/cut/components/StorageUpgradeDialog.tsx
index 90559e75..503c5745 100644
--- a/site/src/cut/components/StorageUpgradeDialog.tsx
+++ b/site/src/cut/components/StorageUpgradeDialog.tsx
@@ -5,6 +5,7 @@
// Pro storage tier — or just explains, when the account already has it.
import { useEffect, useState } from "react";
import { HardDrive, Loader2 } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -13,7 +14,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import { introTerms, wallBanner } from "./IntroOffer";
+import { useIntroTerms, wallBanner } from "./IntroOffer";
import { OfferButton, OfferDialog, OfferDismiss } from "./OfferDialog";
import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
import {
@@ -57,6 +58,9 @@ export function StorageUpgradeDialog() {
// Split so the billing query only runs while the dialog is up.
function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose: () => void }) {
+ const t = useTranslations("billing");
+ const locale = useLocale();
+ const introTerms = useIntroTerms();
const pro = useProSubscription();
const upgrade = useUpgradeToPro();
const isPro = pro.data?.isActive === true;
@@ -68,17 +72,18 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:
const bytes = detail.bytes ?? usage.data?.bytes;
const quotaBytes = detail.quotaBytes ?? usage.data?.quotaBytes ?? undefined;
- const used =
+ const meter =
bytes !== undefined && quotaBytes !== undefined
- ? `You've used ${formatBytes(bytes)} of ${formatBytes(quotaBytes)}.`
+ ? { used: formatBytes(bytes, locale), quota: formatBytes(quotaBytes, locale) }
: null;
- const title = detail.source === "pill" ? "Cloud storage" : "Cloud storage is full";
+ const used = meter ? t("storage.used", meter) : null;
+ const title = detail.source === "pill" ? t("storage.title") : t("storage.fullTitle");
const graceDays = detail.grace ? daysUntil(detail.grace.deadline) : null;
const grace =
detail.grace && graceDays !== null
- ? `Your Pro plan ended. Your oldest cloud projects will be deleted ${
- graceDays === 0 ? "today" : `in ${graceDays} day${graceDays === 1 ? "" : "s"}`
- } unless you upgrade or free ${formatBytes(detail.grace.overBytes)}.`
+ ? graceDays === 0
+ ? t("storage.graceToday", { bytes: formatBytes(detail.grace.overBytes, locale) })
+ : t("storage.graceDays", { bytes: formatBytes(detail.grace.overBytes, locale), days: graceDays })
: null;
// An account that already has Pro is being told something, not sold
@@ -93,11 +98,11 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:
</DialogHeader>
<div className="space-y-2 text-sm text-muted-foreground">
{used && <p>{used}</p>}
- <p>Free up space by deleting projects or media you no longer need.</p>
+ <p>{t("storage.proBody")}</p>
</div>
<DialogFooter className="mt-2">
<Button className="w-full" onClick={onClose}>
- OK
+ {t("ok")}
</Button>
</DialogFooter>
</DialogContent>
@@ -112,16 +117,16 @@ function OpenDialog({ detail, onClose }: { detail: StorageQuotaDetail; onClose:
banner={wallBanner(HardDrive, intro.data)}
closesAt={intro.data?.endsAt}
title={title}
- body={`${used ? `${used} ` : ""}Pro includes 100 GB of cloud storage.`}
- terms={intro.data ? introTerms(intro.data) : "Or free up space by deleting projects and media you no longer need."}
+ body={meter ? t("storage.bodyUsed", meter) : t("storage.body")}
+ terms={intro.data ? introTerms(intro.data) : t("storage.freeUpTerms")}
error={grace}
cta={
<OfferButton disabled={upgrade.isPending} onClick={upgrade.start}>
{upgrade.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Upgrade to Pro
+ {t("upgradeToPro")}
</OfferButton>
}
- secondary={<OfferDismiss onClick={onClose}>Not now</OfferDismiss>}
+ secondary={<OfferDismiss onClick={onClose}>{t("notNow")}</OfferDismiss>}
/>
);
}
diff --git a/site/src/cut/components/SubscribeBonusPill.tsx b/site/src/cut/components/SubscribeBonusPill.tsx
index e8e4ba47..dff05e18 100644
--- a/site/src/cut/components/SubscribeBonusPill.tsx
+++ b/site/src/cut/components/SubscribeBonusPill.tsx
@@ -8,7 +8,8 @@
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Gift } from "lucide-react";
-import { creditValidity, OfferButton, OfferDialog, OfferDismiss, subscribeOfferCopy } from "@/cut/components/OfferDialog";
+import { useFormatter, useLocale, useTranslations } from "next-intl";
+import { OfferButton, OfferDialog, OfferDismiss, useOfferCopy } from "@/cut/components/OfferDialog";
import { useEngineUser } from "@/cut/lib/backend/hooks";
import { useInvalidateOnSettle } from "@/cut/lib/hosted";
import { track } from "@/lib/analytics";
@@ -27,26 +28,39 @@ export function minutesLeft(closesAt: string, now: number): number {
}
/** "3d left" past the day, "5h left" past the hour, "40m left" inside it. */
-export function timeLeftLabel(minutes: number): string {
- if (minutes >= 24 * 60) return `${Math.floor(minutes / (24 * 60))}d left`;
- if (minutes >= 60) return `${Math.floor(minutes / 60)}h left`;
- return `${minutes}m left`;
+function timeLeftLabel(minutes: number, t: ReturnType<typeof useTranslations<"billing">>): string {
+ if (minutes >= 24 * 60) {
+ return t("subscribeBonus.daysLeft", { count: Math.floor(minutes / (24 * 60)) });
+ }
+ if (minutes >= 60) {
+ return t("subscribeBonus.hoursLeft", { count: Math.floor(minutes / 60) });
+ }
+ return t("subscribeBonus.minutesLeft", { count: minutes });
}
/** How long the landed credit lasts, as the sentence after the offer. */
-export function creditLifeClause(offer: { creditsExpireAt: string | null; creditsLifetimeDays: number | null }): string {
- const valid = creditValidity({ expiresAt: offer.creditsExpireAt, lifetimeDays: offer.creditsLifetimeDays });
- return valid ? ` ${valid}` : "";
+export function useCreditLifeClause(): (offer: {
+ creditsExpireAt: string | null;
+ creditsLifetimeDays: number | null;
+}) => string {
+ const { creditValidity } = useOfferCopy();
+ return (offer) => {
+ const valid = creditValidity({ expiresAt: offer.creditsExpireAt, lifetimeDays: offer.creditsLifetimeDays });
+ return valid ? ` ${valid}` : "";
+ };
}
-/** The deadline as people read it in their own clock: "Sep 8, 3:14 PM". */
-export function formatDeadline(closesAt: string): string {
- return new Date(closesAt).toLocaleString("en-US", {
- day: "numeric",
- hour: "numeric",
- minute: "2-digit",
- month: "short",
- });
+/** The deadline as people read it in their own clock and language:
+ * "Sep 8, 3:14 PM". */
+export function useFormatDeadline(): (closesAt: string) => string {
+ const format = useFormatter();
+ return (closesAt) =>
+ format.dateTime(new Date(closesAt), {
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ month: "short",
+ });
}
function seenBefore(offer: SubscribeBonus): boolean {
@@ -77,6 +91,9 @@ export function SubscribeBonusPill() {
}
function OpenOffer({ offer }: { offer: SubscribeBonus }) {
+ const t = useTranslations("billing");
+ const locale = useLocale();
+ const { subscribeOfferCopy } = useOfferCopy();
const queryClient = useQueryClient();
const checkout = useStartCheckout();
// A bonus the app made presents itself once: the first time a tab sees it
@@ -105,7 +122,8 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {
}, [minutes, queryClient]);
if (minutes === 0) return null;
- const credits = formatCredits(offer.dollars);
+ const credits = formatCredits(offer.dollars, locale);
+ const timeLeft = timeLeftLabel(minutes, t);
const subscribe = () => {
track("subscribe_bonus_checkout_started", {
dollars: Number(offer.dollars),
@@ -122,17 +140,17 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {
<button
type="button"
className={PILL}
- aria-label={`${credits} with Pro, ${timeLeftLabel(minutes)}`}
+ aria-label={t("subscribeBonus.pillLabel", { credits, timeLeft })}
onClick={() => setOpen(true)}
>
<Gift className="size-3.5" />
- {compactCredits(offer.dollars)} credits with Pro · {timeLeftLabel(minutes)}
+ {t("subscribeBonus.pill", { credits: compactCredits(offer.dollars, locale), timeLeft })}
</button>
<OfferDialog
open={open}
onOpenChange={setOpen}
banner="subscribe"
- title={`Get ${credits} with Pro`}
+ title={t("claim.withProTitle", { credits })}
closesAt={offer.closesAt}
{...subscribeOfferCopy({
credits,
@@ -141,11 +159,11 @@ function OpenOffer({ offer }: { offer: SubscribeBonus }) {
})}
cta={
<OfferButton disabled={checkout.isPending} onClick={subscribe}>
- {checkout.isPending ? "Starting…" : "Subscribe to Pro"}
+ {checkout.isPending ? t("subscribeBonus.starting") : t("subscribeToPro")}
</OfferButton>
}
- secondary={<OfferDismiss onClick={() => setOpen(false)}>Not now</OfferDismiss>}
- error={checkout.isError ? "Billing is unavailable right now." : null}
+ secondary={<OfferDismiss onClick={() => setOpen(false)}>{t("notNow")}</OfferDismiss>}
+ error={checkout.isError ? t("billingUnavailable") : null}
/>
</>
);
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index c143ec31..cd92eeef 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -1,6 +1,7 @@
"use client";
-import React, { memo, useEffect, useRef, useState } from "react";
+import React, { memo, useEffect, useMemo, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
import { AlertCircle, Captions, ChevronDown, Languages, Loader2, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
@@ -56,21 +57,37 @@ import {
WORD_SWELL_MAX,
WORD_SWELL_MIN,
} from "@donkeycut/effects-kit";
+import { useDescribeError } from "@/i18n/describeError";
+import type { ErrorFields } from "@/cut/lib/userError";
+import { useLabels } from "@/i18n/labels";
+// The languages a caption track can be transcribed in, in picker order. Each
+// is named in the page's language (useLanguageName).
const LOCALES = [
- ["en-US", "English (US)"],
- ["en-GB", "English (UK)"],
- ["es-ES", "Español"],
- ["fr-FR", "Français"],
- ["de-DE", "Deutsch"],
- ["it-IT", "Italiano"],
- ["pt-BR", "Português (BR)"],
- ["ja-JP", "日本語"],
- ["ko-KR", "한국어"],
- ["zh-CN", "中文"],
- ["vi-VN", "Tiếng Việt"],
+ "en-US",
+ "en-GB",
+ "es-ES",
+ "fr-FR",
+ "de-DE",
+ "it-IT",
+ "pt-BR",
+ "ja-JP",
+ "ko-KR",
+ "zh-CN",
+ "vi-VN",
] as const;
+/** Names a language code in the page's language: "en-GB" reads "English
+ * (UK)" on an English page and "Englisch (UK)" on a German one. */
+function useLanguageName(): (code: string) => string {
+ const uiLocale = useLocale();
+ const names = useMemo(
+ () => new Intl.DisplayNames([uiLocale], { type: "language", languageDisplay: "standard", style: "short" }),
+ [uiLocale]
+ );
+ return (code) => names.of(code) ?? code;
+}
+
/** Give the cue track room when it appears. */
const TIMELINE_H_WITH_SUBS = Math.max(TIMELINE_H_MIN, 276);
@@ -86,18 +103,24 @@ function laneLabel(subs: SubtitlesBlock, lane: number): string {
return trackLocale(subs, lane).split("-")[0].toUpperCase();
}
-/** A track's language name from the locale picker list, else its short code. */
-function laneLanguage(subs: SubtitlesBlock, lane: number): string {
- return LOCALES.find(([id]) => id === trackLocale(subs, lane))?.[1] ?? laneLabel(subs, lane);
+/** A track's language name when the locale picker lists it, else its short code. */
+function laneLanguage(subs: SubtitlesBlock, lane: number, languageName: (code: string) => string): string {
+ const locale = trackLocale(subs, lane);
+ if (!(LOCALES as readonly string[]).includes(locale)) {
+ return laneLabel(subs, lane);
+ }
+ return languageName(locale);
}
export function SubtitlesPanel() {
+ const t = useTranslations("panels.subtitles");
+ const describeError = useDescribeError();
const caps = useCutCaps();
const readOnly = useEditor((s) => s.readOnly);
const subtitles = useEditor((s) => s.subtitles);
const lane = useEditor((s) => s.subtitleLane);
const status = useEditor((s) => s.subtitleStatus);
- const error = useEditor((s) => s.subtitleError);
+ const error = useEditor((s) => s.subtitleFailure ?? s.subtitleError);
const activeCues = laneCues(subtitles, lane);
const hasCues = activeCues.length > 0;
// The open tab holds for the session, so leaving the panel and coming back
@@ -137,13 +160,13 @@ export function SubtitlesPanel() {
return (
<>
<div className="flex h-12 shrink-0 items-center pl-4">
- <span className="text-sm font-semibold tracking-tight">Subtitles</span>
+ <span className="text-sm font-semibold tracking-tight">{t("title")}</span>
</div>
{hasCues ? (
<Transcript cues={activeCues} />
) : (
<p className="px-4 text-[11px] leading-relaxed text-muted-foreground">
- No subtitles yet.
+ {t("noSubtitles")}
</p>
)}
</>
@@ -157,9 +180,9 @@ export function SubtitlesPanel() {
<div className="sub-tabs flex items-center gap-3.5">
{(
[
- ["content", "Content"],
- ["styles", "Styles"],
- ["options", "Options"],
+ ["content", t("tabs.content")],
+ ["styles", t("tabs.styles")],
+ ["options", t("tabs.options")],
] as const
).map(([id, label], i) => (
<React.Fragment key={id}>
@@ -178,7 +201,7 @@ export function SubtitlesPanel() {
))}
</div>
) : (
- <span className="text-sm font-semibold tracking-tight">Subtitles</span>
+ <span className="text-sm font-semibold tracking-tight">{t("title")}</span>
)}
</div>
@@ -192,7 +215,7 @@ export function SubtitlesPanel() {
variant="ghost"
size="sm"
className="sub-regenerate"
- title="Transcribe the cut again (replaces these captions — undoable)"
+ title={t("regenerateHint")}
disabled={status === "running"}
onClick={generate}
>
@@ -201,14 +224,14 @@ export function SubtitlesPanel() {
) : (
<RefreshCw />
)}
- Regenerate
+ {t("regenerate")}
</Button>
</div>
)}
<Transcript cues={activeCues} />
{status === "error" && error && (
<p className="sub-error shrink-0 border-t border-border px-4 py-2.5 text-[11px] leading-relaxed text-red-600">
- {error}
+ {describeError(error)}
</p>
)}
</>
@@ -225,11 +248,13 @@ export function SubtitlesPanel() {
* its color, position reset for a dragged caption, and the subtitle-voiceover
* generator. */
function OptionsTab() {
+ const t = useTranslations("panels.subtitles");
+ const wordEffectLabel = useLabels("wordEffect");
const subtitles = useEditor((s) => s.subtitles);
const moved =
subtitles.x !== undefined ||
subtitles.y !== undefined ||
- !!subtitles.tracks?.some((t) => t.x !== undefined || t.y !== undefined);
+ !!subtitles.tracks?.some((track) => track.x !== undefined || track.y !== undefined);
// Effective word effect: the caption style's defaults with the user's
// overrides on top, so the controls always show what's on the video.
const words = captionWords(captionStyle(subtitles.style), subtitles);
@@ -248,7 +273,7 @@ function OptionsTab() {
<GenerateSubtitlesAudio />
</div>
<label className="flex min-h-8 items-center justify-between text-xs font-medium">
- Show subtitles
+ {t("showSubtitles")}
<Switch
className="sub-show"
checked={subtitles.showOnVideo || subtitles.showOnTimeline}
@@ -260,7 +285,7 @@ function OptionsTab() {
/>
</label>
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Font
+ {t("font")}
<FontPicker
className="sub-font w-28"
value={subtitles.font ?? captionStyle(subtitles.style).font}
@@ -268,10 +293,10 @@ function OptionsTab() {
/>
</div>
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Size
+ {t("size")}
<div className="sub-size flex items-center gap-2">
<ValueSlider
- label="Caption size"
+ label={t("captionSize")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-7 text-muted-foreground"
value={subtitles.size ?? captionStyle(subtitles.style).size}
@@ -288,15 +313,15 @@ function OptionsTab() {
</div>
<WordsPerCueRow />
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Word effect
+ {t("wordEffect")}
<PillSelect
className="sub-word-highlight w-36"
- title="Word effect"
+ title={t("wordEffect")}
value={on ? words.style : "none"}
- display={on ? wordEffect(words.style).label : "None"}
+ display={on ? wordEffectLabel(WORD_EFFECT_MENU.find((m) => m.id === words.style)?.id ?? "color") : t("none")}
options={[
- { value: "none", label: "None" },
- ...WORD_EFFECT_MENU.map((m) => ({ value: m.id, label: m.label })),
+ { value: "none", label: t("none") },
+ ...WORD_EFFECT_MENU.map((m) => ({ value: m.id, label: wordEffectLabel(m.id) })),
]}
onChange={(v) =>
useEditor.getState().setSubtitlesView(
@@ -309,10 +334,10 @@ function OptionsTab() {
</div>
{on && knobs.size && (
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Word size
+ {t("wordSize")}
<div className="sub-accent-scale flex items-center gap-2">
<ValueSlider
- label="Word size"
+ label={t("wordSize")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={wordSwell(words)}
@@ -330,10 +355,10 @@ function OptionsTab() {
)}
{on && knobs.dim && (
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Faded to
+ {t("fadedTo")}
<div className="sub-accent-dim flex items-center gap-2">
<ValueSlider
- label="Faded to"
+ label={t("fadedTo")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={wordDim(words)}
@@ -351,11 +376,11 @@ function OptionsTab() {
)}
{on && knobs.color && (
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Word color
+ {t("wordColor")}
<div className="sub-accent-color flex items-center">
<ColorField
value={wordAccent(words, captionStyle(subtitles.style).color)}
- label="Word color"
+ label={t("wordColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => useEditor.getState().setSubtitlesView({ accentColor: c })}
onCommit={(c) => useEditor.getState().setSubtitlesView({ accentColor: c })}
@@ -365,7 +390,7 @@ function OptionsTab() {
)}
<EmphasisRows />
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Position
+ {t("position")}
<Button
variant="outline"
size="sm"
@@ -379,11 +404,11 @@ function OptionsTab() {
);
}}
>
- Reset
+ {t("reset")}
</Button>
</div>
<p className="sub-position-hint -mt-1 text-[11px] leading-relaxed text-muted-foreground">
- Drag the caption on the video to reposition every subtitle.
+ {t("positionHint")}
</p>
</ScrollArea>
);
@@ -392,6 +417,7 @@ function OptionsTab() {
/** The emphasis style: how the words set apart in the transcript look on the
* video. The words themselves are picked in the Content tab. */
function EmphasisRows() {
+ const t = useTranslations("panels.subtitles");
const subtitles = useEditor((s) => s.subtitles);
const em = captionEmphasis(subtitles);
const set = (patch: Parameters<ReturnType<typeof useEditor.getState>["setSubtitlesView"]>[0]) =>
@@ -399,7 +425,7 @@ function EmphasisRows() {
return (
<div className="sub-emphasis mt-1 flex flex-col gap-2.5 border-t border-border pt-3">
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Emphasis font
+ {t("emphasisFont")}
<FontPicker
className="sub-emphasis-font w-28"
value={em.font}
@@ -410,11 +436,11 @@ function EmphasisRows() {
/>
</div>
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Emphasis color
+ {t("emphasisColor")}
<div className="sub-emphasis-color flex items-center">
<ColorField
value={em.color}
- label="Emphasis color"
+ label={t("emphasisColor")}
onBegin={() => useEditor.getState().pushHistory()}
onLive={(c) => set({ emphasisColor: c })}
onCommit={(c) => set({ emphasisColor: c })}
@@ -422,7 +448,7 @@ function EmphasisRows() {
</div>
</div>
<label className="flex min-h-8 items-center justify-between text-xs font-medium">
- Italic
+ {t("italic")}
<Switch
className="sub-emphasis-italic"
checked={em.italic}
@@ -433,7 +459,7 @@ function EmphasisRows() {
/>
</label>
<label className="flex min-h-8 items-center justify-between text-xs font-medium">
- Bold
+ {t("bold")}
<Switch
className="sub-emphasis-weight"
checked={em.weight >= 700}
@@ -444,10 +470,10 @@ function EmphasisRows() {
/>
</label>
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Emphasis size
+ {t("emphasisSize")}
<div className="sub-emphasis-scale flex items-center gap-2">
<ValueSlider
- label="Emphasis size"
+ label={t("emphasisSize")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={em.scale}
@@ -463,8 +489,7 @@ function EmphasisRows() {
</div>
</div>
<p className="-mt-1 text-[11px] leading-relaxed text-muted-foreground">
- Right-click a word in the transcript, or put the cursor on it and press ⌘B, to set it
- apart in this style.
+ {t("emphasisHint", { key: "⌘B" })}
</p>
</div>
);
@@ -475,17 +500,18 @@ function EmphasisRows() {
* takes a moment on a long project — the slider shows the drag, the track is
* re-cut once on release. */
function WordsPerCueRow() {
+ const t = useTranslations("panels.subtitles");
const subtitles = useEditor((s) => s.subtitles);
const [draft, setDraft] = useState<number | null>(null);
const [working, setWorking] = useState(false);
const value = draft ?? cueWordCount(subtitles);
return (
<div className="flex min-h-8 items-center justify-between text-xs font-medium">
- Words at a time
+ {t("wordsAtATime")}
<div className="sub-words-per-cue flex items-center gap-2">
{working && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
<ValueSlider
- label="Words at a time"
+ label={t("wordsAtATime")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-7 text-muted-foreground"
value={value}
@@ -516,6 +542,7 @@ function WordsPerCueRow() {
/** The Styles tab: the caption style list, each option rendered as a live
* preview of that look. */
function StylesTab() {
+ const t = useTranslations("panels.subtitles");
const subtitles = useEditor((s) => s.subtitles);
const style = subtitles.style ?? "clean";
@@ -555,10 +582,10 @@ function StylesTab() {
borderRadius: cs.plate ? `${PLATE_RADIUS}em` : undefined,
}}
>
- Your caption
+ {t("sampleCaption")}
</span>
</div>
- <div className="px-1 pt-1 pb-0.5 text-[11px] font-medium">{cs.label}</div>
+ <div className="px-1 pt-1 pb-0.5 text-[11px] font-medium">{t(`captionStyles.${cs.id}`)}</div>
</button>
))}
</div>
@@ -573,10 +600,13 @@ function EmptyState({
onTranslate,
}: {
status: string;
- error: string | null;
+ error: ErrorFields | string | null;
onGenerate: () => void;
onTranslate: (fromLane: number) => void;
}) {
+ const t = useTranslations("panels.subtitles");
+ const describeError = useDescribeError();
+ const languageName = useLanguageName();
const caps = useCutCaps();
const subtitles = useEditor((s) => s.subtitles);
const lane = useEditor((s) => s.subtitleLane);
@@ -594,12 +624,11 @@ function EmptyState({
<div className="sub-generating flex flex-col items-center gap-3 px-6 pt-10 text-center">
<Loader2 className="size-5 animate-spin text-muted-foreground" />
<p className="text-[13px] font-medium">
- {translating ? "Translating your captions…" : "Transcribing…"}{" "}
+ {translating ? t("translating") : t("transcribing")}{" "}
<SubtitleElapsed />
</p>
<p className="text-[11.5px] leading-relaxed text-muted-foreground">
- Runs in the background — keep editing. Captions appear here when
- it finishes.
+ {t("runsInBackground")}
</p>
</div>
);
@@ -609,14 +638,13 @@ function EmptyState({
<div className="flex flex-col gap-3 px-3.5">
{status === "empty" && (
<p className="sub-empty pt-1 text-[11.5px] leading-relaxed text-muted-foreground">
- No speech was found in this cut, so no subtitles were added to the
- video.
+ {t("noSpeech")}
</p>
)}
{status === "error" && error && (
<div className="sub-error flex items-start gap-2 rounded-lg bg-red-50 px-3 py-2.5 text-[11.5px] leading-relaxed text-red-700">
<AlertCircle className="mt-0.5 size-3.5 shrink-0" />
- {error}
+ {describeError(error)}
</div>
)}
<div className="relative">
@@ -628,9 +656,9 @@ function EmptyState({
s.setSubtitleTrackMeta(s.subtitleLane, { locale: e.target.value });
}}
>
- {LOCALES.map(([id, label]) => (
+ {LOCALES.map((id) => (
<option key={id} value={id}>
- {label}
+ {languageName(id)}
</option>
))}
</select>
@@ -640,10 +668,10 @@ function EmptyState({
<Button
className="sub-generate w-full"
onClick={onGenerate}
- title="Transcribe your audio into plain captions, word for word"
+ title={t("generateHint")}
>
<Captions data-icon="inline-start" />
- {status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}
+ {status === "empty" || status === "error" ? t("tryAgain") : t("generate")}
</Button>
)}
{caps.captionAi &&
@@ -652,13 +680,14 @@ function EmptyState({
key={i}
variant="outline"
className="sub-translate w-full"
- title={`Write this track by translating the ${laneLanguage(subtitles, i)} captions into ${
- LOCALES.find(([id]) => id === locale)?.[1] ?? locale
- }`}
+ title={t("translateHint", {
+ from: laneLanguage(subtitles, i, languageName),
+ to: (LOCALES as readonly string[]).includes(locale) ? languageName(locale) : locale,
+ })}
onClick={() => onTranslate(i)}
>
<Languages data-icon="inline-start" />
- Translate from {laneLanguage(subtitles, i)}
+ {t("translateFrom", { language: laneLanguage(subtitles, i, languageName) })}
</Button>
))}
</div>
@@ -773,7 +802,8 @@ function caretOffset(el: HTMLElement): number {
}
const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: number }) {
- const active = usePreviewSelector((t) => t >= cue.start && t < cue.end);
+ const t = useTranslations("panels.subtitles");
+ const active = usePreviewSelector((at) => at >= cue.start && at < cue.end);
const readOnly = useEditor((s) => s.readOnly);
const ref = useRef<HTMLSpanElement>(null);
const [focused, setFocused] = useState(false);
@@ -838,9 +868,9 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
{gap > 0.5 && (
<span
className="sub-gap mx-0.5 inline-block rounded-md bg-muted px-1.5 py-px align-baseline font-mono text-[10px] text-muted-foreground/80"
- title={`${gap.toFixed(1)}s pause`}
+ title={t("pause", { seconds: gap.toFixed(1) })}
>
- ·&thinsp;{gap.toFixed(1)}s&thinsp;·
+ {`·\u2009${gap.toFixed(1)}s\u2009·`}
</span>
)}
<button
@@ -848,7 +878,7 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
"sub-time mr-1 inline-block cursor-pointer rounded-md bg-muted px-1.5 py-px align-baseline font-mono text-[10px] tabular-nums text-muted-foreground transition-colors hover:bg-[#0a84ff]/15 hover:text-[#0a84ff]",
active && "bg-[#0a84ff] text-white hover:bg-[#0a84ff] hover:text-white"
)}
- title="Jump here"
+ title={t("jumpHere")}
tabIndex={-1}
onClick={() => useEditor.getState().seek(cue.start + 0.001)}
>
@@ -929,7 +959,7 @@ const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: num
}}
>
<span className="truncate">
- {menu.on ? `Emphasize “${menu.label}”` : `Remove emphasis from “${menu.label}”`}
+ {menu.on ? t("emphasize", { words: menu.label }) : t("removeEmphasis", { words: menu.label })}
</span>
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsx
index 48064003..fe9eca34 100644
--- a/site/src/cut/components/TemplateCard.tsx
+++ b/site/src/cut/components/TemplateCard.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import { useTranslations } from "next-intl";
import {
Captions,
ChevronDown,
@@ -28,11 +29,10 @@ import { CardActionsMenu } from "@/cut/components/CardActionsMenu";
import { cardIconButton } from "@/cut/components/iconButton";
import { formatTime } from "@/cut/lib/time";
import {
- EFFECT_LABELS,
retimeOf,
type SpeedNode,
} from "@donkeycut/effects-kit";
-import { SHAPE_LABELS } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
import type { LibraryTemplate, TemplateMedia } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { PICKED_RING } from "@/cut/lib/assetPick";
@@ -87,6 +87,9 @@ export function TemplateCard({
* filling its grid cell with "fill". Absent, the card is a row. */
tile?: number | "fill";
}) {
+ const tc = useTranslations("media.templateCard");
+ const shapeLabel = useLabels("shape");
+ const effectLabel = useLabels("effect");
const refDrop = useAssetDrop((r) => onRefDrop?.(r));
// ⌘C over the card copies its mention token, so a saved arrangement can be
// named in a prompt the same way a clip or an effect is.
@@ -122,13 +125,13 @@ export function TemplateCard({
}[] = [
...t.layers.map((l) => ({
icon: t.media[l.media]?.type === "image" ? ImageIcon : Film,
- label: t.media[l.media]?.name ?? "Media",
+ label: t.media[l.media]?.name ?? tc("media"),
time: speedLen(l),
media: t.media[l.media],
})),
...t.audio.map((a) => ({
icon: Music,
- label: t.media[a.media]?.name ?? "Audio",
+ label: t.media[a.media]?.name ?? tc("audio"),
time: speedLen(a),
media: t.media[a.media],
})),
@@ -136,19 +139,19 @@ export function TemplateCard({
icon: Type,
label:
o.kind === "shape"
- ? SHAPE_LABELS[o.shape]
+ ? shapeLabel(o.shape)
: o.kind === "sticker"
- ? "Sticker"
+ ? tc("sticker")
: o.kind === "effect"
- ? EFFECT_LABELS[o.effect]
- : o.text || "Title",
+ ? effectLabel(o.effect)
+ : o.text || tc("title"),
time: o.end - o.start,
})),
...(t.cues.length
? [
{
icon: Captions,
- label: `${t.cues.length} caption${t.cues.length === 1 ? "" : "s"}`,
+ label: tc("captions", { count: t.cues.length }),
},
]
: []),
@@ -167,8 +170,7 @@ export function TemplateCard({
);
const metaEl = (
<div className="flex items-center gap-0.5 text-[10.5px] whitespace-nowrap text-muted-foreground">
- {formatTime(t.duration)} · {itemCount} item
- {itemCount === 1 ? "" : "s"}
+ {tc("meta", { duration: formatTime(t.duration), count: itemCount })}
<ChevronDown
className={cn("size-3 transition-transform", expanded && "rotate-180")}
/>
@@ -176,12 +178,12 @@ export function TemplateCard({
);
const actionsEl = (
<CardActionsMenu
- label="Template options"
+ label={tc("options")}
// A tile floats the scrim pill in its corner; a light row takes the
// row's own control.
className={tile ? "absolute top-1.5 right-1.5" : cardIconButton}
onUse={onAdd}
- useTitle={addTitle ?? "Add"}
+ useTitle={addTitle ?? tc("add")}
onRename={onRename && (() => setRenaming(true))}
extra={extraMenu}
onDelete={onDelete}
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 78b47b7e..2d214d8a 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -2,6 +2,7 @@
import { TimelineActionButton } from "@/cut/components/TimelineActionButton";
import { TimelineGroupActions } from "@/cut/components/TimelineGroupActions";
+import { useTranslations } from "next-intl";
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { ArrowDownToLine, AudioLines, Check, Clapperboard, Copy, Diamond, Download, EllipsisVertical, Eye, EyeOff, FolderOpen, FolderPlus, Fullscreen, Loader2, Magnet, MoreHorizontal, PanelBottomClose, Pause, Play, Scissors, SkipBack, Sticker, Trash2, Type, Volume2, VolumeX } from "lucide-react";
import { EFFECT_CHIP_ICONS, effectIconKind, SHAPE_CHIP_ICONS, TRANSITION_ICONS } from "@/cut/components/entityIcons";
@@ -67,12 +68,13 @@ import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";
import { cardMatteKey } from "@/cut/lib/cameraCard";
import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
-import { EFFECT_LABELS, hasSpeedCurve, headSrc, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, tailSrc, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
+import { hasSpeedCurve, headSrc, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, tailSrc, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
import { BLOCK_COLOR } from "@/cut/lib/blockSource";
-import { isLinkedAssetType, assetIsSilent, previewUrl, emptySubtitles, fontStack, IMAGE_CLIP_SECONDS, isAudioTransition, clipName, isTextOverlay, overlayName, SHAPE_LABELS, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, XBAR_MAGNET_PX, type ShapeKind } from "@/cut/lib/types";
+import { isLinkedAssetType, assetIsSilent, previewUrl, emptySubtitles, fontStack, IMAGE_CLIP_SECONDS, isAudioTransition, clipName, isTextOverlay, overlayName, transitionBarStart, transitionDefaultSeconds, XBAR_MAGNET_PX, type ShapeKind } from "@/cut/lib/types";
import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionBoundaryKind, TransitionStyle, VideoClip } from "@/cut/lib/types";
import { isLottieAsset } from "@/cut/lib/lottieAssets";
import { gradeCssApprox, normalizeGrade } from "@donkeycut/effects-kit";
+import { useLabels } from "@/i18n/labels";
import { cn } from "@/lib/utils";
/**
@@ -277,12 +279,11 @@ type OverlayFamily = "text" | "element" | "effect";
* (`anchorLen`), since a cross dissolve wants a shorter one than a blend. */
type Anchor = { kind: "cut" | "in" | "out"; clipId: string; at: number; len: number };
-/** One transition bar drawn on the row: the store object itself, the place it
- * resolved to (null while it sits inert), and how it reads. */
+/** One transition bar drawn on the row: the store object itself and the place
+ * it resolved to (null while it sits inert). */
type XBar = {
t: TimelineTransition;
role: { kind: Anchor["kind"]; clipId: string } | null;
- label: string;
};
@@ -563,6 +564,10 @@ function carriedMedia(e: React.DragEvent): CarriedMedia[] {
}
export function Timeline() {
+ const tr = useTranslations("timeline.main");
+ const transitionLabel = useLabels("transition");
+ const shapeLabel = useLabels("shape");
+ const effectLabel = useLabels("effect");
const clips = useEditor((s) => s.clips);
const audioClips = useEditor((s) => s.audioClips);
// The composited layers (every clip off track 0), derived from the one
@@ -1267,15 +1272,25 @@ export function Timeline() {
// A bar can play several same-instant boundaries; the rank-first
// one names it on the row.
const role = barRoles.get(t.id)?.[0] ?? null;
- const base = TRANSITION_STYLE_LABELS[t.style];
- const label =
- role?.kind === "in" ? `${base} in` : role?.kind === "out" ? `${base} out` : base;
- return { t, role, label };
+ return { t, role };
})
.sort((a, b) => a.t.start - b.t.start),
[bars, barRoles]
);
+ /** How a bar reads on the row: its style, and the edge it plays when it
+ * plays one, e.g. "Cross fade in". */
+ const barLabel = (x: XBar) => {
+ const name = transitionLabel(x.t.style);
+ if (x.role?.kind === "in") {
+ return tr("transitionIn", { name });
+ }
+ if (x.role?.kind === "out") {
+ return tr("transitionOut", { name });
+ }
+ return name;
+ };
+
/** The room a bar of `style` takes at this anchor: whatever already plays
* there, or that style's own default length. */
const anchorLen = (a: Anchor, style: TransitionStyle) =>
@@ -2202,7 +2217,7 @@ export function Timeline() {
>
<div
className="tl-resize absolute inset-x-0 top-0 z-30 h-1.5 cursor-row-resize"
- title="Drag to resize the timeline"
+ title={tr("resize")}
onPointerDown={resize}
/>
{/* Three tracks with the transport in the middle, so playback sits centred
@@ -2261,11 +2276,11 @@ export function Timeline() {
max={100}
step={0.1}
value={zoomToSlider(pps, zoomMin)}
- aria-label="Zoom"
+ aria-label={tr("zoom")}
onValueChange={(v) => zoomTo(sliderToZoom(Number(v), zoomMin))}
/>
- <Button variant="ghost" size="sm" title="Fit timeline to window" onClick={fit}>
- Fit
+ <Button variant="ghost" size="sm" title={tr("fitTitle")} onClick={fit}>
+ {tr("fit")}
</Button>
<HideTimelineButton />
</div>
@@ -2422,12 +2437,12 @@ export function Timeline() {
const Icon = SHAPE_CHIP_ICONS[el.shape];
return <Icon className="mr-1 size-2.5 shrink-0" />;
})()}
- {SHAPE_LABELS[el.shape]}
+ {shapeLabel(el.shape)}
</>
) : el?.kind === "effect" ? (
<>
<EffectChipIcon effect={el.effect} />
- {EFFECT_LABELS[el.effect]}
+ {effectLabel(el.effect)}
</>
) : (
<>
@@ -2441,7 +2456,7 @@ export function Timeline() {
) : (
<Sticker className="mr-1 size-2.5 shrink-0" />
)}
- Sticker
+ {tr("sticker")}
</>
);
return (
@@ -2581,12 +2596,13 @@ export function Timeline() {
const drag = laneDragFor(laneDrag, "transition", x.t.id);
const Icon = TRANSITION_ICONS[x.t.style];
const playing = !!x.role;
+ const label = barLabel(x);
return (
<div
key={x.t.id}
role="button"
tabIndex={0}
- title={`${x.label} ${x.t.seconds.toFixed(1)}s — drag it anywhere along the row; it plays where it lines up with a cut or a clip edge`}
+ title={tr("transitionTitle", { name: label, seconds: x.t.seconds.toFixed(1) })}
className={cn(
"tl-xfade-bar group absolute flex cursor-grab items-center gap-1 overflow-hidden rounded-[3px] px-1.5 text-[10.5px] font-medium text-white shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",
// A parked bar reads muted: it is on the row but playing
@@ -2611,7 +2627,7 @@ export function Timeline() {
}}
>
<Icon className="size-2.5 shrink-0" />
- <span className="truncate">{x.label}</span>
+ <span className="truncate">{label}</span>
<HideChip
hidden={!!x.t.hidden}
small
@@ -2625,7 +2641,7 @@ export function Timeline() {
{(["l", "r"] as const).map((side) => (
<span
key={side}
- title="Drag to trim"
+ title={tr("dragToTrim")}
className={cn(trimHandle, side === "l" ? "tl-trim-l left-0" : "tl-trim-r right-0")}
onPointerDown={(e) => trimTransition(e, x, side)}
/>
@@ -3122,7 +3138,7 @@ export function Timeline() {
setGapMenu(null);
}}
>
- <Scissors className="size-3.5 text-muted-foreground" /> Remove empty space
+ <Scissors className="size-3.5 text-muted-foreground" /> {tr("removeEmptySpace")}
</DropdownMenuItem>
</DropdownMenuContent>
)}
@@ -3151,7 +3167,7 @@ export function Timeline() {
setBarMenu(null);
}}
>
- <Diamond className="size-3.5 text-muted-foreground" /> Remove keyframe
+ <Diamond className="size-3.5 text-muted-foreground" /> {tr("removeKeyframe")}
</DropdownMenuItem>
)}
<DropdownMenuItem
@@ -3165,11 +3181,11 @@ export function Timeline() {
>
{o.hidden ? (
<>
- <Eye className="size-3.5 text-muted-foreground" /> Show
+ <Eye className="size-3.5 text-muted-foreground" /> {tr("show")}
</>
) : (
<>
- <EyeOff className="size-3.5 text-muted-foreground" /> Hide
+ <EyeOff className="size-3.5 text-muted-foreground" /> {tr("hide")}
</>
)}
</DropdownMenuItem>
@@ -3200,7 +3216,7 @@ export function Timeline() {
setFrameMenu(null);
}}
>
- <Fullscreen className="size-3.5 text-muted-foreground" /> Capture frame
+ <Fullscreen className="size-3.5 text-muted-foreground" /> {tr("captureFrame")}
</button>
<button
className="flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm whitespace-nowrap hover:bg-accent hover:text-accent-foreground"
@@ -3212,7 +3228,7 @@ export function Timeline() {
setFrameMenu(null);
}}
>
- <Copy className="size-3.5 text-muted-foreground" /> Copy frame
+ <Copy className="size-3.5 text-muted-foreground" /> {tr("copyFrame")}
</button>
</div>
{/* Drawn after the bubble so the diamond's inner half covers
@@ -3389,6 +3405,7 @@ function TimelineTools({
deleteSelection: () => void;
selectionCount: number;
}) {
+ const tr = useTranslations("timeline.toolbar");
const splitEnabled = useSplitEnabled();
const readOnly = useEditor((s) => s.readOnly);
const magnet = useEditor((s) => s.magnet);
@@ -3396,22 +3413,22 @@ function TimelineTools({
if (readOnly) return null;
return (
<>
- <TimelineActionButton label="Text" tooltip="Text (T)" onClick={addText}><Type /></TimelineActionButton>
+ <TimelineActionButton label={tr("text")} tooltip={tr("textTooltip", { key: "T" })} onClick={addText}><Type /></TimelineActionButton>
<SaveSelectionButton />
<div role="separator" aria-orientation="vertical" className="mx-1 h-4 w-px shrink-0 bg-border" />
<TimelineActionButton
- label="Magnet"
- tooltip={magnet ? "Magnet on: track 0 closes up" : "Magnet: close up track 0"}
+ label={tr("magnet")}
+ tooltip={magnet ? tr("magnetOn") : tr("magnetOff")}
pressed={magnet}
onClick={toggleMagnet}
>
<Magnet />
</TimelineActionButton>
{splitEnabled && (
- <TimelineActionButton label="Split" tooltip="Split at pointer, or at playhead (⌘B or S)" onClick={split}><Scissors /></TimelineActionButton>
+ <TimelineActionButton label={tr("split")} tooltip={tr("splitTooltip")} onClick={split}><Scissors /></TimelineActionButton>
)}
{selectionCount > 0 && (
- <TimelineActionButton label={selectionCount > 1 ? `Delete ${selectionCount}` : "Delete"} tooltip="Delete (⌫)" onClick={deleteSelection}><Trash2 /></TimelineActionButton>
+ <TimelineActionButton label={selectionCount > 1 ? tr("deleteCount", { count: selectionCount }) : tr("delete")} tooltip={tr("deleteTooltip", { key: "⌫" })} onClick={deleteSelection}><Trash2 /></TimelineActionButton>
)}
<TimelineGroupActions />
</>
@@ -3440,6 +3457,7 @@ function TimelineToolsMenu({
deleteSelection: () => void;
selectionCount: number;
}) {
+ const tr = useTranslations("timeline.toolbar");
const splitEnabled = useSplitEnabled();
const save = useSaveSelection();
const readOnly = useEditor((s) => s.readOnly);
@@ -3452,29 +3470,29 @@ function TimelineToolsMenu({
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger
render={
- <Button variant="ghost" size="icon-sm" aria-label="Timeline tools" title="Timeline tools" />
+ <Button variant="ghost" size="icon-sm" aria-label={tr("tools")} title={tr("tools")} />
}
>
<MoreHorizontal />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
- {!readOnly && <DropdownMenuItem onClick={addText}><Type /> Text</DropdownMenuItem>}
+ {!readOnly && <DropdownMenuItem onClick={addText}><Type /> {tr("text")}</DropdownMenuItem>}
{save.available && (
<DropdownMenuItem disabled={save.state === "saving"} onClick={save.save}>
{save.state === "done" ? <Check /> : <FolderPlus />}
- {save.state === "done" ? "Saved" : "Save template"}
+ {save.state === "done" ? tr("saved") : tr("saveTemplate")}
</DropdownMenuItem>
)}
{!readOnly && <DropdownMenuSeparator />}
{!readOnly && (
<DropdownMenuCheckboxItem checked={magnet} onCheckedChange={toggleMagnet}>
- <Magnet /> Magnet
+ <Magnet /> {tr("magnet")}
</DropdownMenuCheckboxItem>
)}
- {splitEnabled && <DropdownMenuItem onClick={split}><Scissors /> Split</DropdownMenuItem>}
+ {splitEnabled && <DropdownMenuItem onClick={split}><Scissors /> {tr("split")}</DropdownMenuItem>}
{!readOnly && selectionCount > 0 && (
<DropdownMenuItem onClick={deleteSelection}>
- <Trash2 /> {selectionCount > 1 ? `Delete ${selectionCount}` : "Delete"}
+ <Trash2 /> {selectionCount > 1 ? tr("deleteCount", { count: selectionCount }) : tr("delete")}
</DropdownMenuItem>
)}
<TimelineGroupActions menu />
@@ -3493,7 +3511,7 @@ function TimelineToolsMenu({
max={100}
step={0.1}
value={zoomToSlider(pps, zoomMin)}
- aria-label="Zoom"
+ aria-label={tr("zoom")}
onValueChange={(v) => zoomTo(sliderToZoom(Number(v), zoomMin))}
/>
</div>
@@ -3501,18 +3519,18 @@ function TimelineToolsMenu({
variant="ghost"
size="sm"
className="shrink-0"
- title="Fit timeline to window"
+ title={tr("fitTitle")}
onClick={() => {
fit();
setOpen(false);
}}
>
- Fit
+ {tr("fit")}
</Button>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => useEditor.getState().setTimelineOpen(false)}>
- <PanelBottomClose /> Hide timeline
+ <PanelBottomClose /> {tr("hideTimeline")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -3522,12 +3540,13 @@ function TimelineToolsMenu({
/** Folds the timeline away under the preview; the button over the canvas
* brings it back. */
function HideTimelineButton() {
+ const tr = useTranslations("timeline.toolbar");
return (
<Button
variant="ghost"
size="icon-sm"
- aria-label="Hide timeline"
- title="Hide timeline"
+ aria-label={tr("hideTimeline")}
+ title={tr("hideTimeline")}
onClick={() => useEditor.getState().setTimelineOpen(false)}
>
<PanelBottomClose />
@@ -3553,12 +3572,13 @@ function useSaveSelection() {
}
function SaveSelectionButton() {
+ const tr = useTranslations("timeline.toolbar");
const { available, state, save } = useSaveSelection();
if (!available) return null;
return (
<TimelineActionButton
- label={state === "done" ? "Saved" : "Save template"}
- tooltip="Save template"
+ label={state === "done" ? tr("saved") : tr("saveTemplate")}
+ tooltip={tr("saveTemplate")}
disabled={state === "saving"}
onClick={save}
>
@@ -3580,6 +3600,7 @@ function Timecode() {
/** Playback transport, centered in the timeline toolbar. */
function Transport({ total }: { total: number }) {
+ const tr = useTranslations("timeline.toolbar");
const playing = useEditor((s) => s.playing);
const hasClips = total > 0;
@@ -3597,7 +3618,7 @@ function Transport({ total }: { total: number }) {
<Button
variant="ghost"
size="icon-sm"
- aria-label="Back to start"
+ aria-label={tr("backToStart")}
disabled={!hasClips}
onClick={() => useEditor.getState().seek(0)}
>
@@ -3605,7 +3626,7 @@ function Transport({ total }: { total: number }) {
</Button>
<button
className="grid size-8 place-items-center rounded-full bg-foreground text-background transition-transform hover:opacity-90 active:scale-95 disabled:opacity-40"
- title="Play/Pause (Space)"
+ title={tr("playPause")}
disabled={!hasClips}
onClick={toggle}
>
@@ -3833,6 +3854,7 @@ function ClipView({
grab: { asset: MediaAsset; srcT: number; from: FrameGrabOrigin }
) => void;
}) {
+ const tr = useTranslations("timeline.clip");
const { clip, asset } = span;
const spine = clip.track === 0;
const loading = useEditor((s) => s.loadingMedia.has(asset.fileName));
@@ -3945,7 +3967,7 @@ function ClipView({
// eslint-disable-next-line @next/next/no-img-element
<img
src={LUT_MARK_ICON}
- alt="LUT"
+ alt={tr("lut")}
className="tl-clip-lut pointer-events-none absolute top-1 left-1 z-4 size-3.5 drop-shadow-[0_0_1px_rgba(0,0,0,0.6)]"
/>
)}
@@ -3976,7 +3998,7 @@ function ClipView({
// leaves. A clip too narrow for the word keeps the spinner and "C…".
<span className="tl-cutting-chip pointer-events-none absolute top-1 left-1 z-2 flex items-center gap-1 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] text-white transition-opacity group-hover:opacity-0">
<Loader2 className="size-2.5 shrink-0 animate-spin" />
- {barW >= 96 ? "Cutting…" : "C…"}
+ {barW >= 96 ? tr("cutting") : tr("cuttingShort")}
</span>
)}
{clip.name && !baking && !drag && (
@@ -4012,7 +4034,7 @@ function ClipView({
{!rt.uniform ? (
<span
className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
- title={`Speed curve · ${+rt.rate.toFixed(2)}× on average`}
+ title={tr("speedCurve", { rate: +rt.rate.toFixed(2) })}
>
∿ {+rt.rate.toFixed(1)}×
</span>
@@ -4020,7 +4042,7 @@ function ClipView({
rt.rate !== 1 && (
<span
className="tl-speed-chip absolute right-[30px] bottom-1 z-2 rounded-[5px] bg-black/70 px-1 py-px font-mono text-[9.5px] tabular-nums text-white"
- title={`${rt.rate}× speed`}
+ title={tr("speed", { rate: rt.rate })}
>
{+rt.rate.toFixed(2)}×
</span>
@@ -4045,7 +4067,7 @@ function ClipView({
void ensurePeaks(asset);
}}
>
- <AudioLines /> Detach audio
+ <AudioLines /> {tr("detachAudio")}
</DropdownMenuItem>
) : null}
</ClipMenu>
@@ -4177,6 +4199,7 @@ function ClipStrokeMarks({
pps: number;
barW: number;
}) {
+ const tr = useTranslations("timeline.clip");
const open = useBrushUi((s) => s.clipId === clip.id);
const seeds = clip.removal?.seeds;
if (!open || clip.removal?.mode !== "custom") return null;
@@ -4194,7 +4217,7 @@ function ClipStrokeMarks({
left: Math.min(barW - 4, Math.max(4, retime.tAt(t) * pps)),
transform: "translateX(-50%)",
}}
- title="Brush stroke"
+ title={tr("brushStroke")}
onPointerDown={(e) => {
e.stopPropagation();
e.preventDefault();
@@ -4312,13 +4335,14 @@ function ClipMenu({
clip: VideoClip | AudioClip;
children?: ReactNode;
}) {
+ const tr = useTranslations("timeline.clip");
const caps = useCutCaps();
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<button
- aria-label="Clip options"
+ aria-label={tr("options")}
className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"
onPointerDown={(e) => e.stopPropagation()}
/>
@@ -4336,7 +4360,7 @@ function ClipMenu({
useEditor.getState().updateAsset(asset.id, { origin: undefined, chatId: undefined })
}
>
- <Clapperboard /> Add to Media
+ <Clapperboard /> {tr("addToMedia")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
@@ -4347,10 +4371,10 @@ function ClipMenu({
});
}}
>
- <FolderPlus /> Add to Library
+ <FolderPlus /> {tr("addToLibrary")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => exportSegment(asset, clip)}>
- <ArrowDownToLine /> Export segment
+ <ArrowDownToLine /> {tr("exportSegment")}
</DropdownMenuItem>
<DropdownMenuItem
disabled={!!asset.upload}
@@ -4361,7 +4385,7 @@ function ClipMenu({
if (projectId) downloadMedia(projectId, asset);
}}
>
- <Download /> Download
+ <Download /> {tr("download")}
</DropdownMenuItem>
{caps.revealInFinder && (
<DropdownMenuItem
@@ -4371,7 +4395,7 @@ function ClipMenu({
void revealMedia(projectId, asset.fileName).catch(() => {});
}}
>
- <FolderOpen /> Show in Finder
+ <FolderOpen /> {tr("showInFinder")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
@@ -4895,10 +4919,11 @@ function RowGrip({
enabled: boolean;
onGrab: (e: React.PointerEvent) => void;
}) {
+ const tr = useTranslations("timeline.clip");
if (!enabled) return null;
return (
<div
- title="Drag to reorder the row"
+ title={tr("reorderRow")}
className="group pointer-events-auto absolute inset-x-0 cursor-grab"
style={{ top, height }}
onPointerDown={onGrab}
@@ -4930,15 +4955,16 @@ function GutterToggle({
* that does not is a click on the toggle and nothing more. */
onGrab?: (e: React.PointerEvent) => void;
}) {
+ const tr = useTranslations("timeline.clip");
const active = off || partial;
const title =
kind === "hide"
? off
- ? "Show track"
- : "Hide track"
+ ? tr("showTrack")
+ : tr("hideTrack")
: off
- ? "Unmute track"
- : "Mute track";
+ ? tr("unmuteTrack")
+ : tr("muteTrack");
const Icon = kind === "hide" ? (active ? EyeOff : Eye) : active ? VolumeX : Volume2;
return (
<button
@@ -4997,11 +5023,12 @@ function HideChip({
/** The element bars are low; the chip steps down to fit them. */
small?: boolean;
}) {
+ const tr = useTranslations("timeline.clip");
return (
<button
type="button"
- title={hidden ? "Enable clip" : "Disable clip"}
- aria-label={hidden ? "Enable clip" : "Disable clip"}
+ title={hidden ? tr("enable") : tr("disable")}
+ aria-label={hidden ? tr("enable") : tr("disable")}
className={cn(
"tl-hide-chip absolute z-4 grid place-items-center rounded-[5px] bg-black/55 text-white transition-opacity hover:bg-black/75",
small ? "size-[13px]" : "size-[18px]",
@@ -5035,11 +5062,12 @@ function LoadingChip() {
* missingMediaFor): an upload that never finished, or a file deleted from
* under the project. The clip keeps its place and edits; nothing plays. */
function MissingChip({ assetId }: { assetId: string }) {
+ const tr = useTranslations("timeline.clip");
const missing = useSyncExternalStore(subscribeStripStatus, () => missingMediaFor(assetId), () => false);
if (!missing) return null;
return (
<span className="tl-missing-chip pointer-events-none absolute right-1 bottom-1 z-4 rounded-[5px] bg-black/65 px-1.5 py-px text-[10px] whitespace-nowrap text-white">
- Missing media
+ {tr("missingMedia")}
</span>
);
}
@@ -5055,11 +5083,12 @@ function MuteChip({
onToggle: () => void;
className?: string;
}) {
+ const tr = useTranslations("timeline.clip");
return (
<button
type="button"
- title={muted ? "Unmute clip" : "Mute clip"}
- aria-label={muted ? "Unmute clip" : "Mute clip"}
+ title={muted ? tr("unmute") : tr("mute")}
+ aria-label={muted ? tr("unmute") : tr("mute")}
className={cn(
"tl-mute-chip absolute z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white transition-opacity hover:bg-black/75",
muted ? "opacity-100 bg-black/70" : "opacity-0 group-hover:opacity-100",
@@ -5249,7 +5278,10 @@ function BeatDot({
retime,
pps,
w,
+ title,
}: {
+ /** The dot's hint, resolved once by the row of dots. */
+ title: string;
assetId: string;
/** The source's length, the drag's bound. */
duration: number;
@@ -5268,7 +5300,7 @@ function BeatDot({
left: Math.min(w - 4, Math.max(4, retime.tAt(t) * pps)),
transform: "translateX(-50%)",
}}
- title="Drag to move, double-click to remove"
+ title={title}
onPointerDown={(e) => {
const s = useEditor.getState();
let live = t;
@@ -5323,8 +5355,10 @@ function BeatDots({
pps: number;
w: number;
}) {
+ const tr = useTranslations("timeline.clip");
const beats = asset.beats?.beats;
if (!beats?.length) return null;
+ const title = tr("beat");
return (
<>
{beats
@@ -5338,6 +5372,7 @@ function BeatDots({
retime={retime}
pps={pps}
w={w}
+ title={title}
/>
))}
</>
@@ -5566,6 +5601,7 @@ function FadeGrip({
live: boolean;
onLive: (v: { side: "in" | "out"; v: number } | null) => void;
}) {
+ const tr = useTranslations("timeline.clip");
const px = Math.min(barW, fade * pps);
// The grip keeps clear of the trim grab at its own end, so an edge grab still trims.
const at = Math.max(TRIM_W + 2, px);
@@ -5606,7 +5642,7 @@ function FadeGrip({
side === "in" ? "tl-fade-grip-in" : "tl-fade-grip-out"
)}
style={{ width: FADE_W, [edge]: at - FADE_W / 2 }}
- title={side === "in" ? "Drag to set the fade in" : "Drag to set the fade out"}
+ title={side === "in" ? tr("fadeIn") : tr("fadeOut")}
onPointerDown={grab}
>
<span
@@ -5661,6 +5697,7 @@ function KeyMarker({
* click and Delete removes the picked key. */
onMenu?: (m: { x: number; y: number; id: string; key?: number }) => void;
}) {
+ const tr = useTranslations("timeline.clip");
const picked = useEditor(
(s) =>
!!s.selectedKey &&
@@ -5683,7 +5720,7 @@ function KeyMarker({
left: Math.min(width - inset, Math.max(inset, t * pps)),
transform: "translate(-50%, -50%)",
}}
- title="Drag to retime, Delete to remove"
+ title={tr("key")}
onContextMenu={
onMenu
? (e) => {
@@ -5797,6 +5834,9 @@ function TextBar({
/** Open the bar's right-click menu; `key` set when it landed on a keyframe. */
onMenu: (m: { x: number; y: number; id: string; key?: number }) => void;
}) {
+ const tr = useTranslations("timeline.clip");
+ const shapeLabel = useLabels("shape");
+ const effectLabel = useLabels("effect");
const w = Math.max(8, (o.end - o.start) * pps);
// The bar is drawn a gutter narrower than the footprint; the keys on it
// measure against that.
@@ -5805,24 +5845,36 @@ function TextBar({
// Per-kind chip content: a title shows its text, a shape its name behind a
// shape glyph, a sticker its glyph and name.
const ShapeIcon = SHAPE_CHIP_ICONS[o.kind === "shape" ? o.shape : "rect"];
+ // The name the person gave it, else what it is in the page's language; a
+ // title's own text is its name.
+ const own = o.name?.trim();
+ const name =
+ own ||
+ (o.kind === "shape"
+ ? shapeLabel(o.shape)
+ : o.kind === "effect"
+ ? effectLabel(o.effect)
+ : o.kind === "sticker"
+ ? tr("sticker")
+ : overlayName(o));
const chip =
o.kind === "shape" ? (
<>
<ShapeIcon className="mr-1 size-2.5 shrink-0" />
- {overlayName(o)}
+ {name}
</>
) : o.kind === "sticker" ? (
<>
<StickerThumb overlay={o} />
- {overlayName(o)}
+ {name}
</>
) : o.kind === "effect" ? (
<>
<EffectChipIcon effect={o.effect} />
- {overlayName(o)}
+ {name}
</>
) : (
- overlayName(o)
+ name
);
return (
diff --git a/site/src/cut/components/TimelineGroupActions.tsx b/site/src/cut/components/TimelineGroupActions.tsx
index 1b86c075..5f8cebc8 100644
--- a/site/src/cut/components/TimelineGroupActions.tsx
+++ b/site/src/cut/components/TimelineGroupActions.tsx
@@ -1,6 +1,7 @@
"use client";
import { Group, Ungroup } from "lucide-react";
+import { useTranslations } from "next-intl";
import { useState } from "react";
import { TimelineActionButton } from "@/cut/components/TimelineActionButton";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -8,6 +9,7 @@ import { useEditor } from "@/cut/lib/store";
import { createSelectedGroupSelector } from "@/cut/lib/timelineGroups";
export function TimelineGroupActions({ menu = false }: { menu?: boolean }) {
+ const t = useTranslations("timeline.group");
const count = useEditor((s) => s.multiSelection.length);
const [selectGrouped] = useState(createSelectedGroupSelector);
const grouped = useEditor(selectGrouped);
@@ -16,15 +18,15 @@ export function TimelineGroupActions({ menu = false }: { menu?: boolean }) {
const ungroup = () => useEditor.getState().ungroupSelection();
if (readOnly) return null;
if (menu) return <>
- {count >= 2 && <DropdownMenuItem onClick={group}><Group /> Group</DropdownMenuItem>}
- {grouped && <DropdownMenuItem onClick={ungroup}><Ungroup /> Ungroup</DropdownMenuItem>}
+ {count >= 2 && <DropdownMenuItem onClick={group}><Group /> {t("group")}</DropdownMenuItem>}
+ {grouped && <DropdownMenuItem onClick={ungroup}><Ungroup /> {t("ungroup")}</DropdownMenuItem>}
</>;
return <>
{count >= 2 && (
- <TimelineActionButton label="Group" tooltip="Group (⌘/Ctrl+G)" onClick={group}><Group /></TimelineActionButton>
+ <TimelineActionButton label={t("group")} tooltip={t("groupTooltip", { key: "⌘/Ctrl+G" })} onClick={group}><Group /></TimelineActionButton>
)}
{grouped && (
- <TimelineActionButton label="Ungroup" tooltip="Ungroup (⇧⌘/Ctrl+G)" onClick={ungroup}><Ungroup /></TimelineActionButton>
+ <TimelineActionButton label={t("ungroup")} tooltip={t("ungroupTooltip", { key: "⇧⌘/Ctrl+G" })} onClick={ungroup}><Ungroup /></TimelineActionButton>
)}
</>;
}
diff --git a/site/src/cut/components/TimelinePicker.tsx b/site/src/cut/components/TimelinePicker.tsx
index ebf1accf..023afb84 100644
--- a/site/src/cut/components/TimelinePicker.tsx
+++ b/site/src/cut/components/TimelinePicker.tsx
@@ -1,6 +1,7 @@
"use client";
import { ChevronDown } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -14,12 +15,15 @@ import {
import { useEditor } from "@/cut/lib/store";
import { timelineEnd } from "@/cut/lib/timelineEnd";
import { switchTimeline, useTimelinePicker } from "@/cut/lib/timelineSwitch";
-import { isTimelineId, TIMELINE_IDS, TIMELINE_LABELS, type TimelineBody } from "@/cut/lib/types";
+import { isTimelineId, TIMELINE_IDS, type TimelineBody } from "@/cut/lib/types";
+import { useLabels } from "@/i18n/labels";
/** The timeline picker at the head of the toolbar: the open timeline's name,
* and the project's others under it. Held while work is still landing on the
* open one. */
export function TimelinePicker() {
+ const t = useTranslations("timeline.picker");
+ const timelineLabel = useLabels("timeline");
const timeline = useEditor((s) => s.timeline);
const readOnly = useEditor((s) => s.readOnly);
const { supported, blocked } = useTimelinePicker();
@@ -29,14 +33,14 @@ export function TimelinePicker() {
<DropdownMenu>
<DropdownMenuTrigger
disabled={blocked}
- render={<Button variant="ghost" size="sm" className="shrink-0 gap-1 px-2" aria-label="Timeline" />}
+ render={<Button variant="ghost" size="sm" className="shrink-0 gap-1 px-2" aria-label={t("label")} />}
>
- {TIMELINE_LABELS[timeline]}
+ {timelineLabel(timeline)}
<ChevronDown className="size-3.5 text-muted-foreground" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40">
<DropdownMenuGroup>
- <DropdownMenuLabel>Timelines</DropdownMenuLabel>
+ <DropdownMenuLabel>{t("heading")}</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={timeline}
onValueChange={(id) => {
@@ -45,7 +49,7 @@ export function TimelinePicker() {
>
{TIMELINE_IDS.map((id) => (
<DropdownMenuRadioItem key={id} value={id}>
- {TIMELINE_LABELS[id]}
+ {timelineLabel(id)}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
@@ -76,6 +80,8 @@ function holdsItems(b: Partial<TimelineBody> | undefined): boolean {
/** The note an empty timeline shows when another of the project's timelines
* holds the edit, so opening an empty one never reads as the edit gone. */
export function EmptyTimelineNote() {
+ const t = useTranslations("timeline.picker");
+ const timelineLabel = useLabels("timeline");
const timeline = useEditor((s) => s.timeline);
const readOnly = useEditor((s) => s.readOnly);
const other = useEditor((s) => TIMELINE_IDS.find((id) => id !== s.timeline && holdsItems(s.timelines[id])));
@@ -90,7 +96,7 @@ export function EmptyTimelineNote() {
<div className="pointer-events-none absolute inset-0 z-30 grid place-items-center">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>
- {TIMELINE_LABELS[timeline]} is empty. Your edit is on {TIMELINE_LABELS[other]}.
+ {t("emptyNote", { current: timelineLabel(timeline), other: timelineLabel(other) })}
</span>
<Button
variant="outline"
@@ -99,7 +105,7 @@ export function EmptyTimelineNote() {
disabled={blocked}
onClick={() => void switchTimeline(other)}
>
- Open {TIMELINE_LABELS[other]}
+ {t("open", { name: timelineLabel(other) })}
</Button>
</div>
</div>
diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsx
index 6d204f25..903067ed 100644
--- a/site/src/cut/components/TopBar.tsx
+++ b/site/src/cut/components/TopBar.tsx
@@ -3,6 +3,7 @@
import { DonkeyMark } from "@/components/DonkeyMark";
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
+import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import { Check, ChevronDown, ChevronLeft, CloudUpload, ExternalLink, Loader2, Maximize2, Mic, Monitor, MoreHorizontal, Ratio, Share2, Smartphone, Sparkles, Square, Upload, Video } from "lucide-react";
import { ChatStatusBadge, type ChatStatus } from "./ChatStatusBadge";
@@ -31,6 +32,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cloudBackend } from "@/cut/lib/backend/cloud";
+import { useDescribeError } from "@/i18n/describeError";
import { cloudUsageQueryKey, useCutMode } from "@/cut/lib/backend/hooks";
import { browserBackend } from "@/cut/lib/backend/browser";
import { localBackend } from "@/cut/lib/backend/local";
@@ -42,8 +44,9 @@ import { projectDuration, useEditor } from "@/cut/lib/store";
import { useEnvironment } from "@/cut/lib/environment";
import { openThroughHost, projectPageUrl, requestHostFullscreen, useHostDisplayMode } from "@/cut/lib/hostBridge";
import { useLocalPref } from "@/cut/lib/uiState";
-import { ASPECT_PRESETS, aspectLabel, aspectOrientation, normalizeAspect, parseRatio, type Aspect } from "@/cut/lib/types";
+import { ASPECT_PRESETS, aspectOrientation, normalizeAspect, parseRatio, type Aspect } from "@/cut/lib/types";
import { COLOR_PRESETS, ColorPicker } from "@/cut/components/ColorField";
+import type { Messages } from "@/i18n/namespaces";
import { cn } from "@/lib/utils";
import { CreditsPill } from "./CreditsPill";
import { RecordDialog, type RecordMode } from "./RecordDialog";
@@ -57,6 +60,14 @@ function AspectIcon({ aspect, className }: { aspect: Aspect; className?: string
return <Icon className={className} />;
}
+type AspectKey = keyof Messages["editor"]["topBar"]["aspects"];
+
+/** An aspect preset's catalog key: its ratio with the colon spelled "x"
+ * ("16:9" → "16x9"). */
+function aspectKey(aspect: Aspect): AspectKey {
+ return aspect.replace(":", "x") as AspectKey;
+}
+
/**
* A toolbar action's name, in the app's own tooltip. The trigger is a wrapper
* rather than the button, so a disabled button — which swallows pointer events
@@ -93,6 +104,9 @@ export function TopBar({
* bytes never touch this browser, so the indicator calls it a copy. */
copying?: number;
}) {
+ const t = useTranslations("editor.topBar");
+ const tColor = useTranslations("inspector.colorField");
+ const describeError = useDescribeError();
const base = useCutBase();
const back = backTarget(base, from, folder);
// Something to render, which footage is only one way to have: a cut of
@@ -284,14 +298,15 @@ export function TopBar({
// disk copies, so they report nothing.
const cloudUploading = (uploading > 0 || copying > 0) && cutMode === "cloud";
const transferLabel =
- uploading > 0
- ? uploading === 1
- ? "Uploading"
- : `Uploading ${uploading} files`
- : copying === 1
- ? "Copying"
- : `Copying ${copying} files`;
- const finishingLabel = uploading > 0 ? "Finishing uploads…" : "Finishing copies…";
+ uploading > 0 ? t("uploading", { count: uploading }) : t("copying", { count: copying });
+ const finishingLabel = uploading > 0 ? t("finishingUploads") : t("finishingCopies");
+ // A preset's name and ratio ("Widescreen · 16:9"); any other ratio is custom.
+ const aspectName = (value: Aspect) => {
+ const preset = ASPECT_PRESETS.find((p) => p.value === value);
+ return preset
+ ? t("aspectPreset", { name: t(`aspects.${aspectKey(preset.value)}`), ratio: preset.value })
+ : t("customAspect", { ratio: value });
+ };
// An import whose bytes never landed is absent from the saved document, so
// its clip disappears on the next open. The Media panel shows this for a
// dropped file, but a stock or library import lives on the timeline and has
@@ -325,7 +340,7 @@ export function TopBar({
}
const src = cutMode === "browser" ? browserBackend : localBackend;
const newId = await copyProjectAcross(src, cloudBackend, projectId, {
- onProgress: (done, total) => setMoveProgress(`Moving media ${done}/${total}…`),
+ onProgress: (done, total) => setMoveProgress(t("movingMedia", { done, total })),
});
await src
.fetch(`/api/cut/projects/${projectId}`, { method: "DELETE" })
@@ -335,9 +350,7 @@ export function TopBar({
clearProjectThreads(projectId);
window.location.href = projectHref(base, newId, "projects", null);
} catch (e) {
- setMoveError(
- e instanceof Error && e.message ? e.message : "Could not move the project."
- );
+ setMoveError(describeError(e, t("moveFailed")));
setMoving(false);
setMoveProgress(null);
}
@@ -363,12 +376,12 @@ export function TopBar({
<Button
variant="ghost"
size={compact ? "icon-sm" : "sm"}
- aria-label="Share"
- title={cutMode === "browser" ? "Move to Cloud to share" : "Share"}
+ aria-label={t("share")}
+ title={cutMode === "browser" ? t("moveToShare") : t("share")}
onClick={() => (cutMode === "browser" ? setMoveOpen(true) : setShareOpen(true))}
>
<Share2 data-icon={compact ? undefined : "inline-start"} />
- {!compact && "Share"}
+ {!compact && t("share")}
</Button>
)}
{canMoveToCloud && (
@@ -382,31 +395,31 @@ export function TopBar({
<Button
variant="ghost"
size={compact ? "icon-sm" : "sm"}
- aria-label="Move to Cloud"
+ aria-label={t("moveToCloud")}
onClick={() => setMoveOpen(true)}
>
<CloudUpload data-icon={compact ? undefined : "inline-start"} />
- {!compact && "Cloud"}
+ {!compact && t("cloud")}
</Button>
}
/>
- <TooltipContent side="bottom">Move to Cloud</TooltipContent>
+ <TooltipContent side="bottom">{t("moveToCloud")}</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
<ActionTip
label={
failedImports > 0
- ? "Retry the failed imports first"
+ ? t("retryImportsFirst")
: cloudUploading
? finishingLabel
- : "Export"
+ : t("export")
}
>
<Button
variant="ghost"
size={icons ? "icon-sm" : "sm"}
- aria-label="Export"
+ aria-label={t("export")}
// A render reads the saved document, which an import still uploading
// (or one that failed) is deliberately absent from — exporting now
// would quietly leave it out of the video.
@@ -418,32 +431,32 @@ export function TopBar({
}}
>
<Upload data-icon={icons ? undefined : "inline-start"} />
- {!icons && "Export"}
+ {!icons && t("export")}
</Button>
</ActionTip>
{chatgpt && (
- <ActionTip label="Open in Donkey Cut">
+ <ActionTip label={t("openInCut")}>
<Button
variant="ghost"
size={icons ? "icon-sm" : "sm"}
- aria-label="Open in Donkey Cut"
+ aria-label={t("openInCut")}
onClick={() => openThroughHost(projectPageUrl())}
>
<ExternalLink data-icon={icons ? undefined : "inline-start"} />
- {!icons && "Open"}
+ {!icons && t("open")}
</Button>
</ActionTip>
)}
{chatgpt && hostMode !== "fullscreen" && (
- <ActionTip label="Fullscreen">
+ <ActionTip label={t("fullscreen")}>
<Button
variant="ghost"
size={icons ? "icon-sm" : "sm"}
- aria-label="Fullscreen"
+ aria-label={t("fullscreen")}
onClick={requestHostFullscreen}
>
<Maximize2 data-icon={icons ? undefined : "inline-start"} />
- {!icons && "Fullscreen"}
+ {!icons && t("fullscreen")}
</Button>
</ActionTip>
)}
@@ -451,15 +464,15 @@ export function TopBar({
variant={aiOpen ? "default" : "outline"}
size="sm"
className="ai-toggle relative"
- aria-label="Chat"
+ aria-label={t("chat")}
aria-pressed={aiOpen}
- title="Chat (⌘J)"
+ title={t("chatShortcut", { key: "⌘J" })}
onClick={() => {
const s = useEditor.getState();
s.setAiOpen(!s.aiOpen);
}}
>
- <Sparkles data-icon="inline-start" /> Chat
+ <Sparkles data-icon="inline-start" /> {t("chat")}
{!aiOpen && <ChatStatusBadge status={chatStatus} />}
</Button>}
</>
@@ -484,7 +497,7 @@ export function TopBar({
{!chatgpt && <Button
variant="ghost"
size="icon-sm"
- aria-label={`Back to ${back.tab}`}
+ aria-label={t("backTo", { tab: back.tab })}
nativeButton={false}
render={<Link href={back.href} />}
>
@@ -506,7 +519,7 @@ export function TopBar({
) : (
<button
className="ml-1.5 max-w-64 cursor-text truncate rounded-md px-2 py-1 text-sm font-medium tracking-tight hover:bg-muted"
- title="Rename project"
+ title={t("rename")}
onClick={() => {
setDraft(projectName);
setEditing(true);
@@ -524,14 +537,14 @@ export function TopBar({
{failedImports > 0 ? (
<>
<span className="text-destructive">
- {failedImports === 1 ? "1 import failed" : `${failedImports} imports failed`}
+ {t("importsFailed", { count: failedImports })}
</span>
<button
type="button"
className="font-medium underline underline-offset-2"
onClick={retryFailedUploads}
>
- Retry
+ {t("retry")}
</button>
</>
) : cloudUploading ? (
@@ -541,13 +554,13 @@ export function TopBar({
</>
) : saveState === "saving" || saveState === "dirty" ? (
<>
- <Loader2 className="size-3 animate-spin" /> Saving
+ <Loader2 className="size-3 animate-spin" /> {t("saving")}
</>
) : saveState === "error" ? (
- <span className="text-destructive">Couldn’t save</span>
+ <span className="text-destructive">{t("saveFailed")}</span>
) : (
<>
- <Check className="size-3" /> Saved
+ <Check className="size-3" /> {t("saved")}
</>
)}
</span>
@@ -567,7 +580,7 @@ export function TopBar({
>
<AspectIcon aspect={p.value} />
<span className="flex-1">
- {p.name} · {p.value}
+ {aspectName(p.value)}
{p.sublabel && (
<span className="block text-[10.5px] text-muted-foreground">{p.sublabel}</span>
)}
@@ -586,7 +599,7 @@ export function TopBar({
>
<Ratio />
<span className="flex-1">
- {normalizeAspect(savedCustom) ? `Custom · ${savedCustom}` : "Custom…"}
+ {normalizeAspect(savedCustom) ? t("customAspect", { ratio: savedCustom }) : t("customEllipsis")}
</span>
{showCustomEditor && <Check className="size-3.5 text-muted-foreground" />}
</DropdownMenuItem>
@@ -594,13 +607,13 @@ export function TopBar({
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<span className="size-4 shrink-0 rounded-[4px] ring-1 ring-border" style={{ background }} />
- <span className="flex-1">Background</span>
+ <span className="flex-1">{t("background")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-56">
{COLOR_PRESETS.map((c) => (
<DropdownMenuItem key={c.hex} onClick={() => { useEditor.getState().pushHistory(); useEditor.getState().setBackground(c.hex); }}>
<span className="size-4 shrink-0 rounded-[4px] ring-1 ring-border" style={{ background: c.hex }} />
- <span className="flex-1">{c.name}</span>
+ <span className="flex-1">{tColor(`presets.${c.id}`)}</span>
{background.toUpperCase() === c.hex && <Check className="size-3.5 text-muted-foreground" />}
</DropdownMenuItem>
))}
@@ -625,7 +638,7 @@ export function TopBar({
"aspect-switch flex items-center gap-1 rounded-full border bg-card px-3 py-1.5 text-xs font-medium shadow-xs",
customInvalid ? "border-destructive text-destructive" : "border-border"
)}
- title={customInvalid ? "Up to an 8:1 shape" : undefined}
+ title={customInvalid ? t("aspectLimit") : undefined}
// The session ends when focus leaves the pill entirely. Moving
// between the two fields (or to the chevron) stays inside it, so a
// half-typed side is never settled out from under the user.
@@ -639,7 +652,7 @@ export function TopBar({
>
<Ratio className="size-3.5 text-muted-foreground" />
<input
- aria-label="Width"
+ aria-label={t("width")}
aria-invalid={customInvalid}
inputMode="decimal"
className="w-10 bg-transparent text-center outline-none"
@@ -653,7 +666,7 @@ export function TopBar({
/>
<span className="text-muted-foreground">:</span>
<input
- aria-label="Height"
+ aria-label={t("height")}
aria-invalid={customInvalid}
inputMode="decimal"
className="w-10 bg-transparent text-center outline-none"
@@ -667,7 +680,7 @@ export function TopBar({
/>
<DropdownMenu>
<DropdownMenuTrigger
- aria-label="Aspect ratio presets"
+ aria-label={t("aspectPresets")}
className="grid place-items-center text-muted-foreground transition-colors hover:text-foreground"
>
<ChevronDown className="size-3" />
@@ -679,7 +692,7 @@ export function TopBar({
<DropdownMenu>
<DropdownMenuTrigger className="aspect-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">
<AspectIcon aspect={aspect} className="size-3.5" />
- {aspectLabel(aspect)}
+ {aspectName(aspect)}
<ChevronDown className="size-3" />
</DropdownMenuTrigger>
{aspectMenu}
@@ -689,15 +702,15 @@ export function TopBar({
{!chatgpt && <DropdownMenu>
<DropdownMenuTrigger className="record-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">
<span className="size-2 rounded-full bg-red-500" aria-hidden />
- Record
+ {t("record")}
<ChevronDown className="size-3" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" style={{ width: "12rem" }}>
<DropdownMenuItem onClick={() => setRecordMode("camera")}>
- <Video /> Record camera
+ <Video /> {t("recordCamera")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setRecordMode("audio")}>
- <Mic /> Record audio
+ <Mic /> {t("recordAudio")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>}
@@ -744,7 +757,7 @@ export function TopBar({
) : (
<DropdownMenu>
<DropdownMenuTrigger
- render={<Button variant="ghost" size="icon-sm" className="relative" aria-label="More actions" title="More actions" />}
+ render={<Button variant="ghost" size="icon-sm" className="relative" aria-label={t("moreActions")} title={t("moreActions")} />}
>
<MoreHorizontal />
{!aiOpen && <ChatStatusBadge status={chatStatus} />}
@@ -752,12 +765,12 @@ export function TopBar({
<DropdownMenuContent align="end" className="w-48">
{cutMode === "cloud" && !chatgpt && (
<DropdownMenuItem onClick={() => setShareOpen(true)}>
- <Share2 /> Share
+ <Share2 /> {t("share")}
</DropdownMenuItem>
)}
{canMoveToCloud && (
<DropdownMenuItem onClick={() => setMoveOpen(true)}>
- <CloudUpload /> Move to Cloud
+ <CloudUpload /> {t("moveToCloud")}
</DropdownMenuItem>
)}
<DropdownMenuItem
@@ -768,7 +781,7 @@ export function TopBar({
s.setExportOpen(true);
}}
>
- <Upload /> {cloudUploading ? finishingLabel : "Export"}
+ <Upload /> {cloudUploading ? finishingLabel : t("export")}
</DropdownMenuItem>
{!chatgpt && <DropdownMenuItem
onClick={() => {
@@ -777,7 +790,7 @@ export function TopBar({
}}
>
<Sparkles />
- <span className="relative flex-1">Chat{!aiOpen && <ChatStatusBadge status={chatStatus} />}</span>
+ <span className="relative flex-1">{t("chat")}{!aiOpen && <ChatStatusBadge status={chatStatus} />}</span>
{aiOpen && <Check className="size-3.5 text-muted-foreground" />}
</DropdownMenuItem>}
</DropdownMenuContent>
@@ -795,18 +808,16 @@ export function TopBar({
<Dialog open onOpenChange={(open) => !open && !moving && setMoveOpen(false)}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
- <DialogTitle>Move to Cloud</DialogTitle>
+ <DialogTitle>{t("moveToCloud")}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
- Copies this project and its media to the cloud, then removes it
- from {cutMode === "browser" ? "this browser" : "this Mac"}.
- Exports rendered here stay behind.
+ {t("moveBody", { from: cutMode === "browser" ? "browser" : "mac" })}
</p>
{moveError && <p className="text-sm text-red-600">{moveError}</p>}
<DialogFooter className="mt-2">
<Button disabled={moving} className="w-full" onClick={() => void moveToCloud()}>
{moving && <Loader2 className="animate-spin" data-icon="inline-start" />}
- {moving ? (moveProgress ?? "Moving…") : "Move to Cloud"}
+ {moving ? (moveProgress ?? t("moving")) : t("moveToCloud")}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/site/src/cut/components/TrackRow.tsx b/site/src/cut/components/TrackRow.tsx
index a7d9e9d9..91b79081 100644
--- a/site/src/cut/components/TrackRow.tsx
+++ b/site/src/cut/components/TrackRow.tsx
@@ -2,9 +2,11 @@
import { useState } from "react";
import { Loader2 } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { trackMotion } from "@/cut/lib/trackMotion";
import { TRACK_TARGETS, type TrackTarget } from "@/cut/lib/trackTargets";
+import { useDescribeError } from "@/i18n/describeError";
/**
* The inspector's motion-tracking control: pick what to track and the item's
@@ -13,6 +15,8 @@ import { TRACK_TARGETS, type TrackTarget } from "@/cut/lib/trackTargets";
* footage the row shows how far it has got.
*/
export function TrackRow({ id, use }: { id: string; use: "mask" | "follow" }) {
+ const t = useTranslations("timeline.trackRow");
+ const describeError = useDescribeError();
const [progress, setProgress] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -24,7 +28,7 @@ export function TrackRow({ id, use }: { id: string; use: "mask" | "follow" }) {
try {
await trackMotion({ id, target, use, onProgress: (share) => setProgress(Math.round(share * 100)) });
} catch (e) {
- setError(e instanceof Error ? e.message : "Could not track the footage.");
+ setError(describeError(e, t("failed")));
} finally {
setProgress(null);
}
@@ -33,27 +37,27 @@ export function TrackRow({ id, use }: { id: string; use: "mask" | "follow" }) {
return (
<>
<div className="flex items-center justify-between gap-2 py-1">
- <span className="text-[11.5px] font-medium text-muted-foreground">{use === "mask" ? "Track" : "Follow"}</span>
+ <span className="text-[11.5px] font-medium text-muted-foreground">{use === "mask" ? t("track") : t("follow")}</span>
{progress !== null ? (
<span className="flex h-8 items-center gap-1.5 text-[12px] text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" />
- Tracking {progress}%
+ {t("tracking", { progress })}
</span>
) : (
<Select
value={null}
- items={Object.fromEntries(TRACK_TARGETS.map((t) => [t.id, t.label]))}
+ items={Object.fromEntries(TRACK_TARGETS.map((target) => [target.id, t(`targets.${target.id}`)]))}
onValueChange={(v) => {
if (v) void run(v as TrackTarget);
}}
>
<SelectTrigger className="h-8 w-36 text-[12px]">
- <SelectValue placeholder="Pick a target" />
+ <SelectValue placeholder={t("pickTarget")} />
</SelectTrigger>
<SelectContent>
- {TRACK_TARGETS.map((t) => (
- <SelectItem key={t.id} value={t.id} className="text-[12px]">
- {t.label}
+ {TRACK_TARGETS.map((target) => (
+ <SelectItem key={target.id} value={target.id} className="text-[12px]">
+ {t(`targets.${target.id}`)}
</SelectItem>
))}
</SelectContent>
diff --git a/site/src/cut/components/TransformHandles.tsx b/site/src/cut/components/TransformHandles.tsx
index 12f94805..a3c351b1 100644
--- a/site/src/cut/components/TransformHandles.tsx
+++ b/site/src/cut/components/TransformHandles.tsx
@@ -1,7 +1,8 @@
"use client";
-import type { CSSProperties } from "react";
+import { useMemo, type CSSProperties } from "react";
import { RefreshCw } from "lucide-react";
+import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
/**
@@ -57,8 +58,8 @@ export function TransformHandles({
className,
rotateGap = 32,
rotateCursor,
- resizeTitle = "Drag to resize",
- rotateTitle = "Drag to rotate",
+ resizeTitle,
+ rotateTitle,
}: {
/** Ring color on every grip; the chrome it belongs to picks it. */
color?: string;
@@ -81,6 +82,10 @@ export function TransformHandles({
resizeTitle?: string;
rotateTitle?: string;
}) {
+ const t = useTranslations("editor.transformHandles");
+ // The default grip names, resolved once per locale: the handles redraw
+ // with every drag step.
+ const fallback = useMemo(() => ({ rotate: t("rotate"), resize: t("resize") }), [t]);
return (
<div
className={cn("pointer-events-none absolute", !frame && "inset-0", className)}
@@ -98,7 +103,7 @@ export function TransformHandles({
</span>
)}
<span
- title={rotateTitle}
+ title={rotateTitle ?? fallback.rotate}
onPointerDown={onRotate}
style={{ cursor: rotateCursor ?? "grab" }}
className="pointer-events-auto grid size-[22px] place-items-center rounded-full bg-white text-neutral-700 shadow-[0_1px_4px_rgba(0,0,0,0.4)]"
@@ -115,7 +120,7 @@ export function TransformHandles({
return (
<span
key={h}
- title={resizeTitle}
+ title={resizeTitle ?? fallback.resize}
onPointerDown={(e) => onResize(h, e)}
className={cn(
"pointer-events-auto absolute rounded-full border-[2.5px] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]",
diff --git a/site/src/cut/components/TransitionsPanel.tsx b/site/src/cut/components/TransitionsPanel.tsx
index e83e00ef..e109955a 100644
--- a/site/src/cut/components/TransitionsPanel.tsx
+++ b/site/src/cut/components/TransitionsPanel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
import { PHASE_STEP } from "@/cut/components/AnimationTiles";
import { SwatchScene, useSwatchClock } from "@/cut/components/EffectsPanel";
import { SectionTitle } from "@/cut/components/SectionTitle";
@@ -12,9 +13,7 @@ import { getClipSpans, resolveTransitions, useEditor } from "@/cut/lib/store";
import { usePreviewTimeEvery } from "@/cut/lib/playhead";
import {
ANIM_STYLE_IDS,
- ANIM_STYLE_LABELS,
TRANSITION_STYLE_GROUPS,
- TRANSITION_STYLE_LABELS,
overlayAnimStyle,
previewUrl,
transitionStyleOfAnim,
@@ -37,6 +36,7 @@ import { parseNumberInput } from "@/cut/components/ScrubValue";
import { ValueSlider } from "@/cut/components/ValueSlider";
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useLabels } from "@/i18n/labels";
/**
* The Transitions tab: how one clip hands over to the next, and how a clip
@@ -54,6 +54,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";
* it only picks.
*/
export function TransitionsPanel() {
+ const t = useTranslations("panels.transitions");
// The bar the tab is tuned to: a selected bar directly, or the one playing
// the selected clip's cut.
const live = useEditor((s) => {
@@ -81,7 +82,7 @@ export function TransitionsPanel() {
<div onKeyDown={pickGridNav}>
{TRANSITION_STYLE_GROUPS.map((g) => (
<section key={g.label} className="mb-3 flex flex-col gap-1.5">
- <SectionTitle>{g.label}</SectionTitle>
+ <SectionTitle>{t(`groups.${g.label.toLowerCase()}` as Parameters<typeof t>[0])}</SectionTitle>
<div className="grid grid-cols-2 gap-2">
{g.ids.map((id) => (
<TransitionTile key={id} style={id} live={live} a={a} b={b} />
@@ -98,6 +99,8 @@ export function TransitionsPanel() {
/** How soft the selected bar's reveal edge is: 0 is the hard edge, the top
* of the range a ramp half the frame wide. A drag is one undo step. */
function SoftnessRow({ bar }: { bar: TimelineTransition }) {
+ const t = useTranslations("panels.transitions");
+ const hard = t("hard");
const ck = useSliderCheckpoint();
const write = (v: number) => {
ck.begin();
@@ -105,18 +108,18 @@ function SoftnessRow({ bar }: { bar: TimelineTransition }) {
};
return (
<div className="mb-3">
- <Row label="Softness">
+ <Row label={t("softness")}>
<ValueSlider
- label="Edge softness"
+ label={t("edgeSoftness")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={bar.feather ?? 0}
min={0}
max={TRANSITION_FEATHER_MAX}
step={0.01}
- format={(v) => (v ? `${Math.round(v * 100)}%` : "Hard")}
+ format={(v) => (v ? `${Math.round(v * 100)}%` : hard)}
parse={(raw) => {
- if (raw.trim().toLowerCase() === "hard") {
+ if (raw.trim().toLowerCase() === hard.toLowerCase()) {
return 0;
}
const n = parseNumberInput(raw.replace(/%$/, ""));
@@ -136,6 +139,8 @@ function SoftnessRow({ bar }: { bar: TimelineTransition }) {
/** How wide the white panel running ahead of the selected wipe's edge is:
* 0 is none, the top of the range half the frame. A drag is one undo step. */
function BandRow({ bar }: { bar: TimelineTransition }) {
+ const t = useTranslations("panels.transitions");
+ const none = t("none");
const ck = useSliderCheckpoint();
const write = (v: number) => {
ck.begin();
@@ -143,18 +148,18 @@ function BandRow({ bar }: { bar: TimelineTransition }) {
};
return (
<div className="mb-3">
- <Row label="White band">
+ <Row label={t("whiteBand")}>
<ValueSlider
- label="White band width"
+ label={t("whiteBandWidth")}
sliderClassName="data-horizontal:w-24"
valueClassName="w-9 text-muted-foreground"
value={bar.band ?? 0}
min={0}
max={TRANSITION_BAND_MAX}
step={0.01}
- format={(v) => (v ? `${Math.round(v * 100)}%` : "None")}
+ format={(v) => (v ? `${Math.round(v * 100)}%` : none)}
parse={(raw) => {
- if (raw.trim().toLowerCase() === "none") {
+ if (raw.trim().toLowerCase() === none.toLowerCase()) {
return 0;
}
const n = parseNumberInput(raw.replace(/%$/, ""));
@@ -270,6 +275,7 @@ function TransitionTile({
a: string | null;
b: string | null;
}) {
+ const transitionLabel = useLabels("transition");
const { picked, pick } = useAssetPick(`transition:${style}`);
const ref = useRef<HTMLButtonElement>(null);
const { t, restart } = useHandoverClock(TILE_INDEX.get(style) ?? 0);
@@ -313,7 +319,7 @@ function TransitionTile({
t={t}
className={cn("w-full rounded-lg border border-border", marked && PICKED_RING)}
/>
- <span className="leading-none">{TRANSITION_STYLE_LABELS[style]}</span>
+ <span className="leading-none">{transitionLabel(style)}</span>
</button>
);
}
@@ -355,6 +361,7 @@ export function ClipAnimationTiles({
value?: AnimStyle;
onPick: (style: AnimStyle | null) => void;
}) {
+ const t = useTranslations("panels.transitions");
const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));
const frame = useCutFrame(
`anim-${which}`,
@@ -363,7 +370,7 @@ export function ClipAnimationTiles({
const ids = clip.track > 0 ? ANIM_STYLE_IDS.filter((s) => overlayAnimStyle(s) === s) : ANIM_STYLE_IDS;
return (
<div className="grid grid-cols-2 gap-2" onKeyDown={pickGridNav}>
- <Tile selected={!value} pickId="anim:none" onClick={() => onPick(null)} label="None" className="p-1">
+ <Tile selected={!value} pickId="anim:none" onClick={() => onPick(null)} label={t("none")} className="p-1">
<span className="relative block aspect-square w-full overflow-hidden rounded-md bg-black">
<Layer frame={frame} variant="day" />
</span>
@@ -398,6 +405,7 @@ function ClipAnimTile({
selected: boolean;
onPick: () => void;
}) {
+ const animLabel = useLabels("anim");
const { t, restart } = useHandoverClock(index);
return (
<Tile
@@ -405,7 +413,7 @@ function ClipAnimTile({
pickId={`anim:${style}`}
onClick={onPick}
onHover={(inside) => inside && restart()}
- label={ANIM_STYLE_LABELS[style]}
+ label={animLabel(style)}
className="p-1"
>
<TransitionSwatch
diff --git a/site/src/cut/components/UpgradeDialog.tsx b/site/src/cut/components/UpgradeDialog.tsx
index ad2d7e3c..e2a54798 100644
--- a/site/src/cut/components/UpgradeDialog.tsx
+++ b/site/src/cut/components/UpgradeDialog.tsx
@@ -3,12 +3,13 @@
// The wall a free account meets at a paid limit: one project past the free
// count, or a request that ran out of credits. Both sell Pro. A Pro account
// that runs out is sent to buy credits.
+import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { FolderPlus, Loader2, Zap } from "lucide-react";
-import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
-import { introTerms, wallBanner } from "@/cut/components/IntroOffer";
+import { CUT_PRO, useCutPro } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
+import { useIntroTerms, wallBanner } from "@/cut/components/IntroOffer";
import { OfferButton, OfferDialog, OfferDismiss, preloadBanner } from "@/cut/components/OfferDialog";
import { useCutBase } from "@/cut/lib/nav";
import { onOperationFailure } from "@/cut/lib/operationFailure";
@@ -17,7 +18,7 @@ import { onUpgrade, openUpgrade, type UpgradeReason } from "@/cut/lib/upgrade";
import { track } from "@/lib/analytics";
import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";
import { useAccountConfig } from "@/queries/accountConfig";
-import { useIntroOffer, useProSubscription, type IntroOffer } from "@/queries/billing";
+import { useIntroOffer, useProSubscription } from "@/queries/billing";
export function UpgradeDialog() {
const [reason, setReason] = useState<UpgradeReason | null>(null);
@@ -61,6 +62,10 @@ function OpenDialog({
projectLimit: number | null;
onClose: () => void;
}) {
+ const t = useTranslations("billing");
+ const locale = useLocale();
+ const introTerms = useIntroTerms();
+ const { price } = useCutPro();
const pro = useProSubscription();
const isPro = pro.data?.isActive === true;
const intro = useIntroOffer({ enabled: pro.data?.isActive === false });
@@ -100,8 +105,8 @@ function OpenDialog({
open
onOpenChange={close}
banner="credits"
- title="You're out of credits"
- body="This month's Pro credits are spent. Buy more to keep generating."
+ title={t("upgrade.outOfCredits")}
+ body={t("upgrade.proOutBody")}
cta={
<OfferButton
onClick={() => {
@@ -109,26 +114,42 @@ function OpenDialog({
router.push(`${base}/settings`);
}}
>
- Buy credits
+ {t("buyCredits")}
</OfferButton>
}
- secondary={<OfferDismiss onClick={onClose}>Not now</OfferDismiss>}
+ secondary={<OfferDismiss onClick={onClose}>{t("notNow")}</OfferDismiss>}
/>
);
}
const offer = intro.data ?? null;
- const credits = creditCountLabel(CUT_PRO.monthlyDollars * creditsPerDollar);
+ const credits = creditCountLabel(CUT_PRO.monthlyDollars * creditsPerDollar, locale);
const wall =
reason === "projects"
- ? { icon: FolderPlus, title: "Upgrade to make more projects", body: projectsBody(projectLimit) }
+ ? {
+ icon: FolderPlus,
+ title: t("upgrade.projectsTitle"),
+ body: projectLimit
+ ? t("upgrade.projectsBody", { count: projectLimit })
+ : t("upgrade.projectsBodyStarter"),
+ }
: {
icon: Zap,
- title: "You're out of credits",
+ title: t("upgrade.outOfCredits"),
// An open offer prices Pro on its terms line.
- body: `Upgrade to Pro and get ${credits} every month and 100 GB of cloud storage${offer ? "" : ` for ${CUT_PRO.price}`}.`,
+ body: offer
+ ? t("upgrade.creditsBodyOffer", { credits })
+ : t("upgrade.creditsBody", { credits, price }),
};
+ // The terms line: an open offer's terms, else the price on the projects
+ // wall. The credits wall names the price in its message, so it has none.
+ const terms = offer
+ ? introTerms(offer)
+ : reason === "projects"
+ ? t("upgrade.proPrice", { price })
+ : undefined;
+
return (
<OfferDialog
open
@@ -137,34 +158,14 @@ function OpenDialog({
closesAt={offer?.endsAt}
title={wall.title}
body={wall.body}
- terms={wallTerms(reason, offer)}
+ terms={terms}
cta={
<OfferButton disabled={upgrade.isPending} onClick={upgrade.start}>
{upgrade.isPending && <Loader2 className="animate-spin" data-icon="inline-start" />}
- Upgrade to Pro
+ {t("upgradeToPro")}
</OfferButton>
}
- secondary={<OfferDismiss onClick={onClose}>Not now</OfferDismiss>}
+ secondary={<OfferDismiss onClick={onClose}>{t("notNow")}</OfferDismiss>}
/>
);
}
-
-/** The terms line: an open offer's terms, else the price on the projects
- * wall. The credits wall names the price in its message, so it has none. */
-function wallTerms(reason: UpgradeReason, offer: IntroOffer | null): string | undefined {
- if (offer) {
- return introTerms(offer);
- }
- if (reason === "projects") {
- return `Pro is ${CUT_PRO.price}.`;
- }
- return undefined;
-}
-
-/** What the free plan holds, as the projects wall says it. */
-function projectsBody(limit: number | null): string {
- if (!limit) {
- return "The free plan keeps your starter project. Pro makes as many as you need.";
- }
- return `The free plan keeps ${limit} project${limit === 1 ? "" : "s"} besides your starter. Pro makes as many as you need.`;
-}
diff --git a/site/src/cut/components/ViewerTopBar.tsx b/site/src/cut/components/ViewerTopBar.tsx
index 8bc31989..d936f4ef 100644
--- a/site/src/cut/components/ViewerTopBar.tsx
+++ b/site/src/cut/components/ViewerTopBar.tsx
@@ -2,14 +2,17 @@
import { DonkeyMark } from "@/components/DonkeyMark";
import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { useDescribeError } from "@/i18n/describeError";
import { Copy, Loader2, Sparkles } from "lucide-react";
import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
import { ChatStatusBadge, type ChatStatus } from "./ChatStatusBadge";
import { Button } from "@/components/ui/button";
import { apiFetch } from "@/cut/lib/backend";
-import { quotaErrorMessage } from "@/cut/lib/backend/cloud";
import { projectHref, useCutBase } from "@/cut/lib/nav";
+import { OperationError, operationFailure } from "@/cut/lib/operationFailure";
import { useEditor } from "@/cut/lib/store";
+import { errorFromBody } from "@/cut/lib/userError";
import { authClient } from "@/lib/auth-client";
// Chrome for the read-only share view: logo, project name, a "View only"
@@ -18,6 +21,8 @@ import { authClient } from "@/lib/auth-client";
// session: signed-out clicks route through sign-in with this share URL as the
// callback.
export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
+ const t = useTranslations("editor.viewerTopBar");
+ const describeError = useDescribeError();
const aiOpen = useEditor((s) => s.aiOpen);
const base = useCutBase();
const projectName = useEditor((s) => s.projectName);
@@ -40,16 +45,19 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
| { jobId?: string; error?: string }
| null;
if (!res.ok || !body?.jobId) {
- throw new Error(
- quotaErrorMessage(res.status, body) ?? body?.error ?? "Could not copy the project."
- );
+ // A refusal with a code (a full cloud quota) reads in the page's language.
+ const failure = operationFailure(res.status, body);
+ if (failure?.code === "storage_quota_exceeded") {
+ throw new OperationError(failure);
+ }
+ throw errorFromBody(body, t("copyFailed"));
}
// Copies drain through a queue one at a time; poll the job until this
// one lands.
for (;;) {
await new Promise((r) => setTimeout(r, 2000));
const st = await apiFetch(`/api/cut/copy/${body.jobId}`);
- if (!st.ok) throw new Error("Could not copy the project.");
+ if (!st.ok) throw new Error(t("copyFailed"));
const job = (await st.json()) as {
state: string;
newProjectId?: string;
@@ -59,10 +67,10 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
window.location.href = projectHref(base, job.newProjectId, "projects");
return;
}
- if (job.state === "error") throw new Error(job.error ?? "Could not copy the project.");
+ if (job.state === "error") throw errorFromBody(job, t("copyFailed"));
}
} catch (e) {
- setCopyError(e instanceof Error ? e.message : "Could not copy the project.");
+ setCopyError(describeError(e, t("copyFailed")));
setCopying(false);
}
};
@@ -77,7 +85,7 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
{projectName}
</span>
<span className="ml-1 rounded-full border border-border px-2 py-0.5 text-[10.5px] font-medium text-muted-foreground">
- View only
+ {t("viewOnly")}
</span>
</div>
<div className="flex items-center gap-2">
@@ -87,14 +95,14 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
variant="ghost"
size="sm"
className="ai-toggle relative"
- aria-label="Chat"
- title="Chat (⌘J)"
+ aria-label={t("chat")}
+ title={t("chatShortcut", { key: "⌘J" })}
onClick={() => {
const s = useEditor.getState();
s.setAiOpen(!s.aiOpen);
}}
>
- <Sparkles data-icon="inline-start" /> Chat
+ <Sparkles data-icon="inline-start" /> {t("chat")}
{!aiOpen && <ChatStatusBadge status={chatStatus} />}
</Button>
)}
@@ -104,7 +112,7 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {
) : (
<Copy data-icon="inline-start" />
)}
- {copying ? "Copying…" : "Copy project"}
+ {copying ? t("copying") : t("copyProject")}
</Button>
</div>
</header>
diff --git a/site/src/cut/components/VoicePicker.tsx b/site/src/cut/components/VoicePicker.tsx
index fc9a6c37..0dd4a31d 100644
--- a/site/src/cut/components/VoicePicker.tsx
+++ b/site/src/cut/components/VoicePicker.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { useTranslations } from "next-intl";
import { Captions, ChevronDown, Loader2, Pause, Play } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -23,6 +24,7 @@ import {
import { generateSubtitlesReadout } from "@/cut/lib/voiceover";
import { cn } from "@/lib/utils";
import { PICKED_RING } from "@/cut/lib/assetPick";
+import { useDescribeError } from "@/i18n/describeError";
// Shared speech preferences (speaker voice, spoken language) for every surface
// that generates audio (Audio tab, Subtitles tab, clip settings). Module-level
@@ -75,11 +77,12 @@ export function useSpeechLanguage(): string {
/** A small round persona portrait, used in the trigger and each grid tile. */
function VoiceAvatar({ id, style, className }: { id: string; style: string; className?: string }) {
+ const t = useTranslations("panels.voicePicker");
return (
// eslint-disable-next-line @next/next/no-img-element -- bundled static portrait on a client-only page
<img
src={voicePortraitUrl(id)}
- alt={`${id}, a ${style.toLowerCase()} voice`}
+ alt={t("portraitAlt", { name: id, style: style.toLowerCase() })}
loading="lazy"
className={cn("object-cover", className)}
/>
@@ -106,7 +109,7 @@ const ORDERED_VOICES = [...SPEECH_VOICES].sort((a, b) =>
* voice choice.
*/
export function VoicePicker({
- title = "Speaker voice",
+ title,
direction,
onError,
}: {
@@ -117,9 +120,11 @@ export function VoicePicker({
/** Surfaced when a live (direction) preview fails — e.g. no credits. */
onError?: (e: unknown) => void;
}) {
+ const t = useTranslations("panels.voicePicker");
const voice = useSpeakerVoice();
const language = useSpeechLanguage();
const selected = SPEECH_VOICES.find((v) => v.id === voice) ?? SPEECH_VOICES[0];
+ const selectedStyle = t(`styles.${selected.id}` as Parameters<typeof t>[0]);
const [open, setOpen] = useState(false);
const [sampling, setSampling] = useState<null | "loading" | "playing">(null);
const audio = useRef<HTMLAudioElement | null>(null);
@@ -181,13 +186,13 @@ export function VoicePicker({
return (
<div className="voice-picker flex flex-col gap-1.5">
- <SectionTitle>{title}</SectionTitle>
+ <SectionTitle>{title ?? t("speakerVoice")}</SectionTitle>
<div className="flex items-stretch gap-2">
<button
type="button"
className="voice-sample grid size-[34px] shrink-0 place-items-center rounded-lg border border-input text-foreground transition-colors hover:bg-muted"
- title={direction?.trim() ? "Hear this voice with your direction" : "Hear this voice"}
- aria-label="Play a sample of the selected voice"
+ title={direction?.trim() ? t("hearWithDirection") : t("hearVoice")}
+ aria-label={t("playSample")}
onClick={() => void sample()}
>
{sampling === "loading" ? (
@@ -208,12 +213,12 @@ export function VoicePicker({
<DropdownMenuTrigger className="voice-select flex min-w-0 flex-1 items-center gap-2.5 overflow-hidden rounded-lg border border-input bg-transparent pr-2.5 text-left outline-none transition-colors focus:border-ring">
<VoiceAvatar
id={selected.id}
- style={selected.style}
+ style={selectedStyle}
className="size-8 shrink-0 bg-muted"
/>
<span className="min-w-0 flex-1 truncate text-[12.5px]">
<span className="font-semibold">{selected.name}</span>{" "}
- <span className="text-muted-foreground">· {selected.style}</span>
+ <span className="text-muted-foreground">· {selectedStyle}</span>
</span>
<ChevronDown className="size-4 shrink-0 text-muted-foreground" />
</DropdownMenuTrigger>
@@ -228,13 +233,14 @@ export function VoicePicker({
<div key={i} className="voice-grid grid grid-cols-5 gap-2">
{group.map((v) => {
const isSelected = v.id === voice;
+ const style = t(`styles.${v.id}` as Parameters<typeof t>[0]);
return (
<button
key={v.id}
type="button"
className="voice-tile group flex flex-col gap-1 text-left"
aria-pressed={isSelected}
- title={`${v.name} · ${v.style}`}
+ title={t("tileTitle", { name: v.name, style })}
onClick={() => {
voicePref.write(v.id);
setOpen(false);
@@ -252,12 +258,12 @@ export function VoicePicker({
: "border-input group-hover:border-transparent group-hover:ring-2 group-hover:ring-[#0a84ff]/40"
)}
>
- <VoiceAvatar id={v.id} style={v.style} className="size-full" />
+ <VoiceAvatar id={v.id} style={style} className="size-full" />
</span>
<span className="min-w-0 px-0.5 leading-tight">
<span className="block truncate text-[11px] font-semibold">{v.name}</span>
<span className="block truncate text-[10px] text-muted-foreground">
- {v.style}
+ {style}
</span>
</span>
</button>
@@ -287,7 +293,7 @@ function scopedCueIds(s: EditorState, select?: (s: EditorState) => string[]): st
export function GenerateSubtitlesAudio({
selectCueIds,
ensureCues,
- label = "Generate audio for subtitles",
+ label,
}: {
selectCueIds?: (s: EditorState) => string[];
/** Makes cues exist when the scope has none, matched to that scope (e.g.
@@ -296,6 +302,8 @@ export function GenerateSubtitlesAudio({
ensureCues?: () => Promise<void>;
label?: string;
}) {
+ const t = useTranslations("panels.voicePicker");
+ const describeError = useDescribeError();
const voice = useSpeakerVoice();
const language = useSpeechLanguage();
const signedOut = useSignedIn() === false;
@@ -317,16 +325,16 @@ export function GenerateSubtitlesAudio({
await ensureCues();
} else {
if (useEditor.getState().subtitleStatus === "running") {
- throw new Error("Subtitles are still generating — try again in a moment.");
+ throw new Error(t("subtitlesStillGenerating"));
}
await useEditor.getState().generateSubtitles();
const after = useEditor.getState();
if (after.subtitleStatus === "error") {
- throw new Error(after.subtitleError ?? "Transcription failed.");
+ throw new Error(after.subtitleError ?? t("transcriptionFailed"));
}
}
if (scopedCueIds(useEditor.getState(), selectCueIds).length === 0) {
- throw new Error("No speech found to voice.");
+ throw new Error(t("noSpeech"));
}
}
const { asset } = await generateSubtitlesReadout(voice, {
@@ -336,7 +344,7 @@ export function GenerateSubtitlesAudio({
useGenNotify.getState().landed("audio", asset.id);
} catch (e) {
setError({
- text: e instanceof Error ? e.message : "Voice generation failed.",
+ text: describeError(e, t("voiceFailed")),
});
} finally {
setBusy(false);
@@ -346,7 +354,7 @@ export function GenerateSubtitlesAudio({
return (
<div className="subtitles-audio flex flex-col gap-2.5">
- <VoicePicker title="Generated audio" />
+ <VoicePicker title={t("generatedAudio")} />
<Button
variant="outline"
className="voice-readout w-full"
@@ -354,22 +362,24 @@ export function GenerateSubtitlesAudio({
title={
cueCount === 0
? hasVideo
- ? "Transcribe the speech, then voice it onto the soundtrack"
- : "Add a video to the timeline first"
- : "Voice the subtitle text and drop it on the soundtrack"
+ ? t("transcribeThenVoice")
+ : t("addVideoFirst")
+ : t("voiceSubtitles")
}
onClick={() => void generate()}
>
{busy ? <Loader2 className="animate-spin" /> : <Captions data-icon="inline-start" />}
- {label}
+ {label ?? t("generateForSubtitles")}
</Button>
{signedOut ? (
<p className="voice-signin text-[11px] leading-relaxed text-muted-foreground">
- Voiceovers run on your Donkey account.{" "}
- <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
- Sign in
- </a>{" "}
- to continue.
+ {t.rich("signIn", {
+ link: (chunks) => (
+ <a className="font-medium text-blue-600 hover:underline dark:text-blue-400" href={signInUrl()}>
+ {chunks}
+ </a>
+ ),
+ })}
</p>
) : (
error && (
diff --git a/site/src/cut/components/chatError.ts b/site/src/cut/components/chatError.ts
new file mode 100644
index 00000000..9ab852aa
--- /dev/null
+++ b/site/src/cut/components/chatError.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+
+import { UserError, failureCode, failureText } from "@/cut/lib/userError";
+import { useDescribeError } from "@/i18n/describeError";
+
+/**
+ * Words a failure the chat shows, through the shared describer. A provider
+ * failure with no words of its own reads the chat catalog's "The request
+ * failed." in their place.
+ */
+export function useChatError(): (error: unknown) => string {
+ const t = useTranslations("chat.failures");
+ const describeError = useDescribeError();
+ return (error) => {
+ const coded = failureCode(error);
+ if (coded?.params.detail !== "") {
+ return describeError(error);
+ }
+ return describeError(new UserError(coded.code, failureText(error), { ...coded.params, detail: t("requestFailed") }));
+ };
+}
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index 270ddb0d..c07147bf 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -2,6 +2,7 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Folder, MoreHorizontal, Pencil, Share2, Trash2 } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -17,6 +18,7 @@ import { PICKED_RING } from "@/cut/lib/assetPick";
import { additiveClick } from "@/cut/lib/hostKeys";
import { clearRefDrag, setRefDragData, type AssetRef } from "@/cut/lib/assetRef";
import { reportSwallowed } from "@/cut/lib/report";
+import { useDescribeError } from "@/i18n/describeError";
import { formatBytes } from "@/lib/bytes";
import { RefDropZone } from "./RefDropZone";
import { cn } from "@/lib/utils";
@@ -301,6 +303,7 @@ function CrumbStep({
}
function FolderTitle({ name, onRename }: { name: string; onRename: (name: string) => void | Promise<void> }) {
+ const t = useTranslations("home.folders");
const [editing, setEditing] = useState(false);
const [error, setError] = useState(false);
return (
@@ -315,9 +318,9 @@ function FolderTitle({ name, onRename }: { name: string; onRename: (name: string
}}
/>
) : (
- <button type="button" title="Rename folder" className="max-w-full cursor-text truncate rounded-md px-1 hover:bg-muted" onClick={() => { setError(false); setEditing(true); }}>{name}</button>
+ <button type="button" title={t("renameFolder")} className="max-w-full cursor-text truncate rounded-md px-1 hover:bg-muted" onClick={() => { setError(false); setEditing(true); }}>{name}</button>
)}
- {error && <span role="alert" className="ml-2 text-xs font-normal text-destructive">Could not rename folder.</span>}
+ {error && <span role="alert" className="ml-2 text-xs font-normal text-destructive">{t("renameFailed")}</span>}
</span>
);
}
@@ -393,22 +396,23 @@ export function FolderMenuItems({
onShare,
onRename,
onDelete,
- deleteLabel = "Delete folder",
+ deleteLabel,
}: {
onShare?: () => void;
onRename: () => void;
onDelete: () => void;
deleteLabel?: string;
}) {
+ const t = useTranslations("home.folders");
return (
<>
- {onShare && <DropdownMenuItem onClick={onShare}><Share2 /> Share</DropdownMenuItem>}
+ {onShare && <DropdownMenuItem onClick={onShare}><Share2 /> {t("share")}</DropdownMenuItem>}
<DropdownMenuItem onClick={onRename}>
- <Pencil /> Rename
+ <Pencil /> {t("rename")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 /> {deleteLabel}
+ <Trash2 /> {deleteLabel ?? t("deleteFolder")}
</DropdownMenuItem>
</>
);
@@ -488,6 +492,9 @@ export function FolderShelf<F extends DeskFolder>({
// A folder tile accepts an internal selection (its MIME), another folder
// tile when the host nests folders, and, when the host wires it up, OS
// files dragged from the desktop.
+ const t = useTranslations("home.folders");
+ const locale = useLocale();
+ const describeError = useDescribeError();
const dragTypes = (e: React.DragEvent) => Array.from(e.dataTransfer.types);
const nests = !!folderMime && !!onDropFolders;
// The tile being dragged, so it does not light up as its own target. The
@@ -528,7 +535,7 @@ export function FolderShelf<F extends DeskFolder>({
() => setTimeout(release, LANDING_GRACE_MS),
(err: unknown) => {
release();
- setFailed(err instanceof Error && err.message ? err.message : "Could not create folder.");
+ setFailed(describeError(err, t("createFailed")));
reportSwallowed("[cut] folder create failed", err, name);
},
);
@@ -644,7 +651,7 @@ export function FolderShelf<F extends DeskFolder>({
<Button
variant="ghost"
size="icon-sm"
- aria-label="Folder options"
+ aria-label={t("options")}
className={cn(
"size-6 opacity-0 group-hover/f:opacity-100 data-[state=open]:opacity-100",
rows
@@ -662,7 +669,7 @@ export function FolderShelf<F extends DeskFolder>({
onShare={onShare && (() => onShare(f.id))}
onRename={() => setEditingId(f.id)}
onDelete={() => void onDelete(f.id)}
- deleteLabel={isPicked && picked.size > 1 ? "Delete" : "Delete folder"}
+ deleteLabel={isPicked && picked.size > 1 ? t("delete") : t("deleteFolder")}
/>
</DropdownMenuContent>
</DropdownMenu>
@@ -686,8 +693,8 @@ export function FolderShelf<F extends DeskFolder>({
<div className="min-w-0 flex-1">
<div className="truncate text-xs font-medium">{f.name}</div>
<div className="flex items-center gap-1 text-[10px] text-muted-foreground tabular-nums">
- {s.count} {s.count === 1 ? "item" : "items"}
- {s.size != null ? ` · ${formatBytes(s.size)}` : ""}
+ {t("items", { count: s.count })}
+ {s.size != null ? ` · ${formatBytes(s.size, locale)}` : ""}
{badgeOf?.(f.id)}
</div>
</div>
@@ -712,7 +719,7 @@ export function FolderShelf<F extends DeskFolder>({
</span>
<span className="flex items-center gap-1 text-[10px] text-muted-foreground tabular-nums">
{s.count}
- {s.size != null ? ` · ${formatBytes(s.size)}` : ""}
+ {s.size != null ? ` · ${formatBytes(s.size, locale)}` : ""}
{badgeOf?.(f.id)}
</span>
{menu}
@@ -746,7 +753,7 @@ export function FolderShelf<F extends DeskFolder>({
<Input
autoFocus
value={draft}
- placeholder="Name"
+ placeholder={t("namePlaceholder")}
className={cn("h-6 text-[11px]", rows ? "flex-1" : "w-full")}
onChange={(e) => setDraft(e.target.value)}
onBlur={closeCreate}
diff --git a/site/src/cut/components/editor-mock/EditorMock.tsx b/site/src/cut/components/editor-mock/EditorMock.tsx
index eaa2331b..455c7240 100644
--- a/site/src/cut/components/editor-mock/EditorMock.tsx
+++ b/site/src/cut/components/editor-mock/EditorMock.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useTranslations } from "next-intl";
+import { useEffect, useMemo, useRef, useState } from "react";
import "./editor-mock.css";
@@ -9,7 +10,7 @@ import { MockPreview } from "@/cut/components/editor-mock/MockPreview";
import { MockSidePanel } from "@/cut/components/editor-mock/MockSidePanel";
import { MockTimeline } from "@/cut/components/editor-mock/MockTimeline";
import { MockTopBar } from "@/cut/components/editor-mock/MockTopBar";
-import { MOCK_PROJECTS, type MockProject } from "@/cut/components/editor-mock/mockData";
+import { mockProjects, onboardingProject } from "@/cut/components/editor-mock/mockData";
import { cn } from "@/lib/utils";
// The mock is authored at a fixed design size and scaled to its container's
@@ -29,8 +30,9 @@ const VIEWS = {
export type EditorMockView = keyof typeof VIEWS;
type Props = {
- /** Show exactly this project instead of the landing's showcase pair. */
- project?: MockProject;
+ /** Show exactly the onboarding project in place of the landing's showcase
+ * pair. */
+ project?: "onboarding";
view?: EditorMockView;
/** Which dimension the mock is sized by. "width" fills the container and
* takes whatever height that implies; "height" fills a container of bounded
@@ -59,7 +61,13 @@ export function EditorMock({
showSwitcher = true,
frame = "lifted",
}: Props) {
- const projects = project ? [project] : MOCK_PROJECTS;
+ const t = useTranslations("mock");
+ // Built once per language: the projects are the catalog's words on fixed
+ // geometry.
+ const projects = useMemo(
+ () => (project === "onboarding" ? [onboardingProject(t)] : mockProjects(t)),
+ [project, t],
+ );
const [active, setActive] = useState(0);
const frameRef = useRef<HTMLDivElement>(null);
const [box, setBox] = useState({ width: 0, height: 0 });
@@ -161,11 +169,7 @@ export function EditorMock({
</div>
</div>
</div>
- <figcaption className="sr-only">
- The Donkey Cut editor with a finished project open: generated media in
- the side panel, clips and music on the timeline, and the AI chat that
- assembled them.
- </figcaption>
+ <figcaption className="sr-only">{t("editorMock.caption")}</figcaption>
{showSwitcher && (
<div className="mt-6 flex flex-wrap justify-center gap-1.5">
{projects.map((p, i) => (
diff --git a/site/src/cut/components/editor-mock/MockAiPanel.tsx b/site/src/cut/components/editor-mock/MockAiPanel.tsx
index 1a8072ec..4a4d5757 100644
--- a/site/src/cut/components/editor-mock/MockAiPanel.tsx
+++ b/site/src/cut/components/editor-mock/MockAiPanel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import {
ArrowUp,
Check,
@@ -21,6 +22,7 @@ import type {
/** Static replica of the Cut editor's AI chat panel for the landing mock.
* Mirrors AiPanel's structure and Tailwind styling with hardcoded content. */
export function MockAiPanel({ project }: { project: MockProject }) {
+ const t = useTranslations("mock.aiPanel");
return (
<aside className="relative flex h-full w-[340px] shrink-0 flex-col overflow-hidden border-l border-border bg-card">
<div className="flex h-[46px] shrink-0 items-center gap-1.5 border-b border-border pr-2 pl-3.5">
@@ -44,7 +46,7 @@ export function MockAiPanel({ project }: { project: MockProject }) {
className="mock-chat-msg mt-1 flex items-center gap-1.5 text-[11.5px] text-muted-foreground"
style={{ animationDelay: `${project.chat.length * 120}ms` }}
>
- <CircleDashed className="size-3 animate-spin" /> Working… 3s
+ <CircleDashed className="size-3 animate-spin" /> {t("working", { seconds: 3 })}
</div>
</div>
@@ -54,7 +56,7 @@ export function MockAiPanel({ project }: { project: MockProject }) {
pins white directly. */}
<div className="rounded-xl border border-input bg-card dark:bg-[color-mix(in_oklab,var(--card),white_5%)]">
<div className="min-h-9 px-3 pt-2 text-[12.5px] leading-relaxed text-muted-foreground/70">
- Ask about your video, or tell me what to change… @ references media
+ {t("placeholder")}
</div>
<div className="flex items-center gap-1 px-1.5 pb-1.5">
<span className="flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground">
diff --git a/site/src/cut/components/editor-mock/MockSidePanel.tsx b/site/src/cut/components/editor-mock/MockSidePanel.tsx
index 6754d85a..5e7d46d1 100644
--- a/site/src/cut/components/editor-mock/MockSidePanel.tsx
+++ b/site/src/cut/components/editor-mock/MockSidePanel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import {
Captions,
ChevronDown,
@@ -27,13 +28,13 @@ import type {
// slide data. Class strings mirror SidePanel/ImageGenPanel/GeneratePanel so it
// is indistinguishable from the real editor at a glance.
-const TABS: { id: MockPanelTab; label: string; icon: typeof Film }[] = [
- { id: "media", label: "Media", icon: Clapperboard },
- { id: "video", label: "Video", icon: Film },
- { id: "image", label: "Image", icon: ImageIcon },
- { id: "audio", label: "Audio", icon: Music },
- { id: "subtitles", label: "Subtitles", icon: Captions },
- { id: "details", label: "Details", icon: ClipboardList },
+const TABS: { id: MockPanelTab; icon: typeof Film }[] = [
+ { id: "media", icon: Clapperboard },
+ { id: "video", icon: Film },
+ { id: "image", icon: ImageIcon },
+ { id: "audio", icon: Music },
+ { id: "subtitles", icon: Captions },
+ { id: "details", icon: ClipboardList },
];
/** The rounded pill-select chrome, closed. */
@@ -52,13 +53,14 @@ function Pill({ label, className }: { label: string; className?: string }) {
}
export function MockSidePanel({ project }: { project: MockProject }) {
+ const t = useTranslations("mock.sidePanel");
const { panel } = project;
return (
<div className="flex h-full min-h-0 overflow-hidden border-r border-border bg-card">
{/* Icon rail */}
<div className="flex min-h-0 w-[68px] shrink-0 flex-col items-center gap-1 overflow-hidden border-r border-border py-3">
- {TABS.map(({ id, label, icon: Icon }) => [
+ {TABS.map(({ id, icon: Icon }) => [
// Soft breaks between the file tabs, the AI-generate tabs, and the finishing tabs.
id === "video" || id === "subtitles" ? (
<div key={`${id}-break`} aria-hidden className="my-1 h-px w-8 shrink-0 bg-border" />
@@ -81,7 +83,7 @@ export function MockSidePanel({ project }: { project: MockProject }) {
panel.tab === id && "text-foreground"
)}
>
- {label}
+ {t(`tabs.${id}`)}
</span>
</div>,
])}
@@ -102,28 +104,29 @@ export function MockSidePanel({ project }: { project: MockProject }) {
* arrangements they saved. Generated media lives where it was made, so it
* never shows up here. */
function MediaPanel({ panel }: { panel: Extract<MockPanel, { tab: "media" }> }) {
+ const t = useTranslations("mock.sidePanel");
return (
<>
<div className="flex h-12 shrink-0 items-center px-3.5">
<div className="flex w-full rounded-lg bg-muted p-0.5 text-[11.5px]">
<span className="flex-1 rounded-md bg-background px-3 py-0.5 text-center font-medium text-foreground shadow-sm">
- Project Files
+ {t("projectFiles")}
</span>
<span className="flex-1 rounded-md px-3 py-0.5 text-center font-medium text-muted-foreground">
- Library
+ {t("library")}
</span>
</div>
</div>
<div className="shrink-0 px-3.5 pb-3">
<span className="flex h-8 w-full items-center justify-center gap-1.5 rounded-lg border border-input text-sm font-medium">
- <Upload className="size-4" /> Upload
+ <Upload className="size-4" /> {t("upload")}
</span>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-3.5 pb-4">
<div className="flex shrink-0 flex-col gap-1.5">
- {panel.templates.map((t, i) => (
- <TemplateRow key={i} template={t} />
+ {panel.templates.map((template, i) => (
+ <TemplateRow key={i} template={template} />
))}
</div>
<div className="grid shrink-0 grid-cols-2 content-start gap-2.5">
@@ -137,13 +140,14 @@ function MediaPanel({ panel }: { panel: Extract<MockPanel, { tab: "media" }> })
}
function TemplateRow({ template }: { template: MockTemplate }) {
+ const t = useTranslations("mock.sidePanel");
return (
<div className="light flex items-center gap-2 rounded-lg border border-page-border bg-background bg-clip-padding px-2.5 py-1.5 text-foreground">
<Layers className="size-3.5 shrink-0 text-violet-500" />
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium">{template.name}</div>
<div className="flex items-center gap-0.5 text-[10.5px] text-muted-foreground">
- {template.duration} · {template.items} items
+ {t("templateMeta", { duration: template.duration, count: template.items })}
<ChevronDown className="size-3" />
</div>
</div>
@@ -233,13 +237,16 @@ function GeneratePanel({
panel: Extract<MockPanel, { tab: "image" | "video" }>;
aspect: MockProject["aspect"];
}) {
+ const t = useTranslations("mock");
const isImage = panel.tab === "image";
+ const aspectName = t(aspect === "9:16" ? "aspectNames.vertical" : "aspectNames.widescreen");
+ const generate = t(isImage ? "sidePanel.generateImage" : "sidePanel.generateVideo");
return (
<>
<div className="flex h-12 shrink-0 items-center pr-2.5 pl-4">
<span className="text-sm font-semibold tracking-tight">
- {isImage ? "Generate image" : "Generate video"}
+ {generate}
</span>
</div>
@@ -255,7 +262,7 @@ function GeneratePanel({
<div className="flex shrink-0 items-center gap-2">
<Pill
className="min-w-0 flex-1"
- label={aspect === "9:16" ? "Vertical" : "Widescreen"}
+ label={aspectName}
/>
<Pill label="2K" />
</div>
@@ -264,23 +271,23 @@ function GeneratePanel({
<Pill className="h-7 shrink-0" label="Omni Flash" />
<Pill
className="h-7 shrink-0"
- label={aspect === "9:16" ? "Vertical" : "Widescreen"}
+ label={aspectName}
/>
</>
)}
<div className="flex h-8 w-full shrink-0 items-center justify-center gap-1.5 rounded-lg border border-transparent bg-primary pr-2.5 pl-2 text-sm font-medium whitespace-nowrap text-primary-foreground">
<Sparkles className="size-4 shrink-0" />
- {isImage ? "Generate image" : "Generate video"}
+ {generate}
</div>
{!isImage && (
<p className="shrink-0 text-[11px] leading-relaxed text-muted-foreground">
- Renders take a minute or two. Keep editing while it runs.
+ {t("sidePanel.renderNote")}
</p>
)}
- {isImage && <div className="text-xs font-semibold text-muted-foreground">Generated</div>}
+ {isImage && <div className="text-xs font-semibold text-muted-foreground">{t("sidePanel.generated")}</div>}
{isImage ? (
<div className="grid shrink-0 grid-cols-2 content-start gap-2.5">
diff --git a/site/src/cut/components/editor-mock/MockTopBar.tsx b/site/src/cut/components/editor-mock/MockTopBar.tsx
index ce48b0f7..c29205cf 100644
--- a/site/src/cut/components/editor-mock/MockTopBar.tsx
+++ b/site/src/cut/components/editor-mock/MockTopBar.tsx
@@ -1,6 +1,7 @@
"use client";
import { DonkeyMark } from "@/components/DonkeyMark";
+import { useTranslations } from "next-intl";
import {
Check,
ChevronDown,
@@ -12,22 +13,23 @@ import {
} from "lucide-react";
import type { MockProject } from "@/cut/components/editor-mock/mockData";
-import { aspectLabel } from "@/cut/lib/types";
// Static replica of src/cut/components/TopBar.tsx — same chrome, no store.
export function MockTopBar({ project }: { project: MockProject }) {
+ const t = useTranslations("mock");
const AspectIcon = project.aspect === "9:16" ? Smartphone : Monitor;
+ const aspectName = t(project.aspect === "9:16" ? "aspectNames.vertical" : "aspectNames.widescreen");
return (
<header className="relative flex items-center justify-between border-b border-border bg-card pr-3 pl-2">
<div className="absolute left-1/2 flex -translate-x-1/2 items-center gap-2">
<span className="flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs">
<AspectIcon className="size-3.5" />
- {aspectLabel(project.aspect)}
+ {t("topBar.aspect", { name: aspectName, ratio: project.aspect })}
<ChevronDown className="size-3" />
</span>
<span className="flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs">
<span className="size-2 rounded-full bg-red-500" aria-hidden />
- Record
+ {t("topBar.record")}
<ChevronDown className="size-3" />
</span>
</div>
@@ -42,15 +44,15 @@ export function MockTopBar({ project }: { project: MockProject }) {
{project.name}
</span>
<span className="ml-2 flex items-center gap-1 text-[11px] text-muted-foreground opacity-60">
- <Check className="size-3" /> Saved
+ <Check className="size-3" /> {t("topBar.saved")}
</span>
</div>
<div className="flex items-center gap-2">
<span className="flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium text-foreground">
- <Sparkles className="size-3.5" /> Chat
+ <Sparkles className="size-3.5" /> {t("topBar.chat")}
</span>
<span className="flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground shadow-xs">
- <Upload className="size-3.5" /> Export
+ <Upload className="size-3.5" /> {t("topBar.export")}
</span>
</div>
</header>
diff --git a/site/src/cut/components/editor-mock/mockData.ts b/site/src/cut/components/editor-mock/mockData.ts
index aa38b8fa..b58417d6 100644
--- a/site/src/cut/components/editor-mock/mockData.ts
+++ b/site/src/cut/components/editor-mock/mockData.ts
@@ -1,5 +1,12 @@
// Everything the landing's static editor replica shows, hardcoded per slide.
-// The mock components render exactly this — no stores, no engine.
+// The mock components render exactly this — no stores, no engine. The words
+// come from the `mock` catalog, so the fake project reads in the page's
+// language; file names and the voiceover's own speech stay as recorded.
+import type { useTranslations } from "next-intl";
+
+/** The `mock` catalog's translator, as the factories below take it. */
+export type MockT = ReturnType<typeof useTranslations<"mock">>;
+
export type MockAspect = "9:16" | "16:9";
@@ -93,72 +100,74 @@ export interface MockProject {
const ASSETS = "/cut/landing";
-export const MOCK_PROJECTS: MockProject[] = [
- {
+/** The landing's showcase pair. */
+export function mockProjects(t: MockT): MockProject[] {
+ return [postersProject(t), railwayProject(t)];
+}
+
+function postersProject(t: MockT): MockProject {
+ const paris = t("projects.posters.paris");
+ const newYork = t("projects.posters.newYork");
+ return {
id: "posters",
- switcherLabel: "Travel posters",
- name: "City poster series",
+ switcherLabel: t("projects.posters.switcherLabel"),
+ name: t("projects.posters.name"),
aspect: "9:16",
panel: {
tab: "image",
- prompt:
- "Hand-painted travel poster, PARIS — woman in a trench coat crossing the street, Eiffel Tower behind, café awnings, 'Live the romance' in red script",
+ prompt: t("projects.posters.prompt"),
results: [
- { src: `${ASSETS}/poster-paris.jpg`, label: "Paris", selected: true },
- { src: `${ASSETS}/poster-newyork.jpg`, label: "New York" },
+ { src: `${ASSETS}/poster-paris.jpg`, label: paris, selected: true },
+ { src: `${ASSETS}/poster-newyork.jpg`, label: newYork },
],
},
videoSrc: `${ASSETS}/travel-loop.mp4`,
videoPoster: `${ASSETS}/poster-paris.jpg`,
- previewCaption: "Live the romance",
+ previewCaption: t("projects.posters.captionParis"),
timelineSeconds: 8,
clips: [
- { label: "Paris — Live the romance", thumb: `${ASSETS}/poster-paris.jpg`, seconds: 4, selected: true },
- { label: "New York — Rise above the city", thumb: `${ASSETS}/poster-newyork.jpg`, seconds: 4 },
+ { label: t("projects.posters.clipParis"), thumb: `${ASSETS}/poster-paris.jpg`, seconds: 4, selected: true },
+ { label: t("projects.posters.clipNewYork"), thumb: `${ASSETS}/poster-newyork.jpg`, seconds: 4 },
],
captions: [
- { text: "Live the romance", at: 0.4, seconds: 3.2 },
- { text: "Rise above the city", at: 4.4, seconds: 3.2 },
+ { text: t("projects.posters.captionParis"), at: 0.4, seconds: 3.2 },
+ { text: t("projects.posters.captionNewYork"), at: 4.4, seconds: 3.2 },
],
audioLabel: "Parisian waltz.mp3",
audioDuration: "8.0s",
sfx: [],
chat: [
- {
- role: "user",
- text: "Make two hand-painted travel posters — Paris and New York, same woman crossing the street in both.",
- },
+ { role: "user", text: t("projects.posters.chat1") },
{
role: "assistant",
- text: "Here are the two posters, matched palette and typography:",
+ text: t("projects.posters.chat2"),
cards: [
- { src: `${ASSETS}/poster-paris.jpg`, label: "Paris" },
- { src: `${ASSETS}/poster-newyork.jpg`, label: "New York" },
+ { src: `${ASSETS}/poster-paris.jpg`, label: paris },
+ { src: `${ASSETS}/poster-newyork.jpg`, label: newYork },
],
},
- {
- role: "user",
- text: "Animate them — she walks, slow camera drift, keep the painted texture. Then cut them together with captions and music.",
- },
- {
- role: "assistant",
- text: "Rendered two 4s clips and assembled the timeline with captions and a waltz. Want a different track?",
- },
+ { role: "user", text: t("projects.posters.chat3") },
+ { role: "assistant", text: t("projects.posters.chat4") },
],
- },
- {
+ };
+}
+
+function railwayProject(t: MockT): MockProject {
+ const canyonRun = t("projects.railway.canyonRun");
+ const onTheRoof = t("projects.railway.onTheRoof");
+ const bicycleChase = t("projects.railway.bicycleChase");
+ return {
id: "railway",
- switcherLabel: "Railway mystery",
- name: "The Railway Mystery",
+ switcherLabel: t("projects.railway.switcherLabel"),
+ name: t("projects.railway.name"),
aspect: "16:9",
panel: {
tab: "video",
- prompt:
- "Franco-Belgian comic style, early-1900s animation with film grain: a steam train races a cliffside railway through a mountain canyon; a cloaked figure rides the carriage roof; a boy on a bicycle gives chase",
+ prompt: t("projects.railway.prompt"),
results: [
- { src: `${ASSETS}/chase-1.jpg`, label: "Canyon run", duration: "3.2s", selected: true },
- { src: `${ASSETS}/chase-2.jpg`, label: "On the roof", duration: "2.8s" },
- { src: `${ASSETS}/chase-3.jpg`, label: "Bicycle chase", duration: "4.0s" },
+ { src: `${ASSETS}/chase-1.jpg`, label: canyonRun, duration: "3.2s", selected: true },
+ { src: `${ASSETS}/chase-2.jpg`, label: onTheRoof, duration: "2.8s" },
+ { src: `${ASSETS}/chase-3.jpg`, label: bicycleChase, duration: "4.0s" },
],
},
videoSrc: `${ASSETS}/railway-loop.mp4`,
@@ -166,114 +175,99 @@ export const MOCK_PROJECTS: MockProject[] = [
previewCaption: "",
timelineSeconds: 10,
clips: [
- { label: "Canyon run", thumb: `${ASSETS}/chase-1.jpg`, seconds: 3.2 },
- { label: "On the roof", thumb: `${ASSETS}/chase-2.jpg`, seconds: 2.8, selected: true },
- { label: "Bicycle chase", thumb: `${ASSETS}/chase-3.jpg`, seconds: 4 },
+ { label: canyonRun, thumb: `${ASSETS}/chase-1.jpg`, seconds: 3.2 },
+ { label: onTheRoof, thumb: `${ASSETS}/chase-2.jpg`, seconds: 2.8, selected: true },
+ { label: bicycleChase, thumb: `${ASSETS}/chase-3.jpg`, seconds: 4 },
],
captions: [],
audioLabel: "Steam & Strings.mp3",
audioDuration: "10.0s",
sfx: [
- { text: "train whistle", at: 0.6, seconds: 1.4 },
- { text: "wheels on gravel", at: 6.4, seconds: 2.2 },
+ { text: t("projects.railway.trainWhistle"), at: 0.6, seconds: 1.4 },
+ { text: t("projects.railway.wheelsOnGravel"), at: 6.4, seconds: 2.2 },
],
chat: [
- {
- role: "user",
- text: "Storyboard a 1920s comic-style chase: a mysterious figure on a steam train, a kid chasing on a bicycle through a canyon.",
- },
+ { role: "user", text: t("projects.railway.chat1") },
+ { role: "assistant", text: t("projects.railway.chat2") },
+ { role: "user", text: t("projects.railway.chat3") },
{
role: "assistant",
- text: "Three shots: 1) the train threading the canyon, 2) the cloaked figure steadying himself on the roof, 3) the boy pedaling hard beside the tracks.",
- },
- { role: "user", text: "Animate all three in that ligne-claire style." },
- {
- role: "assistant",
- text: "Rendered the three shots and cut them with a brass-and-strings score:",
+ text: t("projects.railway.chat4"),
cards: [
- { src: `${ASSETS}/chase-1.jpg`, label: "Shot 1", duration: "3.2s" },
- { src: `${ASSETS}/chase-2.jpg`, label: "Shot 2", duration: "2.8s" },
- { src: `${ASSETS}/chase-3.jpg`, label: "Shot 3", duration: "4.0s" },
+ { src: `${ASSETS}/chase-1.jpg`, label: t("projects.railway.shot", { number: 1 }), duration: "3.2s" },
+ { src: `${ASSETS}/chase-2.jpg`, label: t("projects.railway.shot", { number: 2 }), duration: "2.8s" },
+ { src: `${ASSETS}/chase-3.jpg`, label: t("projects.railway.shot", { number: 3 }), duration: "4.0s" },
],
},
- {
- role: "user",
- text: "Add a train whistle when it clears the tunnel, and gravel under the bicycle.",
- },
- {
- role: "assistant",
- text: "Placed both on the effects track and mixed them under the score. Want the cut tightened where the train enters the tunnel?",
- },
+ { role: "user", text: t("projects.railway.chat5") },
+ { role: "assistant", text: t("projects.railway.chat6") },
],
- },
-];
+ };
+}
// The mock the onboarding sequence shows: a real project a parent built from
// one voiceover of their son introducing himself, so the slide's subject — the
// assistant working the timeline mid-conversation — is what the frame shows.
-const VOICEOVER =
- "AI voice — 안녕 내 이름은 메이슨이고 한국에 사는 꼬마 소년이야 나는 학교에 가는 걸 좋아해";
-const SCENE_PROMPT =
- "Hand-drawn 2D cartoon animation with bold black outlines,…";
+// The voiceover's speech is the recording's own Korean in every language.
+const VOICEOVER_SPEECH = "안녕 내 이름은 메이슨이고 한국에 사는 꼬마 소년이야 나는 학교에 가는 걸 좋아해";
-export const ONBOARDING_PROJECT: MockProject = {
- id: "mason",
- switcherLabel: "Mason",
- name: "Cartoon",
- aspect: "9:16",
- panel: {
- tab: "media",
- templates: [
- { name: "Template", duration: "0:03.9", items: 2 },
- { name: "Template", duration: "0:05.3", items: 2 },
- ],
- items: [
- { kind: "audio", handle: "a1", name: VOICEOVER, duration: "0:16.2" },
- { kind: "video", handle: "v1", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
- { kind: "video", handle: "v2", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
- { kind: "image", handle: "i1", name: "Screenshot 2026-07-19 at 9.57.03 PM.png", thumb: `${ASSETS}/mason-shot.jpg` },
- { kind: "video", handle: "v3", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
- { kind: "video", handle: "v4", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
- { kind: "video", handle: "v5", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
- { kind: "video", handle: "v6", name: SCENE_PROMPT, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
- ],
- },
- videoSrc: `${ASSETS}/mason-loop.mp4`,
- videoPoster: `${ASSETS}/mason-walk.jpg`,
- previewCaption: "",
- timelineSeconds: 16.28,
- clips: [
- { label: "Walking to school", thumb: `${ASSETS}/mason-walk.jpg`, seconds: 4.8, muted: true },
- { label: "School gates", thumb: `${ASSETS}/mason-school.jpg`, seconds: 3.2, muted: true },
- { label: "Fish tank", thumb: `${ASSETS}/mason-fish.jpg`, seconds: 2.2, muted: true },
- { label: "Strawberries", thumb: `${ASSETS}/mason-strawberry.jpg`, seconds: 2, muted: true },
- { label: "Soccer", thumb: `${ASSETS}/mason-soccer.jpg`, seconds: 1.3, muted: true },
- { label: "Taekwondo", thumb: `${ASSETS}/mason-taekwondo.jpg`, seconds: 1.3, muted: true },
- { label: "Swimming", thumb: `${ASSETS}/mason-swim.jpg`, seconds: 1.48, muted: true },
- ],
- captions: [],
- audioLabel: VOICEOVER,
- audioDuration: "16.3s",
- sfx: [],
- chat: [
- {
- role: "user",
- text: "@a1 is my son Mason introducing himself in Korean. Draw a scene for everything he mentions and cut it to the audio.",
- },
- {
- role: "assistant",
- tool: { name: "generate_video", count: 3 },
- text: "I've cleared the strawberry eating scene at the end of the timeline and started generating three brand new scenes matching Mason's favorite sports: soccer, taekwondo, and swimming!\n\nThey will render in the background and pop right onto your timeline starting at 9.5 seconds to match the audio perfectly. Let me know if Mason needs any more athletic training!",
- portrait: true,
- cards: [
- { src: `${ASSETS}/mason-soccer.jpg` },
- { src: `${ASSETS}/mason-taekwondo.jpg` },
- { src: `${ASSETS}/mason-swim.jpg` },
+export function onboardingProject(t: MockT): MockProject {
+ const voiceover = t("projects.mason.voiceover", { text: VOICEOVER_SPEECH });
+ const scenePrompt = t("projects.mason.scenePrompt");
+ const template = t("projects.mason.template");
+ return {
+ id: "mason",
+ switcherLabel: t("projects.mason.switcherLabel"),
+ name: t("projects.mason.name"),
+ aspect: "9:16",
+ panel: {
+ tab: "media",
+ templates: [
+ { name: template, duration: "0:03.9", items: 2 },
+ { name: template, duration: "0:05.3", items: 2 },
+ ],
+ items: [
+ { kind: "audio", handle: "a1", name: voiceover, duration: "0:16.2" },
+ { kind: "video", handle: "v1", name: scenePrompt, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
+ { kind: "video", handle: "v2", name: scenePrompt, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
+ { kind: "image", handle: "i1", name: "Screenshot 2026-07-19 at 9.57.03 PM.png", thumb: `${ASSETS}/mason-shot.jpg` },
+ { kind: "video", handle: "v3", name: scenePrompt, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
+ { kind: "video", handle: "v4", name: scenePrompt, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
+ { kind: "video", handle: "v5", name: scenePrompt, thumb: `${ASSETS}/mason-school.jpg`, duration: "0:10.0" },
+ { kind: "video", handle: "v6", name: scenePrompt, thumb: `${ASSETS}/mason-fish.jpg`, duration: "0:10.0" },
],
},
- {
- role: "user",
- text: "he also likes strawberries. you need to match the audio",
- },
- ],
-};
+ videoSrc: `${ASSETS}/mason-loop.mp4`,
+ videoPoster: `${ASSETS}/mason-walk.jpg`,
+ previewCaption: "",
+ timelineSeconds: 16.28,
+ clips: [
+ { label: t("projects.mason.walkingToSchool"), thumb: `${ASSETS}/mason-walk.jpg`, seconds: 4.8, muted: true },
+ { label: t("projects.mason.schoolGates"), thumb: `${ASSETS}/mason-school.jpg`, seconds: 3.2, muted: true },
+ { label: t("projects.mason.fishTank"), thumb: `${ASSETS}/mason-fish.jpg`, seconds: 2.2, muted: true },
+ { label: t("projects.mason.strawberries"), thumb: `${ASSETS}/mason-strawberry.jpg`, seconds: 2, muted: true },
+ { label: t("projects.mason.soccer"), thumb: `${ASSETS}/mason-soccer.jpg`, seconds: 1.3, muted: true },
+ { label: t("projects.mason.taekwondo"), thumb: `${ASSETS}/mason-taekwondo.jpg`, seconds: 1.3, muted: true },
+ { label: t("projects.mason.swimming"), thumb: `${ASSETS}/mason-swim.jpg`, seconds: 1.48, muted: true },
+ ],
+ captions: [],
+ audioLabel: voiceover,
+ audioDuration: "16.3s",
+ sfx: [],
+ chat: [
+ { role: "user", text: t("projects.mason.chat1") },
+ {
+ role: "assistant",
+ tool: { name: "generate_video", count: 3 },
+ text: t("projects.mason.chat2"),
+ portrait: true,
+ cards: [
+ { src: `${ASSETS}/mason-soccer.jpg` },
+ { src: `${ASSETS}/mason-taekwondo.jpg` },
+ { src: `${ASSETS}/mason-swim.jpg` },
+ ],
+ },
+ { role: "user", text: t("projects.mason.chat3") },
+ ],
+ };
+}
diff --git a/site/src/cut/components/groupPanelParity.test.ts b/site/src/cut/components/groupPanelParity.test.ts
index 60b4a9a1..1d239bee 100644
--- a/site/src/cut/components/groupPanelParity.test.ts
+++ b/site/src/cut/components/groupPanelParity.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
+import media from "@/i18n/messages/en/media.json";
/**
* The group panel shows the fields every selected item has. Each timeline
@@ -11,16 +12,21 @@ import { fileURLToPath } from "node:url";
const src = readFileSync(fileURLToPath(new URL("./GroupPanel.tsx", import.meta.url)), "utf8");
const inspector = readFileSync(fileURLToPath(new URL("./Inspector.tsx", import.meta.url)), "utf8");
-// A row's label as the source spells it, whether on the row, handed to a
-// helper, or built from a template; the sound quality row is the inspector's
-// own, mounted here.
-const names = (label: string) =>
- src.includes(`"${label}"`) || src.includes(`\`${label}`) || (label === "Sound quality" && src.includes("<SoundQualityRow"));
+// A row's label is a message in the panel's catalog; the source names it by
+// its key, on the row or handed to a helper. The sound quality row is the
+// inspector's own, mounted here.
+const names = (label: string) => {
+ if (label === "Sound quality") {
+ return src.includes("<SoundQualityRow");
+ }
+ const key = Object.entries(media.groupPanel).find(([, english]) => english === label)?.[0];
+ return !!key && src.includes(`"${key}"`);
+};
const SHARED: Record<string, string[]> = {
"video clips": ["Speed", "Reverse", "Volume", "Mute audio", "Sound quality", "Framing", "Zoom", "Flip", "Rotation", "Opacity", "Hidden", "Border", "Shadow"],
"audio clips": ["Speed", "Reverse", "Volume", "Duck others", "Fade in", "Fade out", "Sound quality", "Hidden"],
- titles: ["Font", "Bold", "Italic", "Align ${a}", "Text size", "Line height", "Letter spacing", "Text box width", "Color", "Outline", "Shadow", "Backdrop", "Position", "Rotation", "Opacity", "Hidden"],
+ titles: ["Font", "Bold", "Italic", "Align left", "Align center", "Align right", "Text size", "Line height", "Letter spacing", "Text box width", "Color", "Outline", "Shadow", "Backdrop", "Position", "Rotation", "Opacity", "Hidden"],
shapes: ["Fill color", "Corner radius", "Outline", "Position", "Rotation", "Opacity", "Hidden"],
stickers: ["Sticker size", "Position", "Rotation", "Opacity", "Hidden"],
effects: ["Effect amount", "Depth", "Zoom speed", "Hidden"],
diff --git a/site/src/cut/components/hostedError.tsx b/site/src/cut/components/hostedError.tsx
index be86d545..81a4326e 100644
--- a/site/src/cut/components/hostedError.tsx
+++ b/site/src/cut/components/hostedError.tsx
@@ -1,7 +1,11 @@
+import { useTranslations } from "next-intl";
+
import { NO_CREDITS_MESSAGE } from "@/cut/lib/credits";
import { creditsUrl } from "@/cut/lib/generate";
import { useOutOfCredits } from "@/cut/lib/hosted";
+import { failureText } from "@/cut/lib/userError";
import { openUpgrade } from "@/cut/lib/upgrade";
+import { useDescribeError } from "@/i18n/describeError";
/** Opens the upgrade dialog on its credits wall. A surface without the dialog
* (the ChatGPT card) opens the credits page. */
@@ -12,28 +16,37 @@ export function openCreditsWall(): void {
window.open(creditsUrl(), "_blank", "noreferrer");
}
-/** A hosted-inference error message (chat reply or generation tile). A balance
+/** A hosted-inference failure (chat reply or generation tile): an Error, a
+ * string, or a record carrying `error` and `errorCode` (a job). A balance
* failure reads "Insufficient credits, reload here" with the link to the
- * credits wall inline; any other error (or a missing message) renders as plain text.
+ * credits wall inline; any other failure reads through the shared describer, and
+ * a missing one reads `fallback`.
* Surfaces inside the chat panel pass `link={false}` and lean on the composer's
* credits tab for the link — but that tab only rises for an empty balance, so a
* balance merely short of one generation keeps its link here. */
-export function HostedErrorText({ error, link = true }: { error?: string; link?: boolean }) {
+export function HostedErrorText({ error, fallback, link = true }: { error?: unknown; fallback?: string; link?: boolean }) {
+ const t = useTranslations("chat.hostedError");
+ const describeError = useDescribeError();
const tabCarriesLink = useOutOfCredits((s) => s.out);
- if (error === NO_CREDITS_MESSAGE) {
- if (!link && tabCarriesLink) return <>{NO_CREDITS_MESSAGE}</>;
+ // The English constant is what every surface and the model compare; the
+ // reader sees it in the page's language.
+ if (failureText(error) === NO_CREDITS_MESSAGE) {
+ if (!link && tabCarriesLink) return <>{t("insufficientCredits")}</>;
return (
<>
- {error},{" "}
- <button
- type="button"
- className="cursor-pointer font-medium underline hover:no-underline"
- onClick={openCreditsWall}
- >
- reload here
- </button>
+ {t.rich("insufficientCreditsReload", {
+ link: (chunks) => (
+ <button
+ type="button"
+ className="cursor-pointer font-medium underline hover:no-underline"
+ onClick={openCreditsWall}
+ >
+ {chunks}
+ </button>
+ ),
+ })}
</>
);
}
- return <>{error ?? "Failed."}</>;
+ return <>{describeError(error, fallback ?? t("failed"))}</>;
}
diff --git a/site/src/cut/components/onboarding/CutOnboarding.tsx b/site/src/cut/components/onboarding/CutOnboarding.tsx
index ca9776b1..8c825b4a 100644
--- a/site/src/cut/components/onboarding/CutOnboarding.tsx
+++ b/site/src/cut/components/onboarding/CutOnboarding.tsx
@@ -1,6 +1,7 @@
"use client";
import { DonkeyMark } from "@/components/DonkeyMark";
+import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArrowLeft, ArrowRight } from "lucide-react";
@@ -60,6 +61,7 @@ const doneHere = (userId: string): boolean =>
// connect gate; nothing here grants, switches, or configures anything. The one
// thing it writes is what it asks for: where the account heard about us.
export function CutOnboarding() {
+ const t = useTranslations("onboarding.sequence");
const base = useCutBase();
// Mounted inside a SessionGate, so the account is already bound. Read from
// the binding rather than the session object, which answers null while the
@@ -291,7 +293,7 @@ export function CutOnboarding() {
<div
role="dialog"
aria-modal="true"
- aria-label="Welcome to Donkey Cut"
+ aria-label={t("dialogLabel")}
className="fixed inset-0 z-[80] flex flex-col bg-cream font-system text-foreground antialiased dark:bg-background"
>
<div className="flex shrink-0 items-center justify-between px-6 py-2 md:px-10 md:py-2.5">
@@ -306,7 +308,7 @@ export function CutOnboarding() {
onClick={() => finish(true)}
className="text-foreground/70"
>
- Skip
+ {t("skip")}
</Button>
) : null}
</div>
@@ -345,7 +347,7 @@ export function CutOnboarding() {
onClick={back}
className={cn("gap-1.5 text-foreground/70", step === 0 && "invisible")}
>
- <ArrowLeft className="size-4" /> Back
+ <ArrowLeft className="size-4" /> {t("back")}
</Button>
<div className="flex items-center gap-1.5">
@@ -373,10 +375,10 @@ export function CutOnboarding() {
)}
>
{done ? (
- "Done"
+ t("done")
) : (
<>
- Next
+ {t("next")}
<ArrowRight className="size-4" />
</>
)}
diff --git a/site/src/cut/components/onboarding/slides/AiChat.tsx b/site/src/cut/components/onboarding/slides/AiChat.tsx
index 9e62ee87..4ebd7e98 100644
--- a/site/src/cut/components/onboarding/slides/AiChat.tsx
+++ b/site/src/cut/components/onboarding/slides/AiChat.tsx
@@ -1,7 +1,8 @@
"use client";
+import { useTranslations } from "next-intl";
+
import { EditorMock } from "@/cut/components/editor-mock/EditorMock";
-import { ONBOARDING_PROJECT } from "@/cut/components/editor-mock/mockData";
// The one slide that uses the whole window rather than the sequence's reading
// column. The editor is the layout — the slide is exactly as tall as the mock,
@@ -24,7 +25,7 @@ export function AiChatSlide() {
<div className="relative mx-auto w-[min(100%,86vh)]">
<div className="pointer-events-none [mask-image:linear-gradient(to_right,transparent_10%,black_70%)] [-webkit-mask-image:linear-gradient(to_right,transparent_10%,black_70%)]">
<EditorMock
- project={ONBOARDING_PROJECT}
+ project="onboarding"
view="ai"
showSwitcher={false}
frame="flat"
@@ -54,19 +55,17 @@ export function AiChatSlide() {
}
function Copy() {
+ const t = useTranslations("onboarding.aiChat");
return (
<div className="max-w-[620px]">
<h2 className="text-[clamp(26px,3.2vw,38px)] leading-[1.05] font-semibold tracking-[-0.02em]">
- Chat with your editor.
+ {t("title")}
</h2>
<p className="mt-5 text-[16.5px] leading-[1.55] text-foreground/70">
- The AI has access to your entire project. Ask it to trim clips, generate
- missing shots, write subtitles, add voiceovers, rearrange your timeline,
- or answer questions about your footage.
+ {t("body")}
</p>
<p className="mt-4 text-[16.5px] leading-[1.55] text-foreground/70">
- Works out of the box with Gemini, or use your own Claude or Codex
- subscription.
+ {t("models")}
</p>
</div>
);
diff --git a/site/src/cut/components/onboarding/slides/Credits.tsx b/site/src/cut/components/onboarding/slides/Credits.tsx
index ead0ae0f..453178d8 100644
--- a/site/src/cut/components/onboarding/slides/Credits.tsx
+++ b/site/src/cut/components/onboarding/slides/Credits.tsx
@@ -1,10 +1,10 @@
"use client";
+import { useFormatter, useLocale, useTranslations } from "next-intl";
import { useEffect, useRef } from "react";
import { burstConfetti } from "@/cut/components/onboarding/confetti";
import { creditCountLabel, creditsFromDollars } from "@/lib/credits/format-credits";
-import { formatCreditExpiry } from "@/lib/credits/top-up";
// The signup grant already landed when the account was created, so this slide
// never grants anything — it says what's there: the credits the grant carried,
@@ -18,6 +18,9 @@ export function CreditsSlide({
credits: string;
expiresAt: string | null;
}) {
+ const t = useTranslations("onboarding.credits");
+ const format = useFormatter();
+ const locale = useLocale();
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
@@ -42,21 +45,22 @@ export function CreditsSlide({
a couple of steps down and thin beside it. */}
<h2 className="flex flex-wrap items-baseline justify-center gap-x-4 leading-[1.02] tracking-[-0.03em]">
<span className="text-[clamp(40px,7.4vw,84px)] font-semibold text-coral tabular-nums">
- {creditCountLabel(creditsFromDollars(credits, "down"))}
+ {creditCountLabel(creditsFromDollars(credits, "down"), locale)}
</span>
<span className="text-[clamp(26px,4.4vw,52px)] font-light">
- on us
+ {t("onUs")}
</span>
</h2>
{/* Ragged right on a narrow measure: the line breaks stay put instead
of the last line floating in the middle of the slide. */}
<p className="mx-auto mt-4 max-w-[460px] text-left text-[16px] leading-[1.55] text-foreground/70">
- Already in your account — nothing to claim. Spend them on generated
- video, audio and images.
+ {t("body")}
</p>
{expiresAt !== null && (
<p className="mt-3 text-[13px] leading-[1.5] text-foreground/70">
- Expires {formatCreditExpiry(new Date(expiresAt))}.
+ {t("expires", {
+ date: format.dateTime(new Date(expiresAt), { day: "numeric", month: "long", year: "numeric" }),
+ })}
</p>
)}
</div>
diff --git a/site/src/cut/components/onboarding/slides/Modes.tsx b/site/src/cut/components/onboarding/slides/Modes.tsx
index 245e40ec..99ff0680 100644
--- a/site/src/cut/components/onboarding/slides/Modes.tsx
+++ b/site/src/cut/components/onboarding/slides/Modes.tsx
@@ -1,18 +1,20 @@
"use client";
import { Cloud, Laptop } from "lucide-react";
+import { useTranslations } from "next-intl";
import { TapedCard } from "@/app/_components/landing/LandingPrimitives";
import { CheckBullet } from "@/cut/components/onboarding/CheckBullet";
export function ModesSlide() {
+ const t = useTranslations("onboarding.modes");
return (
<div className="mx-auto w-full max-w-[760px]">
<h2 className="text-center text-[clamp(24px,3vw,32px)] leading-[1.1] font-semibold tracking-[-0.02em] text-balance">
- Works in the cloud or on your Mac
+ {t("title")}
</h2>
<p className="mx-auto mt-3 max-w-[560px] text-center text-[16px] leading-[1.5] text-foreground/70 italic">
- Same editor. Choose what works for you.
+ {t("subtitle")}
</p>
{/* The landing's taped cards, so the two places to work are framed the
@@ -20,24 +22,20 @@ export function ModesSlide() {
<div className="mt-7 grid gap-4 md:mt-10 md:grid-cols-2 md:gap-5">
<Mode
icon={<Cloud className="size-5" />}
- title="In the cloud"
+ title={t("cloudTitle")}
tape="coral"
- points={["No install", "Works in any browser", "We handle rendering"]}
+ points={[t("cloudNoInstall"), t("cloudAnyBrowser"), t("cloudRendering")]}
/>
<Mode
icon={<Laptop className="size-5" />}
- title="On your Mac"
+ title={t("macTitle")}
tape="yellow"
- points={[
- "Your files stay local",
- "Uses your Mac's hardware",
- "Faster exports & AI features",
- ]}
+ points={[t("macLocalFiles"), t("macHardware"), t("macFaster")]}
/>
</div>
<p className="mt-7 text-center text-[15px] leading-[1.5] text-foreground/70 md:mt-9">
- Automatically switches between cloud and local when available.
+ {t("switching")}
</p>
</div>
);
diff --git a/site/src/cut/components/onboarding/slides/Plans.tsx b/site/src/cut/components/onboarding/slides/Plans.tsx
index de444237..05622dde 100644
--- a/site/src/cut/components/onboarding/slides/Plans.tsx
+++ b/site/src/cut/components/onboarding/slides/Plans.tsx
@@ -1,12 +1,13 @@
"use client";
import { Check } from "lucide-react";
+import { useLocale, useTranslations } from "next-intl";
import { TapedCard } from "@/app/_components/landing/LandingPrimitives";
-import { CUT_PRO } from "@/app/cut/_components/landing/cutPricingPlans";
+import { useCutPro } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";
import { Button } from "@/components/ui/button";
import { priceLabel } from "@/cut/components/IntroOffer";
-import { countdownLabel, useNow } from "@/cut/components/OfferDialog";
+import { countdownParts, useNow } from "@/cut/components/OfferDialog";
import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
import { useIntroOffer, type IntroOffer } from "@/queries/billing";
@@ -19,16 +20,18 @@ import "../onboarding.css";
// storage wall and the billing page start. While the intro offer is open the
// card prices the discount and counts down to its end.
export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
+ const t = useTranslations("onboarding.plans");
+ const plan = useCutPro();
const pro = useUpgradeToPro();
const offer = useIntroOffer().data ?? null;
return (
<div className="mx-auto w-full max-w-[520px]">
<h2 className="text-center text-[clamp(24px,3vw,32px)] leading-[1.1] font-semibold tracking-[-0.02em]">
- Simple pricing
+ {t("title")}
</h2>
<p className="mt-3 text-center text-[16px] text-foreground/70">
- The editor is free. Pay only for AI generated media.
+ {t("subtitle")}
</p>
<div className="mt-8">
@@ -45,19 +48,19 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
) : (
<>
<div className="mt-4 text-[clamp(34px,4.4vw,48px)] leading-[0.95] font-semibold">
- {CUT_PRO.price}
+ {plan.price}
</div>
<div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
- For individuals
+ {t("forIndividuals")}
</div>
</>
)}
<p className="mt-5 text-[15px] leading-[1.55] text-[#1a1a1a]">
- {CUT_PRO.body}
+ {plan.body}
</p>
<div className="mt-6 grid gap-2.5">
- {CUT_PRO.features.map((feature) => (
+ {plan.features.map((feature) => (
<div
key={feature}
className="flex items-center gap-2.5 text-[14px] font-semibold"
@@ -75,7 +78,7 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
disabled={pro.isPending}
className="mt-7 h-11 rounded-full bg-ink px-6 text-[15px] text-white hover:bg-ink/90"
>
- {offer ? `Get ${offer.percentOff}% off Pro` : "Get Pro"}
+ {offer ? t("getProOff", { percent: offer.percentOff }) : t("getPro")}
</Button>
</div>
</TapedCard>
@@ -87,7 +90,7 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
onClick={onSkipPro}
className="text-[15px] text-foreground/70 underline-offset-4 transition-colors hover:text-foreground hover:underline"
>
- Continue with free
+ {t("continueFree")}
</button>
</div>
</div>
@@ -97,24 +100,25 @@ export function PlansSlide({ onSkipPro }: { onSkipPro: () => void }) {
// The discounted price beside the struck-through one, what it covers, and
// the time left to take it.
function IntroPrice({ offer }: { offer: IntroOffer }) {
+ const t = useTranslations("onboarding.plans");
+ const locale = useLocale();
const now = useNow();
- const covers = offer.months === 1 ? "For your first month" : `Per month for your first ${offer.months} months`;
return (
<>
<div className="mt-4 flex items-baseline gap-3">
<span className="text-[clamp(34px,4.4vw,48px)] leading-[0.95] font-semibold">
- {priceLabel(offer.introCents)}
+ {priceLabel(offer.introCents, locale)}
</span>
<span className="text-[22px] font-semibold text-[#201715]/40 line-through decoration-2">
- {priceLabel(offer.priceCents)}
+ {priceLabel(offer.priceCents, locale)}
</span>
</div>
<div className="mt-2.5 text-[13px] font-semibold text-[#201715]">
- {covers}, then {priceLabel(offer.priceCents)}/month
+ {t("covers", { months: offer.months, price: priceLabel(offer.priceCents, locale) })}
</div>
<div className="mt-4 inline-flex rounded-full bg-ink px-3 py-1 text-[12px] font-semibold text-white tabular-nums">
- {offer.percentOff}% off ends in {countdownLabel(offer.endsAt, now)}
+ {t("endsIn", { percent: offer.percentOff, ...countdownParts(offer.endsAt, now) })}
</div>
</>
);
diff --git a/site/src/cut/components/onboarding/slides/Referral.tsx b/site/src/cut/components/onboarding/slides/Referral.tsx
index 5f5a2c41..93ada525 100644
--- a/site/src/cut/components/onboarding/slides/Referral.tsx
+++ b/site/src/cut/components/onboarding/slides/Referral.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useEffect, useRef, type ReactNode } from "react";
import { Check, PenLine, Search, Users } from "lucide-react";
@@ -36,6 +37,7 @@ export function ReferralSlide({
otherText,
onOtherTextChange,
}: Props) {
+ const t = useTranslations("onboarding.referral");
const otherActive = selected.includes("other");
// The field stays mounted so it can unfurl, which rules out autoFocus.
const otherInput = useRef<HTMLInputElement>(null);
@@ -46,10 +48,10 @@ export function ReferralSlide({
return (
<div className="mx-auto w-full max-w-[440px]">
<h2 className="text-center text-[clamp(24px,3vw,32px)] leading-[1.1] font-semibold tracking-[-0.02em]">
- How did you hear about us?
+ {t("title")}
</h2>
<p className="mt-3 text-center text-[16px] text-foreground/70">
- Pick as many as apply — it tells us where to show up next.
+ {t("body")}
</p>
<div className="mt-8 flex flex-col gap-2">
{REFERRAL_SOURCES.map((source) => {
@@ -72,7 +74,7 @@ export function ReferralSlide({
<span className="grid size-5 shrink-0 place-items-center">
{MARKS[source.id]}
</span>
- <span className="flex-1">{source.label}</span>
+ <span className="flex-1">{t(`sources.${source.id}`)}</span>
<Check className={cn("size-4", active ? "opacity-100" : "opacity-0")} />
</button>
{/* The tray hangs off the row absolutely so opening it moves
@@ -94,7 +96,7 @@ export function ReferralSlide({
type="text"
value={otherText}
onChange={(event) => onOtherTextChange(event.target.value)}
- placeholder="Tell us where"
+ placeholder={t("otherPlaceholder")}
maxLength={REFERRAL_OTHER_MAX_LENGTH}
tabIndex={active ? 0 : -1}
className="w-full rounded-b-xl border border-t-0 border-foreground bg-card px-4 pt-6 pb-3 text-[15px] outline-none placeholder:text-muted-foreground"
diff --git a/site/src/cut/components/onboarding/slides/Welcome.tsx b/site/src/cut/components/onboarding/slides/Welcome.tsx
index 66f7752e..0cade556 100644
--- a/site/src/cut/components/onboarding/slides/Welcome.tsx
+++ b/site/src/cut/components/onboarding/slides/Welcome.tsx
@@ -1,20 +1,21 @@
"use client";
+import { useTranslations } from "next-intl";
+
import { EditorMock } from "@/cut/components/editor-mock/EditorMock";
-import { ONBOARDING_PROJECT } from "@/cut/components/editor-mock/mockData";
export function WelcomeSlide() {
+ const t = useTranslations("onboarding.welcome");
return (
<div className="flex flex-col items-center gap-9 text-center">
{/* Sized to hold the headline on one line: the clamp's vw term shrinks it
with the window rather than letting it wrap. */}
<div className="max-w-[860px]">
<h2 className="text-[clamp(22px,3.1vw,34px)] leading-[1.1] font-semibold tracking-[-0.02em]">
- Edit videos by chatting.
+ {t("title")}
</h2>
<p className="mt-4 text-[17px] leading-[1.55] text-foreground/70">
- Trim clips, add captions, generate images, or create new
- scenes&mdash;all from chat.
+ {t("body")}
</p>
</div>
{/* Contained rather than width-driven: on a short window the mock gives
@@ -22,7 +23,7 @@ export function WelcomeSlide() {
cancels the slide's padding and runs edge to edge. */}
<div className="-mx-6 h-[min(56vh,640px)] w-[calc(100%+3rem)] max-w-[1060px] md:mx-0 md:w-full">
<EditorMock
- project={ONBOARDING_PROJECT}
+ project="onboarding"
fit="contain"
showSwitcher={false}
frame="card"
diff --git a/site/src/cut/components/panelBits.tsx b/site/src/cut/components/panelBits.tsx
index 0a916496..9b001a67 100644
--- a/site/src/cut/components/panelBits.tsx
+++ b/site/src/cut/components/panelBits.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useTranslations } from "next-intl";
import { useRef } from "react";
import { Info, RotateCcw } from "lucide-react";
import { useEditor } from "@/cut/lib/store";
@@ -42,12 +43,13 @@ export function InfoTip({
side?: "top" | "bottom";
children: React.ReactNode;
}) {
+ const t = useTranslations("inspector.controls");
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger
className="grid size-4 place-items-center text-muted-foreground/70 transition-colors hover:text-foreground"
- aria-label={`About ${label.toLowerCase()}`}
+ aria-label={t("about", { label: label.toLowerCase() })}
>
<Info className="size-3.5" />
</TooltipTrigger>
diff --git a/site/src/cut/components/searchSuggestions.test.tsx b/site/src/cut/components/searchSuggestions.test.tsx
index b53718e5..1e7d5823 100644
--- a/site/src/cut/components/searchSuggestions.test.tsx
+++ b/site/src/cut/components/searchSuggestions.test.tsx
@@ -1,12 +1,13 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
+import { WithIntl } from "@/i18n/testing";
import { SearchSuggestions } from "./SearchSuggestions";
// A frame whose document takes neither theme gets an opaque canvas from the
// browser whenever the page is dark, which shows white around the chips.
test("the suggestion frame takes the page's light or dark theme", () => {
const output = { display: { searchSuggestions: ['<div class="container">chips</div>'] } };
- const html = renderToStaticMarkup(<SearchSuggestions output={output} />);
+ const html = renderToStaticMarkup(<WithIntl><SearchSuggestions output={output} /></WithIntl>);
const doc = /srcDoc="([^"]*)"/i.exec(html)?.[1].replaceAll("&quot;", '"').replaceAll("&lt;", "<").replaceAll("&gt;", ">") ?? "";
expect(doc).toContain('<meta name="color-scheme" content="light dark">');
});
diff --git a/site/src/cut/components/selectionMenu.test.ts b/site/src/cut/components/selectionMenu.test.tsx
similarity index 57%
rename from site/src/cut/components/selectionMenu.test.ts
rename to site/src/cut/components/selectionMenu.test.tsx
index 12ebaf34..a0a628f4 100644
--- a/site/src/cut/components/selectionMenu.test.ts
+++ b/site/src/cut/components/selectionMenu.test.tsx
@@ -1,27 +1,39 @@
import { describe, expect, test } from "bun:test";
-import { foldersGoNote, phoneGoNote, pickLabel } from "./selectionMenu";
+import { renderToStaticMarkup } from "react-dom/server";
+import { WithIntl } from "@/i18n/testing";
+import { usePickWords } from "./selectionMenu";
+
+// The words come from a hook, so one render hands them over in English.
+type Words = ReturnType<typeof usePickWords>;
+function Probe({ take }: { take: (words: Words) => void }) {
+ take(usePickWords());
+ return null;
+}
+let words!: Words;
+renderToStaticMarkup(<WithIntl><Probe take={(w) => (words = w)} /></WithIntl>);
+const { foldersGoNote, phoneGoNote, pickLabel } = words;
const folder = { name: "Shoot day" };
const item = { name: "clip.mp4" };
describe("what a confirm calls a pick", () => {
test("one folder by name, with what it holds in the grid's own word", () => {
- expect(pickLabel([folder], [], ["project", "projects"], 3)).toBe(
+ expect(pickLabel([folder], [], "project", 3)).toBe(
"“Shoot day” and its 3 projects",
);
- expect(pickLabel([folder], [], ["file", "files"], 1)).toBe("“Shoot day” and its 1 file");
- expect(pickLabel([folder], [], ["item", "items"], 0)).toBe("“Shoot day”");
+ expect(pickLabel([folder], [], "file", 1)).toBe("“Shoot day” and its 1 file");
+ expect(pickLabel([folder], [], "item", 0)).toBe("“Shoot day”");
});
test("one item by name", () => {
- expect(pickLabel([], [item], ["file", "files"], 0)).toBe("“clip.mp4”");
+ expect(pickLabel([], [item], "file", 0)).toBe("“clip.mp4”");
});
test("counts otherwise, the held count in the same word", () => {
- expect(pickLabel([folder, folder], [item, item, item], ["project", "projects"], 19)).toBe(
+ expect(pickLabel([folder, folder], [item, item, item], "project", 19)).toBe(
"2 folders (19 projects) and 3 projects",
);
- expect(pickLabel([folder], [item], ["item", "items"], 0)).toBe("1 folder and 1 item");
+ expect(pickLabel([folder], [item], "item", 0)).toBe("1 folder and 1 item");
});
});
diff --git a/site/src/cut/components/selectionMenu.tsx b/site/src/cut/components/selectionMenu.tsx
index 72713c78..999da790 100644
--- a/site/src/cut/components/selectionMenu.tsx
+++ b/site/src/cut/components/selectionMenu.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState, type ReactNode } from "react";
+import { useTranslations } from "next-intl";
import {
AlertDialog,
AlertDialogAction,
@@ -97,47 +98,76 @@ export function SelectionMenu({
);
}
-/** What a confirm calls a pick: the one thing by name, with what a folder
- * holds counted beside it; or the counts — "2 folders (19 projects) and 3
- * projects". `noun` is the grid's word for an item, singular and plural, the
- * word for what the folders hold too; `held` is how many of those the
- * folders hold between them, however deep. */
-export function pickLabel(
- folders: readonly { name: string }[],
- items: readonly { name: string }[],
- noun: [string, string],
- held: number,
-): string {
- const count = (n: number, [one, many]: [string, string]) => `${n} ${n === 1 ? one : many}`;
- const inside = held > 0 ? ` (${count(held, noun)})` : "";
- if (folders.length === 1 && items.length === 0)
- return `“${folders[0].name}”${held > 0 ? ` and its ${count(held, noun)}` : ""}`;
- if (folders.length === 0 && items.length === 1) return `“${items[0].name}”`;
- const parts: string[] = [];
- if (folders.length) parts.push(count(folders.length, ["folder", "folders"]) + inside);
- if (items.length) parts.push(count(items.length, noun));
- return parts.join(" and ");
-}
+/** The grid's word for what it holds: the noun a confirm counts items in. */
+export type PickNoun = "project" | "file" | "item" | "clip" | "note";
-/** The sentence a confirm opens with while the pick holds folders with
- * something in them: a folder goes with everything inside it. Empty when the
- * folders hold nothing, or there are none. */
-export function foldersGoNote(folders: number, held: number): string {
- if (folders === 0 || held === 0) return "";
- return folders === 1
- ? "Everything inside the folder goes with it. "
- : "Everything inside the folders goes with them. ";
-}
+/**
+ * The words a delete confirm is built from, in the page's language.
+ *
+ * `pickLabel` calls a pick the one thing by name, with what a folder holds
+ * counted beside it; or the counts — "2 folders (19 projects) and 3
+ * projects". `noun` is the grid's word for an item, the word for what the
+ * folders hold too; `held` is how many of those the folders hold between
+ * them, however deep.
+ *
+ * `foldersGoNote` is the sentence a confirm opens with while the pick holds
+ * folders with something in them: a folder goes with everything inside it.
+ * Empty when the folders hold nothing, or there are none.
+ *
+ * `phoneGoNote` is the sentence a Library confirm adds while what goes
+ * includes items synced from the phone: those leave the phone too. `synced`
+ * counts them among the `total` items going. Empty without one.
+ *
+ * Each sentence ends in a space, so the next one follows straight on.
+ */
+export function usePickWords() {
+ const t = useTranslations("home.pick");
+
+ const pickLabel = (
+ folders: readonly { name: string }[],
+ items: readonly { name: string }[],
+ noun: PickNoun,
+ held: number,
+ ): string => {
+ if (folders.length === 1 && items.length === 0) {
+ const name = folders[0].name;
+ return held > 0 ? t("namedHolding", { name, held: t(noun, { count: held }) }) : t("named", { name });
+ }
+ if (folders.length === 0 && items.length === 1) {
+ return t("named", { name: items[0].name });
+ }
+
+ // Counts: the folders with what they hold, then the items beside them.
+ const folderPart = folders.length
+ ? held > 0
+ ? t("foldersHolding", { folders: t("folder", { count: folders.length }), held: t(noun, { count: held }) })
+ : t("folder", { count: folders.length })
+ : "";
+ const itemPart = items.length ? t(noun, { count: items.length }) : "";
+ if (folderPart && itemPart) {
+ return t("both", { folders: folderPart, items: itemPart });
+ }
+ return folderPart || itemPart;
+ };
+
+ const foldersGoNote = (folders: number, held: number): string => {
+ if (folders === 0 || held === 0) {
+ return "";
+ }
+ return `${t("foldersGo", { count: folders })} `;
+ };
+
+ const phoneGoNote = (synced: number, total: number): string => {
+ if (synced === 0) {
+ return "";
+ }
+ if (total === 1) {
+ return `${t("phoneOnly")} `;
+ }
+ return `${t("phoneSome", { count: synced })} `;
+ };
-/** The sentence a Library confirm adds while what goes includes items synced
- * from the phone: those leave the phone too. `synced` counts them among the
- * `total` items going. Empty without one. */
-export function phoneGoNote(synced: number, total: number): string {
- if (synced === 0) return "";
- if (total === 1) return "It was synced from your phone and is removed there too. ";
- return synced === 1
- ? "One of them was synced from your phone and is removed there too. "
- : `${synced} of them were synced from your phone and are removed there too. `;
+ return { pickLabel, foldersGoNote, phoneGoNote };
}
/** The confirm before a pick is deleted. The grid words it: what goes, what
@@ -146,7 +176,7 @@ export function DeleteConfirm({
open,
title,
description,
- action = "Delete",
+ action,
busy = false,
onClose,
onConfirm,
@@ -159,6 +189,7 @@ export function DeleteConfirm({
onClose: () => void;
onConfirm: () => void;
}) {
+ const t = useTranslations("home.pick");
return (
<AlertDialog open={open} onOpenChange={(o) => !o && onClose()}>
<AlertDialogContent>
@@ -167,7 +198,7 @@ export function DeleteConfirm({
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>
+ <AlertDialogCancel disabled={busy}>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction
disabled={busy}
className="bg-destructive/10 text-destructive hover:bg-destructive/20"
@@ -176,7 +207,7 @@ export function DeleteConfirm({
onConfirm();
}}
>
- {action}
+ {action ?? t("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/site/src/cut/components/sentRefs.test.tsx b/site/src/cut/components/sentRefs.test.tsx
index 03d8959e..e894ad50 100644
--- a/site/src/cut/components/sentRefs.test.tsx
+++ b/site/src/cut/components/sentRefs.test.tsx
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import type { AssetRef } from "@/cut/lib/assetRef";
+import { WithIntl } from "@/i18n/testing";
import { refHasCard, UnmentionedRefPills } from "./AssetRefs";
const note: AssetRef = { scope: "note", id: "n1", name: "Shot list", kind: "text", url: "data:text/plain," };
@@ -14,14 +15,14 @@ describe("sent refs", () => {
});
test("an unmentioned note reads as its pill", () => {
- const html = renderToStaticMarkup(<UnmentionedRefPills text="tighten this" refs={[note, video]} />);
+ const html = renderToStaticMarkup(<WithIntl><UnmentionedRefPills text="tighten this" refs={[note, video]} /></WithIntl>);
expect(html).toContain("Shot list");
expect(html).toContain("target=\"_blank\"");
expect(html).not.toContain("beach");
});
test("a note named in the text draws no second pill", () => {
- const html = renderToStaticMarkup(<UnmentionedRefPills text={`use @"Shot list"`} refs={[note]} />);
+ const html = renderToStaticMarkup(<WithIntl><UnmentionedRefPills text={`use @"Shot list"`} refs={[note]} /></WithIntl>);
expect(html).toBe("");
});
});
diff --git a/site/src/cut/components/share/BottomSheet.tsx b/site/src/cut/components/share/BottomSheet.tsx
index 058eaaa8..fb725771 100644
--- a/site/src/cut/components/share/BottomSheet.tsx
+++ b/site/src/cut/components/share/BottomSheet.tsx
@@ -2,6 +2,7 @@
import { useEffect } from "react";
import { X } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
/**
@@ -26,6 +27,7 @@ export function BottomSheet({
onClose: () => void;
children: React.ReactNode;
}) {
+ const t = useTranslations("editor.bottomSheet");
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
@@ -41,7 +43,7 @@ export function BottomSheet({
<div className="fixed inset-0 z-50 flex flex-col justify-end">
<button
type="button"
- aria-label="Close"
+ aria-label={t("close")}
className="absolute inset-0 bg-black/50"
onClick={onClose}
/>
@@ -58,7 +60,7 @@ export function BottomSheet({
</div>
<div className="flex items-center justify-between px-4 pb-2">
<h2 className="text-sm font-medium">{title}</h2>
- <Button variant="ghost" size="icon-sm" aria-label="Close" onClick={onClose}>
+ <Button variant="ghost" size="icon-sm" aria-label={t("close")} onClick={onClose}>
<X />
</Button>
</div>
diff --git a/site/src/cut/components/share/MobileShare.tsx b/site/src/cut/components/share/MobileShare.tsx
index 630b7de5..982e6877 100644
--- a/site/src/cut/components/share/MobileShare.tsx
+++ b/site/src/cut/components/share/MobileShare.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Clapperboard, FileText, Images, Loader2, MessageSquare, Captions } from "lucide-react";
+import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import type { ProjectDoc, ShareFeatures, StoredAsset } from "@/cut/lib/types";
import { BottomSheet } from "./BottomSheet";
@@ -53,6 +54,7 @@ export function MobileShare(props: MobileShareProps) {
}
function MobileShareContent({ token, projectId, name, features }: MobileShareProps) {
+ const t = useTranslations("editor.mobileShare");
const api = useCallback(
(path: string) => `/api/cut-shared/${encodeURIComponent(token)}${path}`,
[token]
@@ -152,14 +154,14 @@ function MobileShareContent({ token, projectId, name, features }: MobileSharePro
const sheets = useMemo(() => {
const out: { id: SheetId; label: string; icon: React.ReactNode }[] = [];
- if (features.details) out.push({ id: "details", label: "Details", icon: <FileText /> });
- if (features.subtitles) out.push({ id: "subtitles", label: "Transcript", icon: <Captions /> });
+ if (features.details) out.push({ id: "details", label: t("details"), icon: <FileText /> });
+ if (features.subtitles) out.push({ id: "subtitles", label: t("transcript"), icon: <Captions /> });
if (features.media || features.genai) {
- out.push({ id: "media", label: "Media", icon: <Images /> });
+ out.push({ id: "media", label: t("media"), icon: <Images /> });
}
- if (features.chat) out.push({ id: "chat", label: "Chat", icon: <MessageSquare /> });
+ if (features.chat) out.push({ id: "chat", label: t("chat"), icon: <MessageSquare /> });
return out;
- }, [features]);
+ }, [features, t]);
return (
<div className="flex h-[100dvh] flex-col bg-background">
@@ -198,14 +200,14 @@ function MobileShareContent({ token, projectId, name, features }: MobileSharePro
) : (
<div className="flex flex-col items-center gap-3 px-8 text-center">
{stream.state === "failed" ? (
- <p className="text-sm text-white/70">This project can&apos;t be played right now.</p>
+ <p className="text-sm text-white/70">{t("cantPlay")}</p>
) : (
<>
<Loader2 className="size-5 animate-spin text-white/70" />
<p className="text-sm text-white/70">
{stream.state === "preparing"
- ? "Getting this project ready to play…"
- : "Loading…"}
+ ? t("preparing")
+ : t("loading")}
</p>
</>
)}
@@ -248,36 +250,37 @@ function Empty({ children }: { children: React.ReactNode }) {
}
function DetailsSheet({ doc }: { doc: ProjectDoc | null }) {
- if (!doc) return <Empty>Loading…</Empty>;
+ const t = useTranslations("editor.mobileShare");
+ if (!doc) return <Empty>{t("loading")}</Empty>;
const notes = doc.notes;
const publish = doc.publish;
const links = notes?.links?.filter(Boolean) ?? [];
if (!notes?.text && !notes?.publishedAt && links.length === 0 && !publish?.caption) {
- return <Empty>No details shared.</Empty>;
+ return <Empty>{t("noDetails")}</Empty>;
}
return (
<div className="flex flex-col gap-4 pb-2 text-sm">
{publish?.caption && (
<section className="flex flex-col gap-1">
- <h3 className="text-xs font-medium text-muted-foreground">Caption</h3>
+ <h3 className="text-xs font-medium text-muted-foreground">{t("caption")}</h3>
<p className="whitespace-pre-wrap">{publish.caption}</p>
</section>
)}
{notes?.publishedAt && (
<section className="flex flex-col gap-1">
- <h3 className="text-xs font-medium text-muted-foreground">Published</h3>
+ <h3 className="text-xs font-medium text-muted-foreground">{t("published")}</h3>
<p>{notes.publishedAt}</p>
</section>
)}
{notes?.text && (
<section className="flex flex-col gap-1">
- <h3 className="text-xs font-medium text-muted-foreground">Notes</h3>
+ <h3 className="text-xs font-medium text-muted-foreground">{t("notes")}</h3>
<p className="whitespace-pre-wrap">{notes.text}</p>
</section>
)}
{links.length > 0 && (
<section className="flex flex-col gap-1">
- <h3 className="text-xs font-medium text-muted-foreground">Links</h3>
+ <h3 className="text-xs font-medium text-muted-foreground">{t("links")}</h3>
{links.map((l) => (
<a
key={l}
@@ -303,9 +306,10 @@ function stamp(seconds: number): string {
}
function SubtitlesSheet({ doc }: { doc: ProjectDoc | null }) {
- if (!doc) return <Empty>Loading…</Empty>;
+ const t = useTranslations("editor.mobileShare");
+ if (!doc) return <Empty>{t("loading")}</Empty>;
const cues = doc.subtitles?.cues ?? [];
- if (cues.length === 0) return <Empty>No transcript shared.</Empty>;
+ if (cues.length === 0) return <Empty>{t("noTranscript")}</Empty>;
return (
<ul className="flex flex-col gap-2 pb-2 text-sm">
{cues.map((cue, i) => (
@@ -329,6 +333,7 @@ function MediaSheet({
projectId: string;
doc: ProjectDoc | null;
}) {
+ const t = useTranslations("editor.mobileShare");
const [urls, setUrls] = useState<Record<string, string>>({});
// Only assets a clip does not already use: the cut itself is the video above,
// so this lists what the share adds to it.
@@ -362,8 +367,8 @@ function MediaSheet({
};
}, [api, projectId, assets]);
- if (!doc) return <Empty>Loading…</Empty>;
- if (assets.length === 0) return <Empty>No media shared.</Empty>;
+ if (!doc) return <Empty>{t("loading")}</Empty>;
+ if (assets.length === 0) return <Empty>{t("noMedia")}</Empty>;
return (
<div className="grid grid-cols-3 gap-2 pb-2">
{assets.map((a) => (
@@ -419,27 +424,28 @@ function messageText(m: NonNullable<SharedThread["messages"]>[number]): string {
}
function ChatSheet({ api, projectId }: { api: (path: string) => string; projectId: string }) {
+ const t = useTranslations("editor.mobileShare");
const [threads, setThreads] = useState<SharedThread[] | null>(null);
useEffect(() => {
let alive = true;
void fetch(api(`/projects/${projectId}/chats`))
.then((r) => (r.ok ? (r.json() as Promise<SharedThread[]>) : []))
- .then((t) => alive && setThreads(Array.isArray(t) ? t : []))
+ .then((list) => alive && setThreads(Array.isArray(list) ? list : []))
.catch(() => alive && setThreads([]));
return () => {
alive = false;
};
}, [api, projectId]);
- if (threads === null) return <Empty>Loading…</Empty>;
+ if (threads === null) return <Empty>{t("loading")}</Empty>;
// Emptiness is decided on what will actually render, not on the message
// count: a thread of nothing but tool calls has messages and no readable
// text, and counting those would open a blank sheet instead of saying so.
const shown = threads
- .flatMap((t) => t.messages ?? [])
+ .flatMap((thread) => thread.messages ?? [])
.map((m) => ({ role: m.role, text: messageText(m) }))
.filter((m) => m.text.length > 0);
- if (shown.length === 0) return <Empty>No chat shared.</Empty>;
+ if (shown.length === 0) return <Empty>{t("noChat")}</Empty>;
return (
<ul className="flex flex-col gap-3 pb-2 text-sm">
{shown.map((m, i) => (
diff --git a/site/src/cut/engine/serve.ts b/site/src/cut/engine/serve.ts
index dae717a7..b7c9cdfd 100644
--- a/site/src/cut/engine/serve.ts
+++ b/site/src/cut/engine/serve.ts
@@ -4,7 +4,7 @@ import { flattenCutUsers, migrateCutDataDir } from "../server/migrateDataDir";
import { sweepPhoneInbox } from "../server/phoneLink";
import { reconcileProjectDirs } from "../server/projects";
import { ensureToolPath, resolveOnPath } from "../server/tool-path";
-import { errorMessage } from "../server/util";
+import { errorReply } from "../server/util";
import { enginePort } from "./config";
// Throws (and exits with a clear message) on a bad DONKEY_CUT_PORT rather than
@@ -85,7 +85,7 @@ async function start() {
status: response.status, statusText: response.statusText, headers: merged,
});
} catch (error) {
- return Response.json({ error: errorMessage(error, String(error)) }, { status: 500, headers });
+ return Response.json(errorReply(error, String(error)), { status: 500, headers });
}
},
});
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index d57531dc..674790ba 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -567,7 +567,7 @@ function describeState(
name: a.name,
type: a.type,
fileName: a.fileName,
- ...(a.sizeBytes !== undefined ? { sizeBytes: a.sizeBytes, fileSize: formatBytes(a.sizeBytes) } : {}),
+ ...(a.sizeBytes !== undefined ? { sizeBytes: a.sizeBytes, fileSize: formatBytes(a.sizeBytes, "en") } : {}),
...(a.width !== undefined ? { width: a.width } : {}),
...(a.height !== undefined ? { height: a.height } : {}),
duration: roundT(a.duration),
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 8ed0f379..562198ba 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -130,7 +130,9 @@ import {
type FlashRhythm,
type TextWeight,
} from "@donkeycut/effects-kit";
-import type { AiPanelToolName } from "@/cut/components/AiPanel.tools";
+import { INTERFACE_LANGUAGE_LIST, languageName, type AiPanelToolName } from "@/cut/components/AiPanel.tools";
+import { isLocale } from "@/i18n/locales";
+import { changeInterfaceLanguage } from "./interfaceLanguage";
import { beatSwitches, clipBeatTimes, switchProblem, tidySwitches, timedFontCycle, validBeatStep } from "./fontCycleTiming";
import { LOOP_SPEED_MAX, LOOP_SPEED_MIN, type OverlayAnimationToolName } from "@/cut/components/AnimationTiles.tools";
import type { AudioToolName } from "@/cut/components/AudioPanel.tools";
@@ -300,7 +302,8 @@ import { composeMusicPrompt } from "./composeGen";
import { stockAssetInDoc } from "./genvideo/docWriter";
import { resolveVoiceAsk, synthesizeSpeech, SPEECH_VOICES } from "./tts";
import { hostedFetch, hostedPost } from "./hosted";
-import { readHostedError } from "./hostedError";
+import { readHostedFailure } from "./hostedError";
+import { UserError } from "./userError";
import { creditPriceQuote, type CreditPriceSheet } from "@/lib/credits/price-sheet";
import { creditsFromDollars } from "@/lib/credits/format-credits";
import { BLOCK_MAX_SECONDS, BLOCK_MIN_SECONDS, BLOCKOUT_MAX, blockAsset } from "./blockSource";
@@ -1636,7 +1639,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const sizeBytes = asset.sizeBytes ?? await readMediaFileSize(asset.url);
return {
id: asset.id, name: asset.name, fileName: asset.fileName, kind: asset.type,
- sizeBytes, fileSize: formatBytes(sizeBytes), duration: roundT(asset.duration), width: asset.width, height: asset.height,
+ sizeBytes, fileSize: formatBytes(sizeBytes, "en"), duration: roundT(asset.duration), width: asset.width, height: asset.height,
};
},
@@ -4726,6 +4729,20 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
return { queued: true, note: "It runs as its own turn after this one finishes." };
},
+ set_interface_language: async (_s, input) => {
+ const locale = input.locale;
+ if (!isLocale(locale)) {
+ throw new ToolError(`Unknown interface language ${String(locale)} — pick from ${INTERFACE_LANGUAGE_LIST}.`);
+ }
+ const language = languageName(locale);
+ const where = await changeInterfaceLanguage(locale).catch((err: unknown) => {
+ throw new ToolError(err instanceof Error ? err.message : String(err), { cause: err });
+ });
+ return where === "page"
+ ? { locale, language, saved: "account", note: `The editor reloads in ${language} as this reply finishes, and the account keeps it.` }
+ : { locale, language, saved: "account", note: `No editor page is open in this session, so the account's language is saved; Donkey Cut opens in ${language} the next time it loads.` };
+ },
+
wait_for_renders: async (s) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
@@ -5964,7 +5981,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
]);
for (const res of [prices, balance]) {
if (!res.ok) {
- throw new ToolError(await readHostedError(res, "Sign in to Donkey to see credit prices.", "Could not read credit prices."));
+ throw new ToolError((await readHostedFailure(res, new UserError("sign_in_to_see_prices", "Sign in to Donkey to see credit prices."), new UserError("credit_prices_read_failed", "Could not read credit prices."))).message);
}
}
const sheet = (await prices.json()) as CreditPriceSheet;
diff --git a/site/src/cut/lib/audioGen.ts b/site/src/cut/lib/audioGen.ts
index 85266210..7ff85793 100644
--- a/site/src/cut/lib/audioGen.ts
+++ b/site/src/cut/lib/audioGen.ts
@@ -1,11 +1,11 @@
"use client";
import { bytesFromBase64 } from "./bytes";
-import { readHostedError } from "./hostedError";
+import { readHostedFailure } from "./hostedError";
import { hostedPost } from "./hosted";
import { importFileToProject } from "./media";
-import { NoCreditsError } from "./tts";
import { mediaSlug, type MediaAsset } from "./types";
+import { UserError } from "./userError";
import type { MusicLength } from "@/lib/credits/price-sheet";
// Client side of AI music generation: Gemini/Lyria on Donkey's hosted inference
@@ -24,8 +24,8 @@ export const MUSIC_VARIANTS: { id: MusicVariant; label: string; hint: string }[]
{ id: "song", label: "Full track", hint: "~2 min" },
];
-const readError = (res: Response, fallback: string) =>
- readHostedError(res, "Sign in to Donkey to generate music.", fallback);
+const readFailure = (res: Response, fallback: UserError) =>
+ readHostedFailure(res, new UserError("sign_in_to_generate_music", "Sign in to Donkey to generate music."), fallback);
/** Display name for the track: the prompt, tidied and capped. */
function musicName(prompt: string) {
@@ -54,8 +54,7 @@ export async function synthesizeMusic(
...(opts?.variant === "song" ? { parameters: { variant: "song" } } : {}),
});
if (!res.ok) {
- const message = await readError(res, "Music generation failed.");
- throw res.status === 402 ? new NoCreditsError(message) : new Error(message);
+ throw await readFailure(res, new UserError("music_generation_failed", "Music generation failed."));
}
const gen = (await res.json()) as {
outputs?: { dataBase64?: string; url?: string; contentType?: string; filename?: string }[];
@@ -73,16 +72,20 @@ export async function synthesizeMusic(
});
} else if (out?.url) {
const dl = await fetch(out.url);
- if (!dl.ok) throw new Error("Could not download the generated music.");
+ if (!dl.ok) {
+ throw new UserError("music_download_failed", "Could not download the generated music.");
+ }
file = new File([await dl.arrayBuffer()], fileName, {
type: out.contentType ?? "audio/mpeg",
});
} else {
- throw new Error("The provider returned no music.");
+ throw new UserError("music_output_missing", "The provider returned no music.");
}
const asset = await importFileToProject(projectId, file);
- if (!asset) throw new Error("Could not save the generated music into the project.");
+ if (!asset) {
+ throw new UserError("music_save_failed", "Could not save the generated music into the project.");
+ }
asset.name = label;
// Generated (not a user import): stays out of the Media panel and lists in the
// Audio tab's Music generator. A chat-made track is re-tagged to its thread by
diff --git a/site/src/cut/lib/backend/browser/exportJobs.ts b/site/src/cut/lib/backend/browser/exportJobs.ts
index f68664ef..c0bb4281 100644
--- a/site/src/cut/lib/backend/browser/exportJobs.ts
+++ b/site/src/cut/lib/backend/browser/exportJobs.ts
@@ -4,6 +4,8 @@
// files stay listed on the project's exports shelf. Shapes match the engine's
// job feed so the dock renders every residency the same way.
+import type { UserErrorParams } from "../../userError";
+
export interface BrowserExportJob {
id: string;
projectId: string;
@@ -12,6 +14,8 @@ export interface BrowserExportJob {
progress: number;
outName?: string;
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
startedAt?: number;
createdAt?: number;
}
diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.ts
index a17f81fd..b3abc2cb 100644
--- a/site/src/cut/lib/backend/browser/library.ts
+++ b/site/src/cut/lib/backend/browser/library.ts
@@ -24,6 +24,7 @@ import type {
import * as store from "./opfs";
import { registerBlobFile, registeredUrl, revokeRegistered } from "./registry";
import { caught, err, json, serveFile } from "./respond";
+import { UserError } from "../../userError";
const INDEX_FILE = "library.json";
@@ -106,7 +107,7 @@ async function readIndex(): Promise<LibraryIndex> {
async function mutateIndex<T>(fn: (idx: LibraryIndex) => T): Promise<T> {
return store.withStoreLock("library", async () => {
const dir = await store.libraryDir(true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw new UserError("browser_storage_unavailable", "Browser storage is unavailable.");
const idx = await readIndex();
const result = fn(idx);
await store.writeFileAt(dir, INDEX_FILE, JSON.stringify(idx));
@@ -171,7 +172,7 @@ async function addAsset(
posterFile?: string,
): Promise<StoredAsset> {
const type = meta?.type ?? libraryTypeOf(fileName);
- if (!type) throw new Error("Unsupported file type.");
+ if (!type) throw new UserError("file_type_unsupported", "Unsupported file type.");
const asset: StoredAsset = {
id: crypto.randomUUID().slice(0, 8),
fileName,
@@ -212,7 +213,7 @@ async function upload(req: Request): Promise<Response> {
const meta = parseField<UploadMeta>(form.get("meta"));
const source = parseField<LibrarySource>(form.get("source"));
if (!(meta?.type ?? libraryTypeOf(file.name)))
- return err("Unsupported file type.", 400);
+ return err(new UserError("file_type_unsupported", "Unsupported file type."), 400);
const fileName = await store.saveLibraryMedia(file, file.name);
await register(fileName, file);
// An import carries the source's cover alongside the media; it is stored
@@ -229,7 +230,7 @@ async function upload(req: Request): Promise<Response> {
}
return json(await addAsset(fileName, name, meta, source, posterFile));
} catch (e) {
- return caught(e, "Upload failed.");
+ return caught(e, new UserError("upload_failed", "Upload failed."));
}
}
@@ -238,7 +239,7 @@ async function serveMedia(
download: boolean,
): Promise<Response> {
const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
- if (!file) return err("Media file not found.", 404);
+ if (!file) return err(new UserError("media_file_not_found", "Media file not found."), 404);
await register(fileName, file);
return serveFile(file, fileName, download);
}
@@ -281,13 +282,13 @@ async function dropFiles(files: string[]): Promise<void> {
async function removeAsset(id: string): Promise<Response> {
try {
const files = await mutateIndex((idx) => {
- if (!idx.assets.some((a) => a.id === id)) throw new Error("Library asset not found.");
+ if (!idx.assets.some((a) => a.id === id)) throw new UserError("library_asset_not_found", "Library asset not found.");
return takeAssets(idx, new Set([id]));
});
await dropFiles(files);
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete.");
+ return caught(e, new UserError("library_delete_failed", "Could not delete."));
}
}
@@ -304,15 +305,15 @@ async function makeProxy(req: Request, id: string): Promise<Response> {
const { compatCoverIn, compatCovers, compatProxyNameFor } = await import("../../proxyNames");
const compat = compatCoverIn(asked);
const asset = (await readIndex()).assets.find((a) => a.id === id);
- if (!asset) return err("Library asset not found.", 404);
- if (asset.type !== "video") return err("Only a video takes a playable copy.", 400);
+ if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
+ if (asset.type !== "video") return err(new UserError("playable_copy_video_only", "Only a video takes a playable copy."), 400);
const dir = await store.libraryMediaDir(true);
- if (!dir) return err("Browser storage is unavailable.", 500);
+ if (!dir) return err(new UserError("browser_storage_unavailable", "Browser storage is unavailable."), 500);
const held = asset.proxyFile;
const answers = !!held && (!compat || compatCovers(held, compat));
if (held && answers && (await store.readFileAt(dir, held))) return json(asset);
const master = await store.readFileAt(dir, asset.fileName);
- if (!master) return err("Media file not found.", 404);
+ if (!master) return err(new UserError("media_file_not_found", "Media file not found."), 404);
// Loaded on the ask: the encoder pulls in the decoders and the muxer.
const { encodeProxyInPage, proxyNameFor, proxyOnTheMac } = await import("../../proxyEncode");
@@ -331,7 +332,7 @@ async function makeProxy(req: Request, id: string): Promise<Response> {
}
if (!fileName) {
const blob = await proxyOnTheMac(async () => master, asset.fileName, maxHeight!, crf!);
- if (!blob) return err("This browser can't make a playable copy of this video. Open the Donkey app to make one.", 422);
+ if (!blob) return err(new UserError("playable_copy_needs_app", "This browser can't make a playable copy of this video. Open the Donkey app to make one."), 422);
fileName = await store.saveLibraryMedia(blob, proxyNameFor(asset.fileName));
}
const landed = fileName;
@@ -339,7 +340,7 @@ async function makeProxy(req: Request, id: string): Promise<Response> {
// The asset may have been deleted while the copy was built.
const updated = await mutateIndex((idx) => {
const live = idx.assets.find((a) => a.id === id);
- if (!live) throw new Error("Library asset not found.");
+ if (!live) throw new UserError("library_asset_not_found", "Library asset not found.");
live.proxyFile = landed;
return live;
});
@@ -352,7 +353,7 @@ async function makeProxy(req: Request, id: string): Promise<Response> {
throw e;
}
} catch (e) {
- return caught(e, "Could not make the playable copy.");
+ return caught(e, new UserError("playable_copy_make_failed", "Could not make the playable copy."));
}
}
@@ -366,15 +367,15 @@ async function move(req: Request): Promise<Response> {
const item =
idx.assets.find((a) => a.id === id) ??
idx.templates.find((t) => t.id === id);
- if (!item) throw new Error("Library item not found.");
+ if (!item) throw new UserError("library_item_not_found", "Library item not found.");
if (folderId && !idx.folders.some((f) => f.id === folderId)) {
- throw new Error("Folder not found.");
+ throw new UserError("folder_not_found", "Folder not found.");
}
item.folderId = folderId ?? null;
});
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not move item.");
+ return caught(e, new UserError("library_item_move_failed", "Could not move item."));
}
}
@@ -385,7 +386,7 @@ async function createFolder(req: Request): Promise<Response> {
parentId?: string | null;
};
const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
+ if (!trimmed) return err(new UserError("folder_name_required", "Folder name required."), 500);
const id = crypto.randomUUID().slice(0, 8);
return json(
await mutateIndex((idx) => {
@@ -400,7 +401,7 @@ async function createFolder(req: Request): Promise<Response> {
}),
);
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
}
@@ -413,11 +414,11 @@ async function updateFolder(req: Request, id: string): Promise<Response> {
parentId?: string | null;
};
const trimmed = name?.trim();
- if (name !== undefined && !trimmed) return err("Folder name required.", 500);
+ if (name !== undefined && !trimmed) return err(new UserError("folder_name_required", "Folder name required."), 500);
return json(
await mutateIndex((idx) => {
const folder = idx.folders.find((f) => f.id === id);
- if (!folder) throw new Error("Folder not found.");
+ if (!folder) throw new UserError("folder_not_found", "Folder not found.");
if (trimmed) folder.name = trimmed.slice(0, 80);
if (parentId !== undefined) {
folder.parentId = resolveParent(idx.folders, id, parentId);
@@ -426,7 +427,7 @@ async function updateFolder(req: Request, id: string): Promise<Response> {
}),
);
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
}
@@ -446,7 +447,7 @@ async function deleteFolder(id: string): Promise<Response> {
await dropFiles(files);
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
}
@@ -456,7 +457,7 @@ async function copyIntoProject(
fileName: string,
): Promise<string> {
const file = await store.readFileAt(await store.libraryMediaDir(), fileName);
- if (!file) throw new Error("Library file not found.");
+ if (!file) throw new UserError("library_file_not_found", "Library file not found.");
const stored = await store.saveMedia(projectId, file, fileName);
registerBlobFile(projectMediaApiPath(projectId, stored), file);
return stored;
@@ -471,7 +472,7 @@ async function copyFromProject(
await store.mediaDir(projectId),
fileName,
);
- if (!file) throw new Error("Media file not found in project.");
+ if (!file) throw new UserError("project_media_not_found", "Media file not found in project.");
const stored = await store.saveLibraryMedia(file, fileName);
await register(stored, file);
return stored;
@@ -484,12 +485,12 @@ async function addToProject(req: Request): Promise<Response> {
projectId: string;
};
const asset = (await readIndex()).assets.find((a) => a.id === assetId);
- if (!asset) return err("Library asset not found.", 404);
+ if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
if (!(await store.readDoc(projectId)))
- return err("Project not found.", 404);
+ return err(new UserError("project_not_found", "Project not found."), 404);
return json({ fileName: await copyIntoProject(projectId, asset.fileName) });
} catch (e) {
- return caught(e, "Could not add from library.");
+ return caught(e, new UserError("library_add_failed", "Could not add from library."));
}
}
@@ -506,7 +507,7 @@ async function saveFromProject(req: Request): Promise<Response> {
name?: string;
};
const doc = await store.readDoc(projectId);
- if (!doc) return err("Project not found.", 404);
+ if (!doc) return err(new UserError("project_not_found", "Project not found."), 404);
const known = doc.assets.find((a) => a.fileName === fileName);
const stored = await copyFromProject(projectId, fileName);
return json(
@@ -518,7 +519,7 @@ async function saveFromProject(req: Request): Promise<Response> {
}),
);
} catch (e) {
- return caught(e, "Could not save to library.");
+ return caught(e, new UserError("library_save_failed", "Could not save to library."));
}
}
@@ -547,8 +548,8 @@ async function saveTemplate(req: Request): Promise<Response> {
projectId: string;
} & TemplateInput;
if (!(await store.readDoc(projectId)))
- return err("Project not found.", 404);
- if (templateEmpty(input)) return err("Nothing to save.", 500);
+ return err(new UserError("project_not_found", "Project not found."), 404);
+ if (templateEmpty(input)) return err(new UserError("template_nothing_to_save", "Nothing to save."), 500);
const media: TemplateMedia[] = [];
for (const m of input.media ?? []) {
media.push({
@@ -574,7 +575,7 @@ async function saveTemplate(req: Request): Promise<Response> {
});
return json(template);
} catch (e) {
- return caught(e, "Could not save the template.");
+ return caught(e, new UserError("template_save_failed", "Could not save the template."));
}
}
@@ -594,7 +595,7 @@ async function importTemplate(req: Request): Promise<Response> {
const media: TemplateMedia[] = [];
for (const [i, m] of (input.media ?? []).entries()) {
const file = files[i];
- if (!file) return err("Template media missing.", 400);
+ if (!file) return err(new UserError("template_media_missing", "Template media missing."), 400);
const fileName = await store.saveLibraryMedia(
file,
m.fileName || file.name,
@@ -621,7 +622,7 @@ async function importTemplate(req: Request): Promise<Response> {
});
return json(template);
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
}
@@ -632,9 +633,9 @@ async function materializeTemplate(
try {
const { projectId } = (await req.json()) as { projectId: string };
if (!(await store.readDoc(projectId)))
- return err("Project not found.", 404);
+ return err(new UserError("project_not_found", "Project not found."), 404);
const template = (await readIndex()).templates.find((t) => t.id === id);
- if (!template) return err("Template not found.", 404);
+ if (!template) return err(new UserError("template_not_found", "Template not found."), 404);
const media: TemplateMedia[] = [];
for (const m of template.media) {
media.push({
@@ -644,7 +645,7 @@ async function materializeTemplate(
}
return json({ template, media });
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
}
@@ -662,7 +663,7 @@ async function addToTemplate(req: Request, id: string): Promise<Response> {
return json(
await mutateIndex((idx) => {
const t = idx.templates.find((x) => x.id === id);
- if (!t) throw new Error("Template not found.");
+ if (!t) throw new UserError("template_not_found", "Template not found.");
const mi = t.media.length;
t.media = [...t.media, { ...media, fileName: stored }];
if (audio)
@@ -681,7 +682,7 @@ async function addToTemplate(req: Request, id: string): Promise<Response> {
throw e;
}
} catch (e) {
- return caught(e, "Could not add to the template.");
+ return caught(e, new UserError("template_append_failed", "Could not add to the template."));
}
}
@@ -692,13 +693,13 @@ async function renameTemplate(req: Request, id: string): Promise<Response> {
return json(
await mutateIndex((idx) => {
const template = idx.templates.find((t) => t.id === id);
- if (!template) throw new Error("Template not found.");
+ if (!template) throw new UserError("template_not_found", "Template not found.");
template.name = next;
return template;
}),
);
} catch (e) {
- return caught(e, "Could not rename the template.");
+ return caught(e, new UserError("template_rename_failed", "Could not rename the template."));
}
}
@@ -709,13 +710,13 @@ async function renameAsset(req: Request, id: string): Promise<Response> {
return json(
await mutateIndex((idx) => {
const asset = idx.assets.find((a) => a.id === id);
- if (!asset) throw new Error("Library asset not found.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
asset.name = next;
return asset;
}),
);
} catch (e) {
- return caught(e, "Could not rename the file.");
+ return caught(e, new UserError("file_rename_failed", "Could not rename the file."));
}
}
@@ -725,7 +726,7 @@ async function deleteTemplate(id: string): Promise<Response> {
await dropFiles(files);
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the template.");
+ return caught(e, new UserError("template_delete_failed", "Could not delete the template."));
}
}
diff --git a/site/src/cut/lib/backend/browser/opfs.ts b/site/src/cut/lib/backend/browser/opfs.ts
index ff1ab461..5041d678 100644
--- a/site/src/cut/lib/backend/browser/opfs.ts
+++ b/site/src/cut/lib/backend/browser/opfs.ts
@@ -22,9 +22,13 @@ import { isDeliveryName } from "../../exportDelivery";
import { timelineEnd } from "../../timelineEnd";
import type { ProjectDoc, ProjectFolder, ProjectSummary } from "../../types";
import { currentEngineUser } from "../../api";
+import { UserError } from "../../userError";
const ROOT_DIR = "cut-store";
+// The failure every write meets when the page cannot reach its own storage.
+const storageUnavailable = () => new UserError("browser_storage_unavailable", "Browser storage is unavailable.");
+
/** Whether this browser can hold a store: OPFS with committed writes. The
* same capability line the in-tab render draws. */
export function supportsBrowserStore(): boolean {
@@ -159,7 +163,7 @@ export async function readIndex(): Promise<StoreIndex> {
export async function updateIndex(mutate: (idx: StoreIndex) => StoreIndex | void): Promise<StoreIndex> {
return withStoreLock("index", async () => {
const dir = await dirAt(userParts(), true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw storageUnavailable();
const idx = await readIndex();
const next = mutate(idx) ?? idx;
await writeFileAt(dir, "index.json", JSON.stringify(next));
@@ -180,12 +184,12 @@ export async function readDoc(id: string): Promise<ProjectDoc | null> {
export async function writeDoc(id: string, doc: ProjectDoc): Promise<string> {
return withStoreLock(`doc:${id}`, async () => {
const dir = await projectDir(id, true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw storageUnavailable();
doc.id = id;
doc.updatedAt = Date.now();
await writeFileAt(dir, "project.json", JSON.stringify(doc));
const file = await readFileAt(dir, "project.json");
- if (!file) throw new Error("Could not read the saved project.");
+ if (!file) throw new UserError("saved_project_unreadable", "Could not read the saved project.");
return String(file.lastModified);
});
}
@@ -273,7 +277,7 @@ export async function freeName(
/** Store media bytes in a project under a deduped name. */
export async function saveMedia(id: string, file: Blob, wantName: string): Promise<string> {
const dir = await mediaDir(id, true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw storageUnavailable();
const name = await freeName(dir, wantName);
await writeFileAt(dir, name, file);
askPersist();
@@ -301,7 +305,7 @@ export const libraryMediaDir = (create = false) => dirAt([...libraryParts(), "me
export async function saveLibraryMedia(file: Blob, wantName: string): Promise<string> {
const dir = await libraryMediaDir(true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw storageUnavailable();
const name = await freeName(dir, wantName);
await writeFileAt(dir, name, file);
askPersist();
@@ -336,7 +340,7 @@ export async function listExports(id: string): Promise<ExportListing[]> {
/** Land a finished render in exports/, deduping like media names do. */
export async function saveExport(id: string, file: File, wantName: string): Promise<string> {
const dir = await exportsDir(id, true);
- if (!dir) throw new Error("Browser storage is unavailable.");
+ if (!dir) throw storageUnavailable();
const dot = wantName.lastIndexOf(".");
const ext = dot > 0 ? wantName.slice(dot) : ".mp4";
const stem = dot > 0 ? wantName.slice(0, dot) : wantName;
diff --git a/site/src/cut/lib/backend/browser/respond.ts b/site/src/cut/lib/backend/browser/respond.ts
index 61b4d1b2..ff8d930a 100644
--- a/site/src/cut/lib/backend/browser/respond.ts
+++ b/site/src/cut/lib/backend/browser/respond.ts
@@ -1,12 +1,13 @@
// The replies the browser backend's handlers build. Shapes match the engine's
// (`server/http/*`), so a call site can't tell which backend answered.
+import { errorBody, type UserError } from "../../userError";
+
export const json = (body: unknown, status = 200) => Response.json(body, { status });
-export const err = (message: string, status: number) => json({ error: message }, status);
+export const err = (failure: string | UserError, status: number) => json(errorBody(failure, ""), status);
-export const caught = (e: unknown, fallback: string) =>
- err(e instanceof Error ? e.message : fallback, 500);
+export const caught = (e: unknown, fallback: string | UserError) => json(errorBody(e, fallback), 500);
/** Serve a store file the way serveFileRange presents it: typed bytes, an
* attachment disposition when the URL asks to download. Blob-backed Responses
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
index e15d0738..7330d735 100644
--- a/site/src/cut/lib/backend/browser/router.ts
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -6,6 +6,7 @@
// Owned here: projects CRUD + folders, media bytes, image import, presign-get
// (answered with blob URLs), exports, the export-jobs feed, and the library
// shelf (./library.ts). Everything else is the driver's cloud proxy.
+import { creatorNames } from "../../defaultNames";
import { resolveParent, settleParents, subtreeOf } from "../../folderTree";
import { sanitizeGuideLines, sanitizeGuides } from "../../guides";
import { OUTPUT_SPACES } from "@donkeycut/effects-kit";
@@ -19,6 +20,13 @@ import { dispatchLibraryRoute } from "./library";
import * as store from "./opfs";
import { registerBlobFile, registeredUrl, revokeRegistered } from "./registry";
import { caught, err, json, serveFile } from "./respond";
+import { UserError } from "../../userError";
+
+// Refusals the page reads, coded so it words them; the engine answers the same.
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
+const FOLDER_NOT_FOUND = new UserError("folder_not_found", "Folder not found.");
+const FOLDER_NAME_REQUIRED = new UserError("folder_name_required", "Folder name required.");
+const EXPORT_NOT_READY = new UserError("export_not_ready", "Export not ready.");
const mediaApiPath = (id: string, fileName: string) =>
`/api/cut/projects/${id}/media/${encodeURIComponent(fileName)}`;
@@ -46,7 +54,8 @@ async function createProject(req: Request): Promise<Response> {
aspect?: string;
};
const id = crypto.randomUUID().slice(0, 10);
- const displayName = (name ?? "Untitled").trim() || "Untitled";
+ // This backend runs in the page, so it names in the page's language.
+ const displayName = name?.trim() || creatorNames().untitled;
const folders = (await store.readIndex()).folders;
const folder = folderId && folders.some((f) => f.id === folderId) ? folderId : null;
const frame = normalizeAspect(aspect);
@@ -68,7 +77,7 @@ async function createProject(req: Request): Promise<Response> {
store.askPersist();
return json(await store.summarize(id, doc));
} catch (e) {
- return caught(e, "Could not create project.");
+ return caught(e, new UserError("project_create_failed", "Could not create project."));
}
}
@@ -78,7 +87,7 @@ async function createProject(req: Request): Promise<Response> {
async function putProject(req: Request, id: string): Promise<Response> {
try {
const existing = await store.readDoc(id);
- if (!existing) return err("Project not found.", 404);
+ if (!existing) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as Partial<ProjectDoc>;
const doc: ProjectDoc = {
...existing,
@@ -120,17 +129,17 @@ async function putProject(req: Request, id: string): Promise<Response> {
const revision = await store.writeDoc(id, doc);
return json({ ok: true, updatedAt: doc.updatedAt, revision });
} catch (e) {
- return caught(e, "Could not save project.");
+ return caught(e, new UserError("project_save_failed", "Could not save project."));
}
}
async function duplicateProject(id: string): Promise<Response> {
try {
const doc = await store.readDoc(id);
- if (!doc) return err("Project not found.", 404);
+ if (!doc) return err(PROJECT_NOT_FOUND, 404);
const newId = crypto.randomUUID().slice(0, 10);
const now = Date.now();
- const copy: ProjectDoc = { ...doc, id: newId, name: `${doc.name} copy`, createdAt: now, updatedAt: now };
+ const copy: ProjectDoc = { ...doc, id: newId, name: creatorNames().copy(doc.name), createdAt: now, updatedAt: now };
await store.writeDoc(newId, copy);
const srcMedia = await store.mediaDir(id);
if (srcMedia) {
@@ -142,7 +151,7 @@ async function duplicateProject(id: string): Promise<Response> {
}
return json(await store.summarize(newId, copy));
} catch (e) {
- return caught(e, "Could not duplicate project.");
+ return caught(e, new UserError("project_duplicate_error", "Could not duplicate project."));
}
}
@@ -150,15 +159,15 @@ async function moveProject(req: Request, id: string): Promise<Response> {
try {
const { folderId } = (await req.json()) as { folderId: string | null };
const doc = await store.readDoc(id);
- if (!doc) return err("Project not found.", 404);
+ if (!doc) return err(PROJECT_NOT_FOUND, 404);
if (folderId && !(await store.readIndex()).folders.some((f) => f.id === folderId)) {
- return err("Folder not found.", 404);
+ return err(FOLDER_NOT_FOUND, 404);
}
doc.folderId = folderId ?? null;
await store.writeDoc(id, doc);
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not move project.");
+ return caught(e, new UserError("project_move_failed", "Could not move project."));
}
}
@@ -166,7 +175,7 @@ async function createFolder(req: Request): Promise<Response> {
try {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
+ if (!trimmed) return err(FOLDER_NAME_REQUIRED, 500);
const id = crypto.randomUUID().slice(0, 8);
let folder: ProjectFolder | null = null;
await store.updateIndex((idx) => {
@@ -180,7 +189,7 @@ async function createFolder(req: Request): Promise<Response> {
});
return json(folder);
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
}
@@ -190,7 +199,7 @@ async function updateFolder(req: Request, fid: string): Promise<Response> {
try {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = name?.trim();
- if (name !== undefined && !trimmed) return err("Folder name required.", 500);
+ if (name !== undefined && !trimmed) return err(FOLDER_NAME_REQUIRED, 500);
let updated: ProjectFolder | null = null;
await store.updateIndex((idx) => ({
...idx,
@@ -206,9 +215,9 @@ async function updateFolder(req: Request, fid: string): Promise<Response> {
: f
),
}));
- return updated ? json(updated) : err("Folder not found.", 500);
+ return updated ? json(updated) : err(FOLDER_NOT_FOUND, 500);
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
}
@@ -231,7 +240,7 @@ async function deleteFolder(fid: string): Promise<Response> {
}));
return json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
}
@@ -243,7 +252,7 @@ async function dropProject(id: string): Promise<void> {
async function uploadMedia(req: Request, id: string): Promise<Response> {
try {
- if (!(await store.readDoc(id))) return err("Project not found.", 404);
+ if (!(await store.readDoc(id))) return err(PROJECT_NOT_FOUND, 404);
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No file in upload.", 400);
@@ -251,13 +260,13 @@ async function uploadMedia(req: Request, id: string): Promise<Response> {
registerBlobFile(mediaApiPath(id, fileName), file);
return json({ fileName });
} catch (e) {
- return caught(e, "Upload failed.");
+ return caught(e, new UserError("upload_failed", "Upload failed."));
}
}
async function importImage(req: Request, id: string): Promise<Response> {
try {
- if (!(await store.readDoc(id))) return err("Project not found.", 404);
+ if (!(await store.readDoc(id))) return err(PROJECT_NOT_FOUND, 404);
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No image in upload.", 400);
@@ -289,7 +298,7 @@ async function importImage(req: Request, id: string): Promise<Response> {
...(origin ? { origin } : {}),
});
} catch (e) {
- return caught(e, "Could not import the image.");
+ return caught(e, new UserError("image_import_failed", "Could not import the image."));
}
}
@@ -333,17 +342,17 @@ async function listProjectExports(id: string): Promise<Response> {
async function exportJobStatus(jobId: string): Promise<Response> {
const job = getBrowserExportJob(jobId);
- if (!job) return err("Unknown export.", 404);
- return json({ status: job.status, progress: job.progress, error: job.error, outName: job.outName });
+ if (!job) return err(new UserError("export_unknown", "Unknown export."), 404);
+ return json({ status: job.status, progress: job.progress, error: job.error, errorCode: job.errorCode, errorParams: job.errorParams, outName: job.outName });
}
async function exportJobFile(jobId: string, download: boolean): Promise<Response> {
const job = getBrowserExportJob(jobId);
if (!job || job.status !== "done" || !job.outName) {
- return err("Export not ready.", 404);
+ return err(EXPORT_NOT_READY, 404);
}
const file = await store.readFileAt(await store.exportsDir(job.projectId), job.outName);
- if (!file) return err("Export not ready.", 404);
+ if (!file) return err(EXPORT_NOT_READY, 404);
return serveFile(file, job.outName, download);
}
@@ -392,7 +401,7 @@ export async function dispatchBrowserRoute(
if (rest.length === 2) {
if (method === "HEAD" || method === "GET") {
const file = await store.docFile(id);
- if (!file) return err("Project not found.", 404);
+ if (!file) return err(PROJECT_NOT_FOUND, 404);
const headers = { "x-cut-doc-version": String(file.lastModified) };
if (method === "HEAD") return new Response(null, { headers });
return new Response(file, { headers: { ...headers, "Content-Type": "application/json" } });
@@ -422,7 +431,7 @@ export async function dispatchBrowserRoute(
const fileName = rest[3];
if (method === "GET") {
const file = await store.readFileAt(dir, fileName);
- if (!file) return err(`${rest[2] === "media" ? "Media file" : "Export"} not found.`, 404);
+ if (!file) return err(rest[2] === "media" ? new UserError("media_file_not_found", "Media file not found.") : new UserError("export_not_found", "Export not found."), 404);
const apiPath =
rest[2] === "media" ? mediaApiPath(id, fileName) : exportApiPath(id, fileName);
if (!registeredUrl(apiPath)) registerBlobFile(apiPath, file);
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.ts
index 29b6f21a..49275259 100644
--- a/site/src/cut/lib/backend/cloud.ts
+++ b/site/src/cut/lib/backend/cloud.ts
@@ -4,6 +4,7 @@
// Media bytes ride presigned R2 URLs minted by those routes, not this
// transport.
import { observeOperationResponse, operationFailure } from "../operationFailure";
+import { UserError } from "../userError";
import { DOC_SEQ_HEADER, DOC_WRITER_HEADER, HTTP_CONFLICT, type CutBackend, type CutRequestInit } from "./types";
const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");
@@ -217,13 +218,16 @@ export async function fetchSignedMediaUrls(
return out;
}
-/** Pure message formatting; the host decides how a quota failure is presented. */
-export function quotaErrorMessage(
- status: number,
- body: { error?: string; bytes?: number; quotaBytes?: number } | null | undefined
-): string | null {
+type QuotaBody = { error?: string; bytes?: number; quotaBytes?: number } | null | undefined;
+
+/** The storage wall a reply is, coded so the page words it; null for any
+ * other reply. The host decides how a quota failure is presented.
+ *
+ * throw quotaError(res.status, body) ?? errorFromBody(body, new UserError("upload_failed", "Upload failed."));
+ */
+export function quotaError(status: number, body: QuotaBody): UserError | null {
const failure = operationFailure(status, body);
- return failure?.code === "storage_quota_exceeded" ? failure.message : null;
+ return failure?.code === "storage_quota_exceeded" ? new UserError(failure.code, failure.message) : null;
}
export const cloudBackend: CutBackend = {
diff --git a/site/src/cut/lib/baseFrame.ts b/site/src/cut/lib/baseFrame.ts
index 8cf21711..0ac4a3f2 100644
--- a/site/src/cut/lib/baseFrame.ts
+++ b/site/src/cut/lib/baseFrame.ts
@@ -27,6 +27,7 @@ import { coveredSrc, frameSink, openMedia, videoTrackOf, type FrameCanvasSink, t
import { sampleClipColorRead, sampleClipFrameData } from "./previewCanvas";
import { colorRead, fileAt, previewFile, type ColorRead } from "./sourceColor";
import { useEditor } from "./store";
+import { UserError } from "./userError";
import type { InputVideoTrack, WrappedCanvas } from "mediabunny";
export { sourceProfileOf } from "./sourceColor";
@@ -154,7 +155,7 @@ export async function baseFrameAt(master: string, time: number, size?: FrameSize
const input = openMedia(url);
try {
const track = await videoTrackOf(input);
- if (!track) throw new Error("This file has no readable video.");
+ if (!track) throw new UserError("media_no_readable_video", "This file has no readable video.");
return await baseFrameSink(track, size, colorReadAt(url)).getCanvas(Math.max(0, time));
} finally {
input.dispose();
@@ -170,7 +171,7 @@ export async function rawFrameAt(master: string, time: number, size: FrameSize):
const input = openMedia(url);
try {
const track = await videoTrackOf(input);
- if (!track) throw new Error("This file has no readable video.");
+ if (!track) throw new UserError("media_no_readable_video", "This file has no readable video.");
const read = colorReadAt(url);
const colorSpace = read.colorSpace;
const frame = await frameSink(track, size, colorSpace ? { colorSpace } : {}).getCanvas(Math.max(0, time));
@@ -205,7 +206,7 @@ export async function* baseFramesAt(master: string, times: number[], size?: Fram
const input = openMedia(url);
try {
const track = await videoTrackOf(input);
- if (!track) throw new Error("This file has no readable video.");
+ if (!track) throw new UserError("media_no_readable_video", "This file has no readable video.");
let next = 0;
try {
for await (const frame of baseFrameSink(track, size, colorReadAt(url)).canvasesAtTimestamps(times)) {
diff --git a/site/src/cut/lib/canvasVideo.ts b/site/src/cut/lib/canvasVideo.ts
index 11d691a8..eeb59534 100644
--- a/site/src/cut/lib/canvasVideo.ts
+++ b/site/src/cut/lib/canvasVideo.ts
@@ -18,6 +18,7 @@ import {
} from "mediabunny";
import { WORKING_VIDEO_CODECS } from "./exportRender";
import { createRasterCanvas, type RasterSurface } from "./raster";
+import { UserError } from "./userError";
export interface CanvasVideoEncoder {
canvas: RasterSurface;
@@ -43,13 +44,13 @@ export async function openCanvasVideo(opts: {
width: opts.width,
height: opts.height,
});
- if (!codec) throw new Error("No video encoder is available.");
+ if (!codec) throw new UserError("video_encoder_unavailable", "No video encoder is available.");
const canvas = createRasterCanvas(opts.width, opts.height);
const ctx = canvas.getContext(
"2d",
opts.readback ? { willReadFrequently: true } : undefined
) as CanvasRenderingContext2D | null;
- if (!ctx) throw new Error("No drawing surface for the encode.");
+ if (!ctx) throw new UserError("encode_surface_unavailable", "No drawing surface for the encode.");
const target = new BufferTarget();
const output = new Output({ format: new Mp4OutputFormat(), target });
const source = new CanvasSource(canvas as HTMLCanvasElement, {
@@ -68,7 +69,7 @@ export async function openCanvasVideo(opts: {
finish: async () => {
await output.finalize();
const buffer = target.buffer;
- if (!buffer) throw new Error("The encode produced nothing.");
+ if (!buffer) throw new UserError("encode_empty", "The encode produced nothing.");
return new Blob([buffer], { type: "video/mp4" });
},
cancel: () => output.cancel().catch(() => {}),
diff --git a/site/src/cut/lib/chatCloud.test.ts b/site/src/cut/lib/chatCloud.test.ts
index b41bbaa3..fcc62b9c 100644
--- a/site/src/cut/lib/chatCloud.test.ts
+++ b/site/src/cut/lib/chatCloud.test.ts
@@ -106,7 +106,7 @@ test("a long thread goes up compacted, and a refused cloud save is told until on
await flushCloudThreadSaves();
expect(bodies[0].length).toBeLessThanOrEqual(CLOUD_THREAD_BUDGET);
expect(JSON.parse(bodies[0]).messages[0].parts).toHaveLength(295);
- expect(threadSaveFailure()).toContain("cloud");
+ expect(threadSaveFailure()?.message).toContain("cloud");
await expect(putCloudThread(cloudBackend, "compact", thread)).rejects.toThrow();
expect(warn.mock.calls.filter((c) => String(c[0]).includes("cloud"))).toHaveLength(1);
status = 200;
diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.ts
index e8d6767c..a429af05 100644
--- a/site/src/cut/lib/chatCloud.ts
+++ b/site/src/cut/lib/chatCloud.ts
@@ -7,6 +7,7 @@ import { cutMode, getBackend, type CutBackend } from "./backend";
import { cloudBackend } from "./backend/cloud";
import { compactThreadForCloud } from "./chatCompact";
import type { SyncPulse } from "./syncCadence";
+import { UserError } from "./userError";
import {
chatThreadDeleted,
cloudThreadSaved,
@@ -42,7 +43,7 @@ export async function fetchCloudThreads(
// Throws on a failed read rather than reading as "no threads": the seed memo
// and a project copy both have to tell an empty history from a lost one.
const res = await backend.fetch(`/api/cut/projects/${projectId}/chats`);
- if (!res.ok) throw new Error("Could not read the project's chats.");
+ if (!res.ok) throw new UserError("chats_read_failed", "Could not read the project's chats.");
const body = (await res.json()) as unknown;
return Array.isArray(body) ? mergeThreads(body.filter(isStoredThread)) : [];
}
@@ -79,9 +80,11 @@ async function sendCloudThread(backend: CutBackend, projectId: string, thread: u
throw err;
}
if (res.status === 410) { deleteStoredThread(projectId, id); return; }
- if (res.status === 409) throw new Error("The conversation changed on the server.");
+ if (res.status === 409) throw new UserError("conversation_changed_remotely", "The conversation changed on the server.");
if (!res.ok) {
- const err = new Error(`Could not save a chat thread (${res.status}).`);
+ const err = new UserError("chat_thread_save_status_failed", `Could not save a chat thread (${res.status}).`, {
+ status: res.status,
+ });
cloudThreadSaveFailed(err);
throw err;
}
@@ -115,7 +118,7 @@ async function syncThreads(state: NonNullable<typeof syncState>): Promise<SyncPu
await loadProjectThreads(projectId);
const path = `/api/cut/projects/${projectId}/chats`;
const response = await backend.fetch(`${path}?revisions=1`);
- if (!response.ok) throw new Error("Could not read the project's chats.");
+ if (!response.ok) throw new UserError("chats_read_failed", "Could not read the project's chats.");
const index = await response.json() as { id: string; revision: string }[];
const remoteIds = new Set(index.map((row) => row.id));
let pulse: SyncPulse = "still";
@@ -123,7 +126,7 @@ async function syncThreads(state: NonNullable<typeof syncState>): Promise<SyncPu
if (versions.get(row.id) === row.revision) continue;
pulse = "moved";
const res = await backend.fetch(`${path}?id=${encodeURIComponent(row.id)}&revision=${encodeURIComponent(row.revision)}`);
- if (!res.ok) throw new Error("Could not read the conversation.");
+ if (!res.ok) throw new UserError("conversation_read_failed", "Could not read the conversation.");
const remote = (await res.json() as unknown[]).filter(isStoredThread);
const local = readProjectThreads(projectId);
const merged = mergeThreads(remote, local);
@@ -150,7 +153,7 @@ async function syncThreads(state: NonNullable<typeof syncState>): Promise<SyncPu
async function saveCloudThread(backend: CutBackend, projectId: string, thread: StoredThread): Promise<void> {
if (!thread.deleted) return putCloudThread(backend, projectId, thread);
const res = await backend.fetch(`/api/cut/projects/${projectId}/chats/${thread.id}`, { method: "DELETE" });
- if (!res.ok) throw new Error("Could not delete the conversation.");
+ if (!res.ok) throw new UserError("conversation_delete_failed", "Could not delete the conversation.");
}
// Saves debounce per thread: while a turn streams, the panel re-saves on every
diff --git a/site/src/cut/lib/chatIntake.ts b/site/src/cut/lib/chatIntake.ts
index 4c5199b9..25c490ea 100644
--- a/site/src/cut/lib/chatIntake.ts
+++ b/site/src/cut/lib/chatIntake.ts
@@ -4,6 +4,7 @@ import type { AssetRef } from "./assetRef";
import { refToInlineImage } from "./refMedia";
import { useEditor } from "./store";
import { formatTime } from "./time";
+import { UserError } from "./userError";
// The chat composer registers itself here so surfaces outside the AI panel —
// the timeline's "Add video frame to chat" — can land a ref among the open
@@ -20,7 +21,7 @@ interface ChatIntake {
* and the grab ends before any capture or flight. */
acceptFrame?: () => boolean;
/** Say why a grab ended with nothing, in the composer's notice tab. */
- notice?: (message: string) => void;
+ notice?: (failure: UserError) => void;
}
let intake: ChatIntake | null = null;
@@ -97,7 +98,7 @@ export async function sendFrameToChat(ref: AssetRef, from: FrameGrabOrigin): Pro
if (!frame) {
// The clip itself is a heavier, different thing than the moment that was
// asked for, so nothing is attached — the grab says why and ends.
- target.notice?.(`Couldn’t read a frame from “${ref.name}”.`);
+ target.notice?.(new UserError("chat_frame_unreadable", `Couldn’t read a frame from “${ref.name}”.`, { name: ref.name }));
return;
}
const frameRef: AssetRef = {
diff --git a/site/src/cut/lib/chatThreads.test.ts b/site/src/cut/lib/chatThreads.test.ts
index 8294abd8..afd53552 100644
--- a/site/src/cut/lib/chatThreads.test.ts
+++ b/site/src/cut/lib/chatThreads.test.ts
@@ -369,7 +369,7 @@ describe("where threads are kept", () => {
await loadProjectThreads("p");
writeProjectThreads("p", [big("mine", 9, 200_000)]);
await flushThreadSaves();
- expect(threadSaveFailure()).toContain("storage is full");
+ expect(threadSaveFailure()?.message).toContain("storage is full");
expect((lists.get("old") as { id: string }[]).map((t) => t.id)).toEqual(["o1", "o2"]);
expect((lists.get("older") as { id: string }[]).map((t) => t.id)).toEqual(["o0"]);
// The open chat is still on screen for the page to show.
@@ -391,7 +391,7 @@ describe("where threads are kept", () => {
await flushThreadSaves();
writeProjectThreads("p", [big("a", 2, 6000)]);
await flushThreadSaves();
- expect(threadSaveFailure()).toContain("couldn't be saved");
+ expect(threadSaveFailure()?.message).toContain("couldn't be saved");
expect(warn.mock.calls).toHaveLength(1);
expect(changes).toBe(1);
// The live copy is still there for the page to show.
diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.ts
index 42c38cc1..ac42f01e 100644
--- a/site/src/cut/lib/chatThreads.ts
+++ b/site/src/cut/lib/chatThreads.ts
@@ -4,6 +4,8 @@
// resume a render whose thread the user deleted — can reach it without
// importing each other.
+import { UserError } from "./userError";
+
// The keys derive from the route's project id, never the editor store's
// projectId (that still points at the previously open project until loadProject
// lands, which used to leak one project's chat into another).
@@ -449,15 +451,15 @@ export async function flushThreadSaves(): Promise<void> {
// A failed save is told once in the console and shown in the panel until a
// save lands again — for this browser's copy and for a cloud project's server
// copy alike.
-const failures: Record<"local" | "cloud", string | null> = { local: null, cloud: null };
+const failures: Record<"local" | "cloud", UserError | null> = { local: null, cloud: null };
const warned = { local: false, cloud: false };
const failureChanges = new Set<() => void>();
-function setFailure(where: "local" | "cloud", message: string | null): void {
- if (message === failures[where]) return;
+function setFailure(where: "local" | "cloud", message: UserError | null): void {
+ if (message?.code === failures[where]?.code) return;
failures[where] = message;
for (const onChange of failureChanges) onChange();
}
-function setSaveFailure(message: string | null): void {
+function setSaveFailure(message: UserError | null): void {
setFailure("local", message);
}
function saveFailed(err: unknown): void {
@@ -467,8 +469,8 @@ function saveFailed(err: unknown): void {
}
setSaveFailure(
isQuotaError(err)
- ? "Chat history couldn't be saved — this browser's storage is full."
- : "Chat history couldn't be saved in this browser.",
+ ? new UserError("chat_save_storage_full", "Chat history couldn't be saved — this browser's storage is full.")
+ : new UserError("chat_save_local_failed", "Chat history couldn't be saved in this browser."),
);
}
/** A cloud project's thread didn't reach the server. It is still in this
@@ -478,12 +480,12 @@ export function cloudThreadSaveFailed(err: unknown): void {
warned.cloud = true;
console.warn("[chat] couldn't save chat history to the cloud", err);
}
- setFailure("cloud", "Chat history couldn't be saved to the cloud — it's kept in this browser and will retry.");
+ setFailure("cloud", new UserError("chat_save_cloud_failed", "Chat history couldn't be saved to the cloud — it's kept in this browser and will retry."));
}
export function cloudThreadSaved(): void {
setFailure("cloud", null);
}
-export function threadSaveFailure(): string | null {
+export function threadSaveFailure(): UserError | null {
return failures.local ?? failures.cloud;
}
export function subscribeThreadSaveFailure(onChange: () => void): () => void {
diff --git a/site/src/cut/lib/cloudJob.ts b/site/src/cut/lib/cloudJob.ts
index 91fb3da9..b7a18f12 100644
--- a/site/src/cut/lib/cloudJob.ts
+++ b/site/src/cut/lib/cloudJob.ts
@@ -1,13 +1,15 @@
"use client";
import { apiJson, type CutBackend } from "./backend";
+import { errorFromBody, type UserError } from "./userError";
/**
* Wait on a cloud render job (URL import, conversion) and hand back its
* result. The cloud answers those routes with a job id and a worker does the
* work, so the client polls: 2s cadence, a ten-minute ceiling, and a run of
* failed polls before giving up — a single dropped request keeps polling.
- * Failure reports what the job itself said, or `fallback`.
+ * Failure reports what the job itself said, with the code the worker recorded,
+ * or `fallback`.
*
* `onState` sees every state the job reports ("queued", "running", …), so a
* surface waiting on the job can say which one it is in; `onProgress` sees
@@ -16,18 +18,18 @@ import { apiJson, type CutBackend } from "./backend";
export async function pollCloudJob<T>(
jobId: string,
backend: CutBackend,
- fallback: string,
+ fallback: UserError | string,
{
timedOut = fallback,
onState,
onProgress,
- }: { timedOut?: string; onState?: (state: string) => void; onProgress?: (progress: number) => void } = {}
+ }: { timedOut?: UserError | string; onState?: (state: string) => void; onProgress?: (progress: number) => void } = {}
): Promise<T> {
const deadline = Date.now() + 10 * 60 * 1000;
const MAX_STRIKES = 6;
let strikes = 0;
for (;;) {
- if (Date.now() > deadline) throw new Error(timedOut);
+ if (Date.now() > deadline) throw errorFromBody(null, timedOut);
await new Promise((r) => setTimeout(r, 2000));
let res: Response | null = null;
try {
@@ -36,16 +38,16 @@ export async function pollCloudJob<T>(
// Network blip — a strike, counted below.
}
// The create call returned this job's id, so a 404 means it's gone.
- if (res?.status === 404) throw new Error(fallback);
+ if (res?.status === 404) throw errorFromBody(null, fallback);
if (!res?.ok) {
- if (++strikes >= MAX_STRIKES) throw new Error(fallback);
+ if (++strikes >= MAX_STRIKES) throw errorFromBody(null, fallback);
continue;
}
strikes = 0;
const job = await apiJson<{ state?: string; progress?: number; result?: T }>(res);
if (job.state) onState?.(job.state);
if (typeof job.progress === "number") onProgress?.(job.progress);
- if (job.state === "error") throw new Error(job.error ?? fallback);
+ if (job.state === "error") throw errorFromBody(job, fallback);
if (job.state === "done") return (job.result ?? {}) as T;
}
}
diff --git a/site/src/cut/lib/cloudLibraryUpload.ts b/site/src/cut/lib/cloudLibraryUpload.ts
index a56c62f5..ca1fbefe 100644
--- a/site/src/cut/lib/cloudLibraryUpload.ts
+++ b/site/src/cut/lib/cloudLibraryUpload.ts
@@ -8,6 +8,7 @@ import type { ConvertMode } from "@/cut/lib/convertMode";
import type { CompatCover } from "@/cut/lib/proxyNames";
import type { LibraryAsset, LibrarySource } from "@/cut/lib/library";
import type { LibraryUploadStage, LibraryUploadState } from "@/cut/lib/libraryUpload";
+import { UserError, errorFromBody, replyError } from "@/cut/lib/userError";
export type CloudUploadOptions = {
name?: string;
@@ -39,13 +40,13 @@ export async function uploadCloudLibraryMedia(file: File, options: CloudUploadOp
}),
});
const body = await apiJson<LibraryAsset | { jobId: string }>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not prepare this upload.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("upload_prepare_failed", "Could not prepare this upload."));
const asset = "jobId" in body ? await pollCloudJob<LibraryAsset>(body.jobId, cloudBackend,
- "Could not prepare this upload.", {
- timedOut: "This file is still being prepared. Retry to check its progress.",
+ new UserError("upload_prepare_failed", "Could not prepare this upload."), {
+ timedOut: new UserError("upload_still_preparing", "This file is still being prepared. Retry to check its progress."),
onState: (status) => options.onStage?.(status === "queued" ? "queued" : "preparing"),
}) : body;
- if (!asset.id || !asset.fileName) throw new Error("The import returned no media.");
+ if (!asset.id || !asset.fileName) throw new UserError("import_no_media", "The import returned no media.");
return { ...asset, residency: "cloud" };
}
@@ -53,7 +54,7 @@ export async function uploadCloudLibraryMedia(file: File, options: CloudUploadOp
* cloud worker: the file stages on the cloud shelf, the proxy comes back,
* and both leave the shelf. */
export async function compatInTheCloud(file: File, cover: CompatCover, onProgress?: (p: number) => void): Promise<Blob> {
- const failed = "Could not make the preview proxy.";
+ const failed = new UserError("proxy_failed", "Could not make the preview proxy.");
const asset = await uploadCloudLibraryMedia(file, { name: file.name });
try {
const res = await cloudBackend.fetch(`/api/cut/library/${encodeURIComponent(asset.id)}/proxy`, {
@@ -62,13 +63,13 @@ export async function compatInTheCloud(file: File, cover: CompatCover, onProgres
body: JSON.stringify({ compat: cover }),
});
const body = await apiJson<LibraryAsset | { jobId: string }>(res);
- if (!res.ok) throw new Error(body.error ?? failed);
+ if (!res.ok) throw errorFromBody(body, failed);
const landed = "jobId" in body
- ? await pollCloudJob<LibraryAsset>(body.jobId, cloudBackend, failed, { timedOut: "The preview proxy took too long.", onProgress })
+ ? await pollCloudJob<LibraryAsset>(body.jobId, cloudBackend, failed, { timedOut: new UserError("proxy_too_slow", "The preview proxy took too long."), onProgress })
: body;
- if (!landed.proxyFile) throw new Error(failed);
+ if (!landed.proxyFile) throw failed;
const media = await cloudBackend.fetch(`/api/cut/library/media/${encodeURIComponent(landed.proxyFile)}`);
- if (!media.ok) throw new Error(failed);
+ if (!media.ok) throw failed;
return await media.blob();
} finally {
await cloudBackend.fetch(`/api/cut/library/${encodeURIComponent(asset.id)}`, { method: "DELETE" }).catch(() => {});
@@ -85,12 +86,12 @@ export async function withCloudPreparedMedia<T>(
let prepared: File;
try {
const response = await cloudBackend.fetch(`/api/cut/library/media/${encodeURIComponent(asset.fileName)}`);
- if (!response.ok) throw new Error("Could not read the prepared media.");
+ if (!response.ok) throw new UserError("prepared_media_read_failed", "Could not read the prepared media.");
const blob = await response.blob();
prepared = new File([blob], asset.fileName, { type: blob.type });
} finally {
const removed = await cloudBackend.fetch(`/api/cut/library/${encodeURIComponent(asset.id)}`, { method: "DELETE" });
- if (!removed.ok) throw new Error("Could not remove the temporary cloud import.");
+ if (!removed.ok) throw new UserError("temp_import_remove_failed", "Could not remove the temporary cloud import.");
if (options.state) delete options.state.key;
}
// Finish staging cleanup before adoption so a cleanup retry cannot import twice.
diff --git a/site/src/cut/lib/cloudTranscribe.ts b/site/src/cut/lib/cloudTranscribe.ts
index 63098960..3527baab 100644
--- a/site/src/cut/lib/cloudTranscribe.ts
+++ b/site/src/cut/lib/cloudTranscribe.ts
@@ -15,6 +15,7 @@ import { renderMix as mixAudio } from "./audioMix";
import { apiFetch } from "./backend";
import { cloudBackend } from "./backend/cloud";
import { mediaUrl, type MediaAsset, type SubtitleCue } from "./types";
+import { replyError, UserError } from "./userError";
import { wavHeader } from "./wav";
/** Mirror of the engine's TranscribeSpec (server/transcribe.ts) minus projectId. */
@@ -100,22 +101,13 @@ interface WireCue {
words?: { t0: number; t1: number; w: string }[];
}
-// The route's error code for an account whose included chunks are used up.
-// A `freeOnly` caller reads it off the thrown error and stops transcribing.
+// The route's error code for an account whose included chunks are used up,
+// which is also the failure's catalog code. A `freeOnly` caller reads it off
+// the thrown error and stops transcribing.
const FREE_EXHAUSTED_CODE = "free_transcription_exhausted";
-export class HostedTranscribeError extends Error {
- public constructor(
- message: string,
- public readonly code?: string
- ) {
- super(message);
- this.name = "HostedTranscribeError";
- }
-}
-
export const isFreeTranscriptionExhausted = (e: unknown): boolean =>
- e instanceof HostedTranscribeError && e.code === FREE_EXHAUSTED_CODE;
+ e instanceof UserError && e.code === FREE_EXHAUSTED_CODE;
/** The transport a run posts its chunks on. Defaults to the active backend;
* mic dictation names the hosted one, because the take it is falling back with
@@ -139,10 +131,12 @@ async function postChunk(
| { cues?: WireCue[]; error?: string; message?: string }
| null;
if (!res.ok) {
- throw new HostedTranscribeError(
- body?.message ?? body?.error ?? "Transcription failed.",
- body?.error
- );
+ // The used-up allowance answers 402 with its own code under `error`, so it
+ // is read before the credits wall would claim the status.
+ if (body?.error === FREE_EXHAUSTED_CODE) {
+ throw new UserError(FREE_EXHAUSTED_CODE, body.message ?? "The free transcription allowance is used up.");
+ }
+ throw replyError(res.status, body, new UserError("transcription_failed", "Transcription failed."));
}
return (body?.cues ?? []).filter(
(c) =>
@@ -247,7 +241,7 @@ export async function cloudTranscribeRecording(blob: Blob, locale?: string): Pro
try {
decoded = await probe.decodeAudioData(bytes);
} catch {
- throw new Error("Could not read the recording's audio.");
+ throw new UserError("recording_audio_unreadable", "Could not read the recording's audio.");
} finally {
void probe.close().catch(() => {});
}
diff --git a/site/src/cut/lib/defaultNames.ts b/site/src/cut/lib/defaultNames.ts
new file mode 100644
index 00000000..7e388f64
--- /dev/null
+++ b/site/src/cut/lib/defaultNames.ts
@@ -0,0 +1,76 @@
+import { createTranslator } from "use-intl/core";
+
+import english from "@/i18n/messages/en/errors.json";
+import { DEFAULT_LOCALE, isLocale, type Locale } from "@/i18n/locales";
+import { translatorFor } from "@/i18n/translator";
+
+// The names the product writes into a person's project when they gave none:
+// a project or note called "Untitled", a new title reading "Your text", a
+// still named "Frame 0:12". They are content, so they are written in the
+// language of the person who created them and stay that way. The catalog is
+// `errors.defaults` (messages/<locale>/errors.json).
+//
+// Two ways in. A request handler (engine, cloud route) knows its caller's
+// locale and asks `defaultNames(locale)`. Code that runs inside one person's
+// session (the page, a headless turn) binds that person's locale once and
+// reads `creatorNames()` synchronously, the way it reads the editor store.
+
+export interface DefaultNames {
+ untitled: string;
+ text: string;
+ /** A still's name for the timecode it was taken at, e.g. "Frame 0:12". */
+ frame: (time: string) => string;
+ /** A duplicate's name, e.g. "Trip copy". */
+ copy: (name: string) => string;
+}
+
+type DefaultsTranslator = (
+ key: "untitled" | "text" | "frame" | "copy",
+ values?: { time: string } | { name: string },
+) => string;
+
+const namesFrom = (t: DefaultsTranslator): DefaultNames => ({
+ untitled: t("untitled"),
+ text: t("text"),
+ frame: (time) => t("frame", { time }),
+ copy: (name) => t("copy", { name }),
+});
+
+// English ships in every bundle, so the sync read always has names.
+const ENGLISH = namesFrom(
+ createTranslator({ locale: DEFAULT_LOCALE, messages: { errors: english }, namespace: "errors.defaults" }),
+);
+
+const loaded = new Map<Locale, DefaultNames>([[DEFAULT_LOCALE, ENGLISH]]);
+let bound: Locale = DEFAULT_LOCALE;
+
+/** The locale a request named, e.g. a create body's `locale`; the default
+ * when it named none the catalog has. */
+export const requestedLocale = (value: unknown): Locale => (isLocale(value) ? value : DEFAULT_LOCALE);
+
+/** The default names in one locale's words. */
+export async function defaultNames(locale: Locale): Promise<DefaultNames> {
+ const hit = loaded.get(locale);
+ if (hit) {
+ return hit;
+ }
+ const t = await translatorFor(locale, "errors");
+ const names = namesFrom((key, values) => t(`defaults.${key}`, values));
+ loaded.set(locale, names);
+ return names;
+}
+
+/** Name what this session creates in `locale` from now on: the page binds
+ * the language it draws in, a headless turn the language of its request.
+ * Settles once that language's names have loaded. */
+export async function bindCreatorLocale(locale: Locale): Promise<void> {
+ bound = locale;
+ await defaultNames(locale);
+}
+
+/** The locale the session bound, for a request that carries it onward. */
+export const creatorLocale = (): Locale => bound;
+
+/** The bound locale's default names. English until its catalog has loaded,
+ * a moment after the bind. */
+export const creatorNames = (): DefaultNames => loaded.get(bound) ?? ENGLISH;
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 1030d7d6..1f8dd6ff 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -4,6 +4,7 @@ import { captureRenderSnapshot, renderDoc, type ExportDoc, type RenderSnapshot }
import { sourceExportPlan, sourceSequence } from "@/cut/lib/sourceExportPlan";
import { DELIVERY_DEFAULTS, EXPORT_PRESETS, EXPORT_RESOLUTIONS } from "./exportPresets";
import { operationFailure, type OperationFailure } from "./operationFailure";
+import { UserError, errorFromBody, type UserErrorParams } from "./userError";
import { projectOperation } from "./projectOperation";
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
@@ -411,13 +412,16 @@ export function audioBitrate(settings: Pick<ExportSettings, "audioCodec" | "audi
return settings.audioCodec === "pcm" ? (settings.audioSampleRate ?? 48_000) * 16 * (settings.audioChannels ?? 2) : settings.audioBitrate ?? 192_000;
}
-/** Human-readable size estimate matching the finished-export MB display. */
-export function formatSizeEstimate(bytes: number): string {
+/** Human-readable size estimate matching the finished-export MB display,
+ * with the number and unit in the reader's locale ("~1.4 MB", "~1,4 Mo"). */
+export function formatSizeEstimate(bytes: number, locale: string): string {
if (bytes <= 0) return "";
const mb = bytes / (1024 * 1024);
- if (mb < 1) return "~1 MB";
- if (mb < 1000) return `~${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;
- return `~${(mb / 1024).toFixed(1)} GB`;
+ const size = (value: number, unit: "megabyte" | "gigabyte", digits: number) =>
+ `~${new Intl.NumberFormat(locale, { style: "unit", unit, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value)}`;
+ if (mb < 1) return size(1, "megabyte", 0);
+ if (mb < 1000) return mb < 10 ? size(mb, "megabyte", 1) : size(Math.round(mb), "megabyte", 0);
+ return size(mb / 1024, "gigabyte", 1);
}
/** Reveal a rendered export in Finder (local engine only). */
@@ -461,7 +465,7 @@ export async function deleteExport(projectId: string, file: string) {
);
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
- throw new Error(body.error ?? "Could not delete the export.");
+ throw errorFromBody(body, new UserError("export_delete_failed", "Could not delete the export."));
}
}
@@ -849,7 +853,9 @@ export function specColor(
if (!asset || asset.type === "image") return { profile: "srgb", matrix: "bt709", fullRange: true };
if (asset.block) return { profile: "rec709", matrix: "bt709", fullRange: false };
const c = asset.color;
- if (!c) throw new Error(`The color of ${asset.fileName} was never read.`);
+ if (!c) {
+ throw new UserError("asset_color_unread", `The color of ${asset.fileName} was never read.`, { file: asset.fileName });
+ }
return { profile: asset.colorProfile ?? c.detected, matrix: c.matrix, fullRange: c.fullRange };
}
@@ -885,7 +891,7 @@ export async function buildExportPayload(
): Promise<ExportPayload> {
// H.264 is an 8-bit delivery; an HDR picture takes HEVC Main 10 or ProRes.
if ((doc.colorSpace ?? "sdr") !== "sdr" && settings.codec === "h264" && target === "export") {
- throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");
+ throw new UserError("export_h264_hdr", "H.264 is 8-bit. Export HDR as HEVC or ProRes.");
}
// Every video's color is read before the spec is: footage the lazy fill
// has not reached would otherwise go out as Rec.709.
@@ -903,7 +909,7 @@ export async function buildExportPayload(
// whole length. Anything on any row gives the project a duration, so having
// one is the same question as having something to render.
if (!(duration > 0)) {
- throw new Error("Add something to the timeline first.");
+ throw new UserError("export_timeline_empty", "Add something to the timeline first.");
}
// The person matte renders first, so the loops below attach subject fields
@@ -1545,19 +1551,33 @@ export async function buildExportPayload(
* its render cap. The worker would say the same, so the export ends here with
* the gate's own words.
*/
-export class ExportRefusedError extends Error {
- constructor(message: string, readonly failure?: OperationFailure) { super(message); }
+export class ExportRefusedError extends UserError {
+ constructor(code: string, message: string, params: UserErrorParams = {}, readonly failure?: OperationFailure) {
+ super(code, message, params);
+ }
}
+const startFailed = () => new UserError("export_start_failed", "Export failed to start.");
+const saveFailed = () => new UserError("export_save_failed", "Could not save the export.");
+
/** Concurrent PUTs a cloud export's inputs go up on. */
const UPLOAD_LANES = 4;
function cloudRefusal(res: Response, body: { error?: string; bytes?: number; quotaBytes?: number } | null | undefined): ExportRefusedError | null {
if (res.ok) return null;
const failure = operationFailure(res.status, body);
- if (failure) return new ExportRefusedError(failure.message, failure);
- if (res.status === 429 || res.status === 413) return new ExportRefusedError(body?.error ?? "Export failed to start.");
- return null;
+ if (failure) {
+ return new ExportRefusedError(failure.code, failure.message, {}, failure);
+ }
+ if (res.status !== 429 && res.status !== 413) {
+ return null;
+ }
+
+ // The gate's own words keep their code; uncoded words read as they came.
+ const reason = errorFromBody(body, startFailed());
+ return reason instanceof UserError
+ ? new ExportRefusedError(reason.code, reason.message, reason.params)
+ : new ExportRefusedError("export_refused", reason.message, { reason: reason.message });
}
/** Serialize a payload to the engine's multipart form: PNGs in render order,
@@ -1600,7 +1620,7 @@ async function postExport(
const preBody =
await apiJson<{ files?: { name: string; key: string; type?: string; url: string }[] }>(pre);
if (!pre.ok || !preBody.files) {
- throw cloudRefusal(pre, preBody) ?? new Error(preBody.error ?? "Export failed to start.");
+ throw cloudRefusal(pre, preBody) ?? errorFromBody(preBody, startFailed());
}
const byName = new Map(preBody.files.map((f) => [f.name, f]));
// The list carries a borrowed render's whole media set, so the PUTs go a
@@ -1610,7 +1630,9 @@ async function postExport(
Array.from({ length: Math.min(UPLOAD_LANES, queue.length) }, async () => {
for (let p = queue.shift(); p; p = queue.shift()) {
const target = byName.get(p.name);
- if (!target) throw new Error("Export failed to start.");
+ if (!target) {
+ throw startFailed();
+ }
// The content type the URL was signed with: it is the one the
// signature covers, and for a video it differs from the blob's.
await putSigned(target.url, p.blob, target.type || "image/png", { signal });
@@ -1631,7 +1653,9 @@ async function postExport(
* asking for them is refused before anything renders. */
function stemsFor(doc: ExportDoc): StemDef[] {
const stems = planStems(doc);
- if (stems.length === 0) throw new ExportRefusedError("Nothing in this cut makes a sound to split into stems.");
+ if (stems.length === 0) {
+ throw new ExportRefusedError("export_stems_silent", "Nothing in this cut makes a sound to split into stems.");
+ }
return stems;
}
@@ -1671,7 +1695,9 @@ export async function pollExport(
backend: CutBackend = getBackend()
): Promise<string> {
for (;;) {
- if (isCanceled()) throw new Error("Export canceled.");
+ if (isCanceled()) {
+ throw new UserError("export_canceled", "Export canceled.");
+ }
await new Promise((r) => setTimeout(r, 400));
const st = await backend.fetch(`/api/cut/export/${jobId}`);
const status = await apiJson<{
@@ -1679,7 +1705,9 @@ export async function pollExport(
progress?: number;
outName?: string;
}>(st);
- if (!st.ok || status.status === "error" || status.status === "canceled") throw new Error(status.error ?? "Export failed.");
+ if (!st.ok || status.status === "error" || status.status === "canceled") {
+ throw errorFromBody(status, new UserError("export_failed", "Export failed."));
+ }
onProgress("Rendering", status.progress ?? 0);
if (status.status === "done") return status.outName ?? "export.mp4";
}
@@ -1740,7 +1768,10 @@ async function assertEngineCarries(
const has = await engineFeatures();
for (const [feature, wanted, what] of wants) {
if (wanted && !has.has(feature)) {
- throw new ExportRefusedError(`Update the Donkey app to ${what}.`);
+ throw new ExportRefusedError("app_update_required", `Update the Donkey app to ${what}.`, {
+ feature: feature.replace(".", "_"),
+ what,
+ });
}
}
}
@@ -1761,7 +1792,7 @@ export async function createExportJob(
const res = await postExport(projectId, payload, outName, backend);
const body = await apiJson<{ id?: string }>(res);
if (!res.ok || !body.id) {
- throw cloudRefusal(res, body) ?? new Error(body.error ?? "Export failed to start.");
+ throw cloudRefusal(res, body) ?? errorFromBody(body, startFailed());
}
return body.id;
}
@@ -1823,10 +1854,10 @@ export async function runBrowserExport(
});
const claimed = await apiJson<{ jobId?: string; url?: string; outName?: string; type?: string; stemsUrl?: string }>(claim);
if (!claim.ok || !claimed.jobId || !claimed.url) {
- throw cloudRefusal(claim, claimed) ?? new Error(claimed.error ?? "Export failed to start.");
+ throw cloudRefusal(claim, claimed) ?? errorFromBody(claimed, startFailed());
}
if (settings.stems && !claimed.stemsUrl) {
- throw new Error("The cloud did not hold a place for the stems.");
+ throw new UserError("cloud_stems_slot_missing", "The cloud did not hold a place for the stems.");
}
const jobId = claimed.jobId;
opts.onClaimed?.(jobId);
@@ -1889,7 +1920,7 @@ export async function runBrowserExport(
});
const body = await apiJson<{ id?: string }>(done);
if (!done.ok || !body.id) {
- throw cloudRefusal(done, body) ?? new Error(body.error ?? "Could not save the export.");
+ throw cloudRefusal(done, body) ?? errorFromBody(body, saveFailed());
}
return body.id;
} catch (err) {
@@ -1937,7 +1968,9 @@ async function runEngineExport(
}),
});
const claimed = await apiJson<{ id?: string; outName?: string }>(claim);
- if (!claim.ok || !claimed.id) throw new Error(claimed.error ?? "Export failed to start.");
+ if (!claim.ok || !claimed.id) {
+ throw errorFromBody(claimed, startFailed());
+ }
const jobId = claimed.id;
opts.onClaimed?.(jobId);
// The engine's feed carries the progress to every other tab's dock; a
@@ -1987,7 +2020,12 @@ async function runEngineExport(
void stems.discard();
}
if (landed.status === 409) throw new DOMException("Export canceled.", "AbortError");
- if (!landed.ok) throw new Error((await apiJson<object>(landed)).error ?? "Could not save the stems.");
+ if (!landed.ok) {
+ throw errorFromBody(
+ await apiJson<object>(landed),
+ new UserError("export_stems_save_failed", "Could not save the stems."),
+ );
+ }
}
let done: Response;
try {
@@ -2007,7 +2045,9 @@ async function runEngineExport(
// ends here the way a cancel in this tab does.
if (done.status === 409) throw new DOMException("Export canceled.", "AbortError");
const body = await apiJson<{ id?: string }>(done);
- if (!done.ok || !body.id) throw new Error(body.error ?? "Could not save the export.");
+ if (!done.ok || !body.id) {
+ throw errorFromBody(body, saveFailed());
+ }
opts.onProgress?.(1);
return body.id;
} catch (err) {
@@ -2050,7 +2090,8 @@ async function saveStems(
await dropStoredExport(projectId, videoName);
if (err instanceof DOMException && err.name === "AbortError") throw err;
if (err instanceof ExportRefusedError) throw err;
- throw new ExportRefusedError(`The stems could not be saved: ${err instanceof Error ? err.message : String(err)}`);
+ const reason = err instanceof Error ? err.message : String(err);
+ throw new ExportRefusedError("stems_save_failed", `The stems could not be saved: ${reason}`, { reason });
} finally {
releaseRegistered(`/api/cut/projects/${projectId}/`);
}
@@ -2138,18 +2179,24 @@ async function renderBorrowedFile(
const asset = doc.assets.find((a) => a.fileName === name);
const url = asset ? renderAssetUrl(projectId, asset) : null;
const blob = url ? resolveRegisteredBlob(url) : null;
- if (!blob) throw new Error(`${name} is not in this browser's storage.`);
+ if (!blob) {
+ throw new UserError("export_media_not_stored", `${name} is not in this browser's storage.`, { name });
+ }
payload.pngs.push({ name, blob });
}
const res = await postExport(projectId, payload, requestedName, backend, { mediaFrom: "overlays" }, opts.signal);
const body = await apiJson<{ id?: string }>(res);
- if (!res.ok || !body.id) throw cloudRefusal(res, body) ?? new Error(body.error ?? "Render failed to start.");
+ if (!res.ok || !body.id) {
+ throw cloudRefusal(res, body) ?? errorFromBody(body, new UserError("render_start_failed", "Render failed to start."));
+ }
cloudJobId = body.id;
opts.onClaimed?.(cloudJobId);
const outName = await pollExport(cloudJobId, (_stage, ratio) => opts.onProgress?.(ratio * 0.95), () => !!opts.signal?.aborted, backend);
stop();
const fileRes = await backend.fetch(`/api/cut/export/${cloudJobId}/file`, { signal: opts.signal });
- if (!fileRes.ok) throw new Error("Could not fetch the rendered file.");
+ if (!fileRes.ok) {
+ throw new UserError("render_fetch_failed", "Could not fetch the rendered file.");
+ }
const file = new File([await fileRes.blob()], outName, { type: deliveryContainer(settings.container).mime });
stop();
return file;
@@ -2271,7 +2318,9 @@ export async function submitPreviewSnapshot(
const settings = previewSettings(doc.aspect);
if (backend.kind === "browser") {
const directory = await projectDir(projectId);
- if (!directory) throw new Error("Project not found in browser storage.");
+ if (!directory) {
+ throw new UserError("project_not_in_browser", "Project not found in browser storage.");
+ }
holdRegistered(`/api/cut/projects/${projectId}/`);
try {
// The hover preview is an SDR web picture whatever the project delivers.
@@ -2290,7 +2339,9 @@ export async function submitPreviewSnapshot(
signal?.throwIfAborted();
await writeFileAt(directory, "preview.mp4", rendered.file);
const file = await readFileAt(directory, "preview.mp4");
- if (!file) throw new Error("Could not read the rendered preview.");
+ if (!file) {
+ throw new UserError("preview_read_failed", "Could not read the rendered preview.");
+ }
const url = registerBlobFile(`/api/cut/projects/${projectId}/preview`, file);
return { id: revision, projectId, revision, url, status: "done" };
} finally {
@@ -2304,7 +2355,9 @@ export async function submitPreviewSnapshot(
signal?.throwIfAborted();
const res = await postExport(projectId, payload, "preview.mp4", backend, { revision }, signal);
const body = await apiJson<{ id?: string }>(res);
- if (!res.ok || !body.id) throw cloudRefusal(res, body) ?? new Error(body.error ?? "Preview failed to start.");
+ if (!res.ok || !body.id) {
+ throw cloudRefusal(res, body) ?? errorFromBody(body, new UserError("preview_start_failed", "Preview failed to start."));
+ }
if (signal?.aborted) {
cancelExportJob(body.id, backend);
signal.throwIfAborted();
@@ -2332,7 +2385,9 @@ export async function renderPreviewSnapshot(
if (backend.kind === "cloud") {
const response = await backend.fetch(`/api/cut/export/${job.id}`);
const body = await apiJson<{ artifact?: { url: string; expiresIn: number } }>(response);
- if (!response.ok || !body.artifact) throw new Error(body.error ?? "Preview is unavailable.");
+ if (!response.ok || !body.artifact) {
+ throw errorFromBody(body, new UserError("preview_unavailable", "Preview is unavailable."));
+ }
return { id: job.id, projectId: job.projectId, revision: job.revision, url: body.artifact.url,
expiresAt: Date.now() + body.artifact.expiresIn * 1000 };
}
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index f6114679..913a2789 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -65,6 +65,7 @@ import type { ExportSettings } from "./exportClient";
import { sourceExportPlan } from "@/cut/lib/sourceExportPlan";
import { prepareSourceRemux } from "@/cut/lib/sourceRemux";
import { deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor } from "./exportDelivery";
+import { UserError } from "./userError";
/** Audio is written at the rate and width a delivery file wants, rather than
* the 16 kHz mono a speech model reads. */
@@ -1085,23 +1086,32 @@ export async function renderProjectToMp4(
} finally { for (const input of inputs.values()) input.dispose(); }
}
const duration = projectDuration(doc);
- if (!(duration > 0)) throw new Error("There is nothing to export yet.");
+ if (!(duration > 0)) {
+ throw new UserError("export_nothing_yet", "There is nothing to export yet.");
+ }
// The window of the timeline the file carries: a range when the settings
// name one, the whole cut otherwise. Frames are drawn at timeline time and
// written at file time, so the file starts at zero.
const from = Math.max(0, settings.range?.start ?? 0);
const span = deliverySpan(settings.range, duration);
- if (!(span > 0)) throw new Error("The export range is empty.");
+ if (!(span > 0)) {
+ throw new UserError("export_range_empty", "The export range is empty.");
+ }
const wanted = deliveryVideoCodec(settings);
- if (!wanted) throw new Error("This browser can't encode ProRes.");
+ if (!wanted) {
+ throw new UserError("browser_prores_unsupported", "This browser can't encode ProRes.");
+ }
const codec = await getFirstEncodableVideoCodec([wanted], {
width: settings.width,
height: settings.height,
});
if (!codec) {
- throw new Error(
- `This browser can't encode ${settings.codec === "hevc" ? "HEVC" : "H.264"} at ${settings.width} × ${settings.height}.`
+ const name = settings.codec === "hevc" ? "HEVC" : "H.264";
+ throw new UserError(
+ "browser_codec_unsupported",
+ `This browser can't encode ${name} at ${settings.width} × ${settings.height}.`,
+ { codec: name, width: settings.width, height: settings.height },
);
}
@@ -1177,7 +1187,9 @@ export async function renderProjectToMp4(
numberOfChannels: settings.audioChannels ?? AUDIO_CHANNELS,
sampleRate: settings.audioSampleRate ?? AUDIO_RATE,
});
- if (!audioCodec) throw new Error("This browser can't encode AAC audio.");
+ if (!audioCodec) {
+ throw new UserError("browser_aac_unsupported", "This browser can't encode AAC audio.");
+ }
// The mix starts its encoder's priming early, so the edit list trims
// the priming and the sound stays on its picture.
const lead = await encoderLead(audioCodec, mix.sampleRate, mix.numberOfChannels);
diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.ts
index 652f9021..f29f2b5a 100644
--- a/site/src/cut/lib/exportStore.ts
+++ b/site/src/cut/lib/exportStore.ts
@@ -7,6 +7,7 @@ import { getBackend, type CutBackend, type CutMode } from "./backend";
import { browserBackend } from "./backend/browser";
import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
+import { errorFields, UserError, type UserErrorParams } from "./userError";
import {
matchSourceSettings,
cancelExportJob,
@@ -41,6 +42,9 @@ export interface ExportJob {
progress: number; // 0..1
outName?: string;
error?: string;
+ /** The failure's code, beside `error`, for the dock to word it. */
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** Epoch ms the encode began (elapsed clock) and the job was created (order). */
startedAt?: number;
createdAt?: number;
@@ -49,6 +53,8 @@ export interface ExportJob {
residency: CutMode;
}
+const EXPORT_CANCELED = new UserError("export_canceled", "Export canceled.");
+
/** The backend a dock row lives on; per-row actions hit this, never the
* globally bound mode. */
export function exportBackend(residency: CutMode): CutBackend {
@@ -68,6 +74,8 @@ export interface LocalRow {
projectName?: string;
status: "preparing" | "rendering" | "error";
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** 0..1 while rendering in this tab. */
progress?: number;
createdAt: number;
@@ -157,10 +165,10 @@ export const useExports = create<ExportsState>((set, get) => ({
set((s) => ({ rendering: s.rendering.filter((id) => !gone.has(id)) }));
};
const fail = (err: unknown) => {
- const msg = err instanceof Error ? err.message : String(err);
+ const failure = errorFields(err, String(err));
set((s) => ({
local: s.local.map((r) =>
- r.id === localId ? { ...r, status: "error" as const, error: msg, abort: undefined } : r
+ r.id === localId ? { ...r, status: "error" as const, ...failure, abort: undefined } : r
),
}));
};
@@ -256,7 +264,7 @@ export const useExports = create<ExportsState>((set, get) => ({
cancelExportJob(id, job ? exportBackend(job.residency) : undefined);
set((s) => ({
jobs: s.jobs.map((j) =>
- j.id === id ? { ...j, status: "error", error: "Export canceled." } : j
+ j.id === id ? { ...j, status: "error", ...errorFields(EXPORT_CANCELED, "") } : j
),
}));
void get().refresh();
diff --git a/site/src/cut/lib/factCheck.ts b/site/src/cut/lib/factCheck.ts
index 6a189e72..292edde2 100644
--- a/site/src/cut/lib/factCheck.ts
+++ b/site/src/cut/lib/factCheck.ts
@@ -1,6 +1,7 @@
import type { FactCheckResponse } from "@/lib/inference/factCheck";
import { hostedPost } from "./hosted";
-import { readHostedError } from "./hostedError";
+import { readHostedFailure } from "./hostedError";
+import { UserError } from "./userError";
// Checking a video's claims against the web, through the hosted fact-check
// route. The page, the cloud runner and the ChatGPT card all reach it with the
@@ -11,7 +12,11 @@ import { readHostedError } from "./hostedError";
export async function checkFacts(input: { claims?: unknown; context?: unknown }): Promise<FactCheckResponse> {
const res = await hostedPost("/api/inference/fact-check", { claims: input.claims, context: input.context });
if (!res.ok) {
- throw new Error(await readHostedError(res, "Sign in to Donkey to check facts.", `The fact check failed (${res.status}).`));
+ throw await readHostedFailure(
+ res,
+ new UserError("sign_in_to_check_facts", "Sign in to Donkey to check facts."),
+ new UserError("fact_check_failed", `The fact check failed (${res.status}).`, { status: res.status }),
+ );
}
return (await res.json()) as FactCheckResponse;
}
diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.ts
index b3a6a1ee..f7221786 100644
--- a/site/src/cut/lib/genScene.ts
+++ b/site/src/cut/lib/genScene.ts
@@ -15,6 +15,7 @@ import { projectWriteMode, withProjectDoc } from "./genvideo/docWriter";
import type { RefAsset, Shot, VideoEvent, VideoPhase, VideoProject } from "./genvideo/types";
import { useEditor } from "./store";
import { isLinkedAssetType, nearestAspect } from "./types";
+import { errorFields, type UserErrorParams } from "./userError";
import { defaultVideoAspects } from "./videoModels";
// Brief-to-video ("generate a video") controller. It owns one VideoOrchestrator
@@ -57,6 +58,8 @@ export interface SceneRun {
* it made (sheets, frames, takes), rendered in the chat card in order. */
feed: SceneFeedItem[];
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** When the run began (planning), for the elapsed clock. */
startedAt: number;
/** When rendering began (approval) — the render timer counts from here, not
@@ -446,6 +449,8 @@ function applyEvent(projectId: string, e: VideoEvent): void {
case "error":
note(e.message);
run.error = e.message;
+ run.errorCode = e.errorCode;
+ run.errorParams = e.errorParams;
break;
}
return { run };
@@ -565,10 +570,20 @@ function syncFromProject(projectId: string): void {
}
}
-function fail(projectId: string, message: string): void {
+function fail(projectId: string, failure: unknown): void {
+ const fields = errorFields(failure, String(failure));
useGenScene.setState((s) =>
s.run && s.run.projectId === projectId
- ? { run: { ...s.run, status: "failed", error: message, endedAt: Date.now() } }
+ ? {
+ run: {
+ ...s.run,
+ status: "failed",
+ errorCode: undefined,
+ errorParams: undefined,
+ ...fields,
+ endedAt: Date.now(),
+ },
+ }
: s
);
// Failed is terminal — whatever the run placed belongs to the user now.
@@ -596,7 +611,7 @@ function failed(projectId: string, orch: SceneOrchestrator): (e: unknown) => voi
return;
}
if (orchestrators.get(projectId) === orch && !orch.isAborted) {
- fail(projectId, e instanceof Error ? e.message : String(e));
+ fail(projectId, e);
}
};
}
@@ -862,6 +877,8 @@ export const useGenScene = create<GenSceneState>((set, get) => ({
...s.run,
status: plan.breakdownApproved ? ("generating" as const) : ("planning" as const),
error: undefined,
+ errorCode: undefined,
+ errorParams: undefined,
endedAt: undefined,
renderStartedAt: Date.now(),
},
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index a2ba3eff..7a545132 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -16,8 +16,7 @@ import {
stockAssetInDoc,
upsertRenderInDoc,
} from "./genvideo/docWriter";
-import { NO_CREDITS_MESSAGE } from "./credits";
-import { readHostedError } from "./hostedError";
+import { NoCreditsError, readHostedFailure } from "./hostedError";
import { CUT_APP_BASE } from "./nav";
import { hostedFetch, hostedPost } from "./hosted";
import { enrichAsset, importFileToProject, uploadProjectImage } from "./media";
@@ -26,6 +25,7 @@ import { useGenNotify } from "./genNotify";
import { IMAGE_ASPECTS, useImageGen } from "./imageGen";
import { useEditor } from "./store";
import { mediaSlug, nearestAspect, type MediaAsset, type RenderRecord } from "./types";
+import { UserError, errorFields, type UserErrorParams } from "./userError";
import {
DEFAULT_VIDEO_RESOLUTION,
aspectFramingNote,
@@ -53,6 +53,8 @@ export interface GenerateJob {
startedAt: number;
status: "running" | "done" | "error";
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** The project asset the finished generation landed as. */
assetId?: string;
/** The chat thread that launched this render, when it wasn't the panel.
@@ -276,8 +278,10 @@ interface GenerationResponse {
metadata?: Record<string, unknown>;
}
-const readError = (res: Response, fallback: string) =>
- readHostedError(res, "Sign in to Donkey to generate media.", fallback);
+const readFailure = (res: Response, fallback: UserError) =>
+ readHostedFailure(res, new UserError("sign_in_to_generate_media", "Sign in to Donkey to generate media."), fallback);
+
+const videoFailed = () => new UserError("video_generation_failed", "Video generation failed.");
const providerError = (error: unknown): string | null => {
if (typeof error === "string" && error) return error;
@@ -339,7 +343,14 @@ function readPersistedJobs(): GenerateJob[] {
.filter((j) => j?.id)
.map((j) =>
j.status === "running" && !j.poll
- ? { ...j, status: "error" as const, error: "Interrupted by a reload before the render started." }
+ ? {
+ ...j,
+ status: "error" as const,
+ ...errorFields(
+ null,
+ new UserError("video_render_interrupted", "Interrupted by a reload before the render started."),
+ ),
+ }
: j
);
} catch {
@@ -420,6 +431,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
startedAt: j.startedAt,
status: j.status,
...(j.error !== undefined ? { error: j.error } : {}),
+ ...(j.errorCode !== undefined ? { errorCode: j.errorCode, errorParams: j.errorParams ?? {} } : {}),
...(j.assetId !== undefined ? { assetId: j.assetId } : {}),
};
const backend = jobBackend(j);
@@ -453,7 +465,12 @@ export const useGenerate = create<GenerateState>((set, get) => {
};
const fail = (id: string, err: unknown) =>
- update(id, { status: "error", error: err instanceof Error ? err.message : String(err) });
+ update(id, {
+ status: "error",
+ errorCode: undefined,
+ errorParams: undefined,
+ ...errorFields(err, String(err)),
+ });
// The job after it has settled, for callers that awaited the run.
const settled = (id: string, fallback: GenerateJob): GenerateJob =>
@@ -507,7 +524,9 @@ export const useGenerate = create<GenerateState>((set, get) => {
metadata: gen.metadata ?? {},
},
});
- if (Date.now() > deadline) throw new Error("The video render is taking too long — try again.");
+ if (Date.now() > deadline) {
+ throw new UserError("video_render_timeout", "The video render is taking too long — try again.");
+ }
await sleep(REFRESH_MS);
const poll = await hostedPost("/api/inference/assets/refresh", {
id: gen.id,
@@ -519,11 +538,14 @@ export const useGenerate = create<GenerateState>((set, get) => {
providerPollingUrl: gen.providerPollingUrl,
metadata: gen.metadata ?? {},
});
- if (!poll.ok) throw new Error(await readError(poll, "Video generation failed."));
+ if (!poll.ok) {
+ throw await readFailure(poll, videoFailed());
+ }
gen = (await poll.json()) as GenerationResponse;
}
if (gen.status !== "completed") {
- throw new Error(providerError(gen.error) ?? "Video generation failed.");
+ const reason = providerError(gen.error);
+ throw reason ? new Error(reason) : videoFailed();
}
// Owner deleted while the render finished: skip the import entirely so no
// file is even written for media nobody will ever see.
@@ -538,17 +560,21 @@ export const useGenerate = create<GenerateState>((set, get) => {
});
} else if (out?.url) {
const dl = await fetch(out.url);
- if (!dl.ok) throw new Error("Could not download the generated video.");
+ if (!dl.ok) {
+ throw new UserError("video_download_failed", "Could not download the generated video.");
+ }
file = new File([await dl.arrayBuffer()], fileName, {
type: out.contentType ?? "video/mp4",
});
} else {
- throw new Error("The provider returned no video.");
+ throw new UserError("video_output_missing", "The provider returned no video.");
}
const backend = jobBackend(job);
const asset = await importFileToProject(job.projectId, file, backend);
- if (!asset) throw new Error("Could not import the generated video.");
+ if (!asset) {
+ throw new UserError("video_import_failed", "Could not import the generated video.");
+ }
// The owner may have been deleted during the import (the file write is a
// round trip): drop the file we just wrote rather than leave it orphaned.
if (aborted()) {
@@ -659,10 +685,15 @@ export const useGenerate = create<GenerateState>((set, get) => {
...(opts?.negativePrompt ? { negativePrompt: opts.negativePrompt } : {}),
},
});
- if (!res.ok) throw new Error(await readError(res, "Video generation failed."));
+ if (!res.ok) {
+ throw await readFailure(res, videoFailed());
+ }
return (await res.json()) as GenerationResponse;
};
+ // The last rung's thrown failure, kept whole so the job records its code;
+ // the walk itself reports only the English.
+ let lastFailure: unknown = null;
const settledRun = (async () => {
try {
const outcome = await walkLadder(
@@ -673,12 +704,17 @@ export const useGenerate = create<GenerateState>((set, get) => {
// settles — a reload that adopts this in-flight job must still
// know which rung (anchored or not) produced the take.
update(job.id, { rung });
- const gen = await submitRung(attempt);
- // The backend took the submit — a render is genuinely in flight
- // now (instant rejects throw above and never reach here). A later
- // polling failure still fails the job, but it did start.
- reportSubmit({ ok: true });
- await finishVideo(job.id, gen, jobOpts?.onDone, Date.now());
+ try {
+ const gen = await submitRung(attempt);
+ // The backend took the submit — a render is genuinely in flight
+ // now (instant rejects throw above and never reach here). A later
+ // polling failure still fails the job, but it did start.
+ reportSubmit({ ok: true });
+ await finishVideo(job.id, gen, jobOpts?.onDone, Date.now());
+ } catch (err) {
+ lastFailure = err;
+ throw err;
+ }
},
{
// The next rung is a fresh submission: drop the dead rung's poll
@@ -686,10 +722,12 @@ export const useGenerate = create<GenerateState>((set, get) => {
onRungFailed: () => update(job.id, { poll: undefined }),
// The balance fails every rung identically — stop there so a
// render nobody can pay for fails fast, not once per rung.
- fatal: (error) => error === NO_CREDITS_MESSAGE,
+ fatal: () => lastFailure instanceof NoCreditsError,
}
);
- if (!outcome.ok) fail(job.id, new Error(outcome.error));
+ if (!outcome.ok) {
+ fail(job.id, lastFailure ?? videoFailed());
+ }
} finally {
releaseJobLease(job.id);
// No rung was ever accepted: the render never started, so report the
@@ -768,10 +806,14 @@ export const useGenerate = create<GenerateState>((set, get) => {
// The image model takes a real frame + detail via imageConfig; no prompt steering.
parameters: { aspectRatio: aspect, imageSize: resolution },
});
- if (!res.ok) throw new Error(await readError(res, "Image generation failed."));
+ if (!res.ok) {
+ throw await readFailure(res, new UserError("image_generation_failed", "Image generation failed."));
+ }
const gen = (await res.json()) as GenerationResponse;
const out = gen.outputs.find((o) => o.dataBase64);
- if (!out?.dataBase64) throw new Error("The provider returned no image.");
+ if (!out?.dataBase64) {
+ throw new UserError("image_output_missing", "The provider returned no image.");
+ }
// Mark it generated so it surfaces in the generate panel; a stock
// image imported from a tile sends no origin (plain import).
@@ -784,7 +826,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
{
name: promptName(prompt),
origin: "generated",
- failMessage: "Could not add the image to the project.",
+ failMessage: new UserError("image_add_to_project_failed", "Could not add the image to the project."),
backend,
}
);
@@ -852,6 +894,8 @@ export const useGenerate = create<GenerateState>((set, get) => {
status: "running",
startedAt: Date.now(),
error: undefined,
+ errorCode: undefined,
+ errorParams: undefined,
assetId: undefined,
rung: undefined,
poll: undefined,
diff --git a/site/src/cut/lib/genvideo/adapters/media.ts b/site/src/cut/lib/genvideo/adapters/media.ts
index 92b0fe63..e0482f62 100644
--- a/site/src/cut/lib/genvideo/adapters/media.ts
+++ b/site/src/cut/lib/genvideo/adapters/media.ts
@@ -44,6 +44,7 @@ import { buildShotAttempts } from "../shotAttempts";
import type { ImageRole, VideoRole, VoiceRole } from "../capabilities";
import { refRoleNote } from "../prompt";
import type { RefAsset } from "../types";
+import { UserError, errorFromBody } from "../../userError";
/** Resolve the pipeline's media-id references to the project assets the
* generators take, dropping any that are no longer in the project. Resolution
@@ -81,7 +82,7 @@ export function makeImageRole(projectId: string, chatId?: string): ImageRole {
...(chatId ? { chatId } : {}),
});
if (job.status !== "done" || !job.assetId) {
- throw new Error(job.error || "Image generation failed.");
+ throw errorFromBody(job, new UserError("image_generation_failed", "Image generation failed."));
}
return job.assetId;
},
@@ -186,7 +187,7 @@ export function makeVideoRole(projectId: string, chatId?: string): VideoRole {
}).settled;
if (job.status === "done" && job.assetId)
return { mediaId: job.assetId, anchored: anchoredRung(job.rung) };
- throw new Error(job.error || "Video generation failed.");
+ throw errorFromBody(job, new UserError("video_generation_failed", "Video generation failed."));
},
};
}
diff --git a/site/src/cut/lib/genvideo/adapters/music.ts b/site/src/cut/lib/genvideo/adapters/music.ts
index 63980d95..91c86e23 100644
--- a/site/src/cut/lib/genvideo/adapters/music.ts
+++ b/site/src/cut/lib/genvideo/adapters/music.ts
@@ -14,6 +14,7 @@ import { hostedPost } from "../../hosted";
import { enrichAsset, importFileToProject } from "../../media";
import { useEditor } from "../../store";
import type { MusicRole } from "../capabilities";
+import { UserError } from "../../userError";
export function makeMusicRole(projectId: string, chatId?: string): MusicRole {
return {
@@ -23,7 +24,9 @@ export function makeMusicRole(projectId: string, chatId?: string): MusicRole {
prompt: input.mood,
parameters: { durationSeconds: Math.max(1, Math.round(input.durationSec)) },
});
- if (!res.ok) throw new Error("Music generation is unavailable.");
+ if (!res.ok) {
+ throw new UserError("music_unavailable", "Music generation is unavailable.");
+ }
const gen = (await res.json()) as {
status?: string;
outputs?: { dataBase64?: string; url?: string; contentType?: string; filename?: string }[];
@@ -36,13 +39,17 @@ export function makeMusicRole(projectId: string, chatId?: string): MusicRole {
});
} else if (out?.url) {
const dl = await fetch(out.url);
- if (!dl.ok) throw new Error("Could not download the music bed.");
+ if (!dl.ok) {
+ throw new UserError("music_bed_download_failed", "Could not download the music bed.");
+ }
file = new File([await dl.arrayBuffer()], "music.mp3", { type: out.contentType ?? "audio/mpeg" });
} else {
- throw new Error("The provider returned no music.");
+ throw new UserError("music_output_missing", "The provider returned no music.");
}
const asset = await importFileToProject(projectId, file);
- if (!asset) throw new Error("Could not import the music bed.");
+ if (!asset) {
+ throw new UserError("music_bed_import_failed", "Could not import the music bed.");
+ }
asset.name = "Music bed";
// Chat-owned from birth so the bed never surfaces in a panel; it's placed
// on the soundtrack as part of the run. Only the run's own thread id: the
diff --git a/site/src/cut/lib/genvideo/adapters/review.ts b/site/src/cut/lib/genvideo/adapters/review.ts
index 2c3ed071..6406a62e 100644
--- a/site/src/cut/lib/genvideo/adapters/review.ts
+++ b/site/src/cut/lib/genvideo/adapters/review.ts
@@ -17,6 +17,7 @@ import { hostedPost } from "../../hosted";
import { captureVideoFrames } from "../../visualFrames";
import { findRunAsset } from "../docWriter";
import { imagePart } from "./refImages";
+import { UserError } from "../../userError";
import type {
FrameCheckInput,
ReviewInput,
@@ -27,6 +28,7 @@ import type {
} from "../capabilities";
const MAX_FRAMES = 8;
+const reviewUnavailable = () => new UserError("review_model_unavailable", "The review model is unavailable.");
/** Aim for one frame every ~1s of take. */
const SECONDS_PER_FRAME = 1;
@@ -236,7 +238,9 @@ The benchmark sheet — the artist to match:`,
response_format: { type: "json_object" },
input: [{ role: "user", content }],
});
- if (!res.ok) throw new Error("The review model is unavailable.");
+ if (!res.ok) {
+ throw reviewUnavailable();
+ }
const body = (await res.json()) as { output_text?: string };
const parsed = JSON.parse(body.output_text ?? "{}") as Record<string, unknown>;
const ok = parsed.ok !== false;
@@ -280,7 +284,9 @@ The look: ${input.style || "(none)"}`,
response_format: { type: "json_object" },
input: [{ role: "user", content }],
});
- if (!res.ok) throw new Error("The review model is unavailable.");
+ if (!res.ok) {
+ throw reviewUnavailable();
+ }
const body = (await res.json()) as { output_text?: string };
const parsed = JSON.parse(body.output_text ?? "{}") as Record<string, unknown>;
const verdicts = Array.isArray(parsed.panels) ? parsed.panels : [];
@@ -303,10 +309,14 @@ The look: ${input.style || "(none)"}`,
// The take resolves wherever the run's project lives — store when open,
// persisted doc when the user switched away mid-render.
const asset = await findRunAsset(projectId, input.videoMediaId);
- if (!asset || asset.type !== "video") throw new Error("No take to review.");
+ if (!asset || asset.type !== "video") {
+ throw new UserError("review_take_missing", "No take to review.");
+ }
const clipSec = Math.max(0.1, asset.duration);
const frames = await captureVideoFrames(asset.url, frameTimes(clipSec));
- if (frames.length === 0) throw new Error("Could not sample the take.");
+ if (frames.length === 0) {
+ throw new UserError("review_take_unsampled", "Could not sample the take.");
+ }
// Each cast sheet rides both the main review and the identity check —
// resolve and encode it once per take, not once per use.
const sheetImages = new Map<string, Awaited<ReturnType<typeof imagePart>>>();
@@ -359,7 +369,9 @@ The timeline slot needs ${input.slotSec.toFixed(1)}s of this take.`,
text: { format: { type: "json_schema", schema: REVIEW_SCHEMA } },
input: [{ role: "user", content }],
});
- if (!res.ok) throw new Error("The review model is unavailable.");
+ if (!res.ok) {
+ throw reviewUnavailable();
+ }
const body = (await res.json()) as { output_text?: string };
// The reviewer CLASSIFIES what it sees, one field per rule — an easier
// ask than remembering to fail — and code adds the fields up. A reply
@@ -398,7 +410,9 @@ The canonical design sheet for "${sheet.name}":`,
text: { format: { type: "json_schema", schema: IDENTITY_SCHEMA } },
input: [{ role: "user", content: idContent }],
});
- if (!idRes.ok) throw new Error("The review model is unavailable.");
+ if (!idRes.ok) {
+ throw reviewUnavailable();
+ }
const idBody = (await idRes.json()) as { output_text?: string };
let idParsed: Record<string, unknown> | null = null;
try {
diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.ts
index 1915d44b..be7397ae 100644
--- a/site/src/cut/lib/genvideo/adapters/text.ts
+++ b/site/src/cut/lib/genvideo/adapters/text.ts
@@ -16,7 +16,8 @@
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
import { hostedPost } from "../../hosted";
-import { NO_CREDITS_MESSAGE } from "../../credits";
+import { NoCreditsError } from "../../hostedError";
+import { UserError } from "../../userError";
import { secToFrame, type RawShot } from "../coverage";
import { wordsInRange, type BreakdownRole, type ScriptRole, type StyleRole } from "../capabilities";
import { refImageParts, type InlineImagePart } from "./refImages";
@@ -39,7 +40,8 @@ async function llmJson<T>(
parse: (o: Record<string, unknown>) => T | null,
images: InlineImagePart[] = []
): Promise<T> {
- let lastError = new Error("The planning model is unavailable — try again.");
+ const unavailable = () => new UserError("planning_model_unavailable", "The planning model is unavailable — try again.");
+ let lastError: Error = unavailable();
for (const delay of LLM_RETRY_DELAYS_MS) {
if (delay > 0) await new Promise((r) => setTimeout(r, delay));
let res: Response;
@@ -63,10 +65,14 @@ async function llmJson<T>(
continue; // network blip — retry
}
if (!res.ok) {
- if (res.status === 402) throw new Error(NO_CREDITS_MESSAGE);
- if (res.status === 401) throw new Error("Sign in to Donkey to generate a video.");
+ if (res.status === 402) {
+ throw new NoCreditsError();
+ }
+ if (res.status === 401) {
+ throw new UserError("sign_in_to_generate_video", "Sign in to Donkey to generate a video.");
+ }
const reason = await providerReason(res);
- lastError = new Error(reason ?? "The planning model is unavailable — try again.");
+ lastError = reason ? new Error(reason) : unavailable();
// Any other 4xx is deterministic — the same request fails the same way —
// so surface the reason now instead of burning the retry envelope on it.
if (res.status < 500 && res.status !== 408 && res.status !== 429) throw lastError;
@@ -77,12 +83,12 @@ async function llmJson<T>(
try {
parsed = JSON.parse(body.output_text ?? "") as Record<string, unknown>;
} catch {
- lastError = new Error("The planning model returned unreadable output.");
+ lastError = new UserError("planning_output_unreadable", "The planning model returned unreadable output.");
continue;
}
const out = parse(parsed);
if (out === null) {
- lastError = new Error("The planning model returned an unusable plan.");
+ lastError = new UserError("planning_plan_unusable", "The planning model returned an unusable plan.");
continue;
}
return out;
diff --git a/site/src/cut/lib/genvideo/adapters/transcribe.ts b/site/src/cut/lib/genvideo/adapters/transcribe.ts
index 5e8da31e..f8d99816 100644
--- a/site/src/cut/lib/genvideo/adapters/transcribe.ts
+++ b/site/src/cut/lib/genvideo/adapters/transcribe.ts
@@ -17,13 +17,16 @@ import { runTranscription, useEditor } from "../../store";
import { trackLocale } from "../../subtitles";
import type { TranscribeRole } from "../capabilities";
import type { TranscriptWord } from "../types";
+import { UserError } from "../../userError";
export function makeTranscribeRole(projectId: string): TranscribeRole {
return {
async transcribe(audioMediaId) {
const state = useEditor.getState();
const asset = state.assets.find((a) => a.id === audioMediaId);
- if (!asset || asset.type !== "audio") throw new Error("No audio to transcribe.");
+ if (!asset || asset.type !== "audio") {
+ throw new UserError("transcribe_audio_missing", "No audio to transcribe.");
+ }
const cues = await runTranscription(projectId, {
duration: asset.duration,
// The recognizer's language: a voiceover stamped what it speaks at
@@ -37,7 +40,9 @@ export function makeTranscribeRole(projectId: string): TranscribeRole {
// The poller yields null when the project closed mid-run. That is a
// pause, never a result — an empty transcript here would silently plan
// shots with no relation to the narration's words.
- if (cues === null) throw new Error("Transcription stopped — the project was closed.");
+ if (cues === null) {
+ throw new UserError("transcribe_project_closed", "Transcription stopped — the project was closed.");
+ }
return cues.flatMap<TranscriptWord>((c) => c.words ?? []);
},
};
diff --git a/site/src/cut/lib/genvideo/docWriter.ts b/site/src/cut/lib/genvideo/docWriter.ts
index 364499cd..01bcb2af 100644
--- a/site/src/cut/lib/genvideo/docWriter.ts
+++ b/site/src/cut/lib/genvideo/docWriter.ts
@@ -21,6 +21,7 @@ import { storedMediaUrl } from "../mediaSync";
import { projectBackend } from "../residency";
import { footprints, nextFreeStart, placeInRun, RENDERS_CAP, storedAssets, useEditor } from "../store";
import { SPEED_MIN } from "../types";
+import { UserError, errorFromBody } from "../userError";
import type { AudioClip, MediaAsset, ProjectDoc, RenderRecord, VideoClip } from "../types";
import { fillSlot } from "./fillSlot";
@@ -43,14 +44,18 @@ export function withProjectDoc(
const owner = backend ?? await projectBackend(projectId);
const res = await owner.fetch(`/api/cut/projects/${projectId}`);
const doc = await apiJson<ProjectDoc>(res);
- if (!res.ok) throw new Error(doc?.error ?? "Could not read the project.");
+ if (!res.ok) {
+ throw errorFromBody(doc, new UserError("project_read_failed", "Could not read the project."));
+ }
mutate(doc);
const put = await owner.fetch(`/api/cut/projects/${projectId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(doc),
});
- if (!put.ok) throw new Error("Could not save the project in the background.");
+ if (!put.ok) {
+ throw new UserError("project_background_save_failed", "Could not save the project in the background.");
+ }
});
chains.set(projectId, next.catch(() => {}));
return next;
diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.ts
index 157f603e..a47b2c00 100644
--- a/site/src/cut/lib/genvideo/editorBridge.ts
+++ b/site/src/cut/lib/genvideo/editorBridge.ts
@@ -29,6 +29,7 @@ import { useEditor } from "../store";
import { nearestAspect, TRANSITION_STYLE_IDS, type TransitionStyle } from "../types";
import { defaultVideoAspects } from "../videoModels";
import { docPlaceGenAudio, docPlaceGenClip, projectWriteMode, withProjectDoc } from "./docWriter";
+import { UserError } from "../userError";
import type { AudioClipInfo, EditorBridge, TimelineInfo } from "./editor";
/** The rate the plan runs at. Fixed to the export frame rate so a shot's frame
@@ -107,14 +108,18 @@ export class StoreEditorBridge implements EditorBridge {
): Promise<string> {
if ((await this.mode()) === "store" && this.open()) {
const id = useEditor.getState().placeGenClip(mediaId, toSec(startFrame), toSec(endFrame), opts);
- if (!id) throw new Error(`placeClip: no placeable asset ${mediaId}`);
+ if (!id) {
+ throw new UserError("scene_clip_unplaceable", `placeClip: no placeable asset ${mediaId}`, { id: mediaId });
+ }
return id;
}
let placed: string | null = null;
await withProjectDoc(this.projectId, (doc) => {
placed = docPlaceGenClip(doc, mediaId, toSec(startFrame), toSec(endFrame), opts);
});
- if (!placed) throw new Error(`placeClip: no placeable asset ${mediaId}`);
+ if (!placed) {
+ throw new UserError("scene_clip_unplaceable", `placeClip: no placeable asset ${mediaId}`, { id: mediaId });
+ }
return placed;
}
@@ -184,14 +189,18 @@ export class StoreEditorBridge implements EditorBridge {
const id = useEditor
.getState()
.placeGenAudio(mediaId, toSec(startFrame), toSec(durationFrames), audioOpts);
- if (!id) throw new Error(`placeAudio: no audio asset ${mediaId}`);
+ if (!id) {
+ throw new UserError("scene_audio_unplaceable", `placeAudio: no audio asset ${mediaId}`, { id: mediaId });
+ }
return id;
}
let placed: string | null = null;
await withProjectDoc(this.projectId, (doc) => {
placed = docPlaceGenAudio(doc, mediaId, toSec(startFrame), toSec(durationFrames), audioOpts);
});
- if (!placed) throw new Error(`placeAudio: no audio asset ${mediaId}`);
+ if (!placed) {
+ throw new UserError("scene_audio_unplaceable", `placeAudio: no audio asset ${mediaId}`, { id: mediaId });
+ }
return placed;
}
diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.ts
index 50ed5daf..7c63104e 100644
--- a/site/src/cut/lib/genvideo/orchestrator.ts
+++ b/site/src/cut/lib/genvideo/orchestrator.ts
@@ -32,6 +32,7 @@ import { buildNegative, buildPrompt, buildRefPrompt, refsForAsset, shotRefs, sty
import { segmentByDuration, type ModelSuite, type ReviewVerdict } from "./capabilities";
import type { EditorBridge } from "./editor";
import type { BeatVoice, RefAsset, ScriptBeat, Shot, TranscriptWord, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";
+import { UserError, errorFields } from "../userError";
export interface OrchestratorDeps {
editor: EditorBridge;
@@ -56,6 +57,8 @@ const BACKOFF_MS = 500;
// narration rather than competing with it (a generated scene has no separate
// voice track to duck the music beneath).
const MUSIC_BED_VOLUME = 0.4;
+/** A shot's failure fields, cleared: the error and its catalog code go together. */
+const NO_ERROR = { error: undefined, errorCode: undefined, errorParams: undefined } as const;
export class VideoOrchestrator {
/** Serializes persistence so concurrent shot updates never interleave writes. */
@@ -441,7 +444,7 @@ export class VideoOrchestrator {
// Set per attempt, not once: a declined review leaves the shot in
// "reviewing", and the retake that follows must show as rendering (this
// is also what fires the "retake N…" ticker line).
- this.updateShot(shot, { status: "generating", error: undefined });
+ this.updateShot(shot, { status: "generating", ...NO_ERROR });
const prompt = critique ? `${basePrompt} Note from the last take's review: ${critique}` : basePrompt;
const video = this.deps.suite.video;
try {
@@ -465,7 +468,7 @@ export class VideoOrchestrator {
}
shot.startKeyframe = shot.startKeyframe ?? prior.start;
await this.save();
- this.updateShot(shot, { status: "generating", error: undefined });
+ this.updateShot(shot, { status: "generating", ...NO_ERROR });
}
const take = await video.generate({
prompt,
@@ -516,7 +519,7 @@ export class VideoOrchestrator {
// so those re-mint too, with the critique.
remintSeed = !verdict.offModel || !take.anchored;
if (verdict.offModel && !take.anchored) unanchoredMisses++;
- throw new Error(`Retake: ${critique}`);
+ throw new UserError("shot_retake", `Retake: ${critique}`, { note: critique });
}
srcInSec = verdict.fromSec;
}
@@ -532,11 +535,11 @@ export class VideoOrchestrator {
muted: this.project.audioMode === "provided",
...this.placementAnchors(shot),
});
- this.updateShot(shot, { status: "placed", error: undefined });
+ this.updateShot(shot, { status: "placed", ...NO_ERROR });
this.emitProgress();
return;
} catch (e) {
- shot.error = String(e instanceof Error ? e.message : e);
+ Object.assign(shot, NO_ERROR, errorFields(e, String(e)));
if (attempt < VIDEO_ATTEMPTS) await this.sleep(BACKOFF_MS * attempt);
}
}
@@ -602,7 +605,12 @@ export class VideoOrchestrator {
shot.timelineClipId = await this.deps.editor.placeClip(still, shot.startFrame, shot.endFrame, this.placementAnchors(shot));
} else {
// Nothing to hold — keep whatever was there rather than opening a hole.
- this.deps.emit({ type: "error", message: `Shot ${shot.id} could not be generated or filled.` });
+ this.deps.emit({
+ type: "error",
+ message: `Shot ${shot.id} could not be generated or filled.`,
+ errorCode: "shot_unfilled",
+ errorParams: { shot: shot.id },
+ });
}
this.updateShot(shot, { status: "failed" });
}
@@ -729,7 +737,7 @@ export class VideoOrchestrator {
// fails. The beat voice is untouched, so narration never restacks.
shot.startKeyframe = undefined;
shot.lipSynced = false;
- shot.error = undefined;
+ Object.assign(shot, NO_ERROR);
shot.status = "pending";
mutate?.(shot);
targets.push(shot);
@@ -791,7 +799,9 @@ export class VideoOrchestrator {
const list = this.project.shots;
const first = list.findIndex((s) => s.id === ids[0]);
const last = list.findIndex((s) => s.id === ids[ids.length - 1]);
- if (first < 0 || last < first) throw new Error("Those shots are not in this scene.");
+ if (first < 0 || last < first) {
+ throw new UserError("scene_shots_missing", "Those shots are not in this scene.");
+ }
const span = list.slice(first, last + 1);
const startFrame = span[0].startFrame;
const endFrame = span[span.length - 1].endFrame;
diff --git a/site/src/cut/lib/genvideo/sceneOwnership.ts b/site/src/cut/lib/genvideo/sceneOwnership.ts
index 3b4092cf..7f1ab81b 100644
--- a/site/src/cut/lib/genvideo/sceneOwnership.ts
+++ b/site/src/cut/lib/genvideo/sceneOwnership.ts
@@ -7,6 +7,7 @@ import type { ProjectDoc } from "../types";
import { docWriterIdle } from "./docWriter";
import { VideoOrchestrator } from "./orchestrator";
import { SceneOwnedElsewhere, withSceneLease } from "./sceneLease";
+import { UserError } from "../userError";
export { SceneOwnedElsewhere } from "./sceneLease";
/** Every entry into a scene takes the project's lease, including reload recovery. */
@@ -22,7 +23,9 @@ export function ownScene(projectId: string, scene: VideoOrchestrator, fresh = fa
let leaseMs = CHAT_RUNTIME.sceneLeaseMs;
const lease = async (release = false) => {
const res = await backend.fetch(route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ owner, release, leaseMs: CHAT_RUNTIME.sceneLeaseMs }) });
- if (!res.ok) throw new Error("Could not reserve the video run.");
+ if (!res.ok) {
+ throw new UserError("scene_lease_failed", "Could not reserve the video run.");
+ }
const result = await res.json() as { acquired: boolean; leaseMs?: number };
if (result.leaseMs) leaseMs = result.leaseMs;
return result.acquired;
@@ -31,13 +34,19 @@ export function ownScene(projectId: string, scene: VideoOrchestrator, fresh = fa
await flushEditorSave(projectId);
await docWriterIdle(projectId);
const res = await backend.fetch(`/api/cut/projects/${encodeURIComponent(projectId)}`, { observe: true });
- if (!res.ok) throw new Error("Could not read the video run.");
+ if (!res.ok) {
+ throw new UserError("scene_read_failed", "Could not read the video run.");
+ }
const doc = await res.json() as ProjectDoc;
const current = useEditor.getState();
const revision = res.headers.get("x-cut-doc-version");
if (backend.kind === "cloud" && current.projectId === projectId && current.loaded &&
- revision && projectRevision(projectId) !== revision)
- throw new Error("The project changed in another tab. Reload it before continuing the video run.");
+ revision && projectRevision(projectId) !== revision) {
+ throw new UserError(
+ "scene_project_changed",
+ "The project changed in another tab. Reload it before continuing the video run.",
+ );
+ }
if (!fresh && doc.genvideo?.id !== scene.project.id) {
scene.abort();
return scene.project;
@@ -55,7 +64,9 @@ export function ownScene(projectId: string, scene: VideoOrchestrator, fresh = fa
return result;
};
if (backend.kind === "browser") {
- if (typeof navigator === "undefined" || !navigator.locks) throw new Error("This browser cannot coordinate background video runs.");
+ if (typeof navigator === "undefined" || !navigator.locks) {
+ throw new UserError("scene_locks_unavailable", "This browser cannot coordinate background video runs.");
+ }
return await navigator.locks.request(`cut-scene:${projectId}`, { ifAvailable: true }, async (lock) => {
if (!lock) throw new SceneOwnedElsewhere();
return execute();
diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.ts
index ab63c91c..4e577f26 100644
--- a/site/src/cut/lib/genvideo/types.ts
+++ b/site/src/cut/lib/genvideo/types.ts
@@ -19,6 +19,8 @@
* construction. Seconds appear only at the editor boundary (see coverage.ts).
*/
+import type { UserErrorParams } from "../userError";
+
/** A reference the user brought, passed to generation as media not text. */
export interface RefAsset {
mediaId: string;
@@ -108,6 +110,8 @@ export interface Shot {
attempts: number;
lastPrompt?: string;
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
}
/** One beat's frame span — the beat→timeline map a re-cut reads to synthesize
@@ -215,6 +219,6 @@ export type VideoEvent =
| { type: "asset"; label: string; mediaId: string; key?: string }
/** The live ticker: one line on what the run is doing right now. */
| { type: "activity"; message: string; key?: string }
- | { type: "error"; message: string };
+ | { type: "error"; message: string; errorCode?: string; errorParams?: UserErrorParams };
export type VideoEmit = (event: VideoEvent) => void;
diff --git a/site/src/cut/lib/groupEdit.test.ts b/site/src/cut/lib/groupEdit.test.ts
index bd05fbaa..4505f6f6 100644
--- a/site/src/cut/lib/groupEdit.test.ts
+++ b/site/src/cut/lib/groupEdit.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { selectionCenter, selectionSummary, selectionTranslation, sharedNumber, sharedValue } from "./groupEdit";
+import { selectionCenter, selectionCounts, selectionTranslation, sharedNumber, sharedValue } from "./groupEdit";
import type { Overlay } from "./types";
describe("groupEdit", () => {
@@ -39,6 +39,6 @@ describe("groupEdit", () => {
const overlays = [
{ kind: "shape" } as Overlay, { kind: "shape" } as Overlay, { text: "hi" } as Overlay,
];
- expect(selectionSummary({ overlays, clips: [], audios: [] })).toBe("2 shapes · 1 title");
+ expect(selectionCounts({ overlays, clips: [], audios: [] })).toEqual([["shape", 2], ["title", 1]]);
});
});
diff --git a/site/src/cut/lib/groupEdit.ts b/site/src/cut/lib/groupEdit.ts
index 91bc7a62..f827ba3c 100644
--- a/site/src/cut/lib/groupEdit.ts
+++ b/site/src/cut/lib/groupEdit.ts
@@ -50,12 +50,16 @@ export function selectionTranslation(
return { dx, dy };
}
-/** "5 shapes · 4 titles": what a selection holds, by kind, in selection order. */
-export function selectionSummary(items: { overlays: readonly Overlay[]; clips: readonly VideoClip[]; audios: readonly AudioClip[] }): string {
- const counts = new Map<string, number>();
- const bump = (name: string) => counts.set(name, (counts.get(name) ?? 0) + 1);
+/** A kind of item a selection counts. */
+export type SelectionKind = "clip" | "title" | "shape" | "effect" | "sticker" | "audio";
+
+/** What a selection holds, by kind, in selection order — [["shape", 5],
+ * ["title", 4]] — for the panel to word as "5 shapes · 4 titles". */
+export function selectionCounts(items: { overlays: readonly Overlay[]; clips: readonly VideoClip[]; audios: readonly AudioClip[] }): [SelectionKind, number][] {
+ const counts = new Map<SelectionKind, number>();
+ const bump = (kind: SelectionKind) => counts.set(kind, (counts.get(kind) ?? 0) + 1);
for (let i = 0; i < items.clips.length; i++) bump("clip");
for (const o of items.overlays) bump(isTextOverlay(o) ? "title" : isShapeOverlay(o) ? "shape" : isEffectOverlay(o) ? "effect" : "sticker");
- for (let i = 0; i < items.audios.length; i++) bump("audio clip");
- return [...counts].map(([name, n]) => `${n} ${name}${n === 1 ? "" : "s"}`).join(" · ");
+ for (let i = 0; i < items.audios.length; i++) bump("audio");
+ return [...counts];
}
diff --git a/site/src/cut/lib/guides.ts b/site/src/cut/lib/guides.ts
index 7d161d8f..4306f610 100644
--- a/site/src/cut/lib/guides.ts
+++ b/site/src/cut/lib/guides.ts
@@ -17,6 +17,10 @@ export interface GuideLines {
h: number[];
}
+/** Which part of a platform's UI a keep-out box covers; the preview names
+ * it in the page's language. */
+export type GuideRegion = "topBar" | "cropped" | "actions" | "caption";
+
/** A region the platform's own UI covers, as frame fractions. */
export interface GuideBox {
x: number;
@@ -24,6 +28,7 @@ export interface GuideBox {
w: number;
h: number;
label: string;
+ region: GuideRegion;
}
/** Lines (frame fractions along one axis) and keep-out boxes to draw. The
@@ -94,11 +99,11 @@ export const GUIDE_PRESETS: readonly GuidePreset[] = [
v: [],
h: [],
boxes: [
- { x: 0, y: 0, w: 1, h: phone(215, 1920), label: "Top bar" },
- { x: 0, y: 0, w: phone(50, 1080), h: 1, label: "Cropped" },
- { x: 1 - phone(50, 1080), y: 0, w: phone(50, 1080), h: 1, label: "Cropped" },
- { x: phone(895, 1080), y: phone(730, 1920), w: phone(185, 1080), h: phone(730, 1920), label: "Actions" },
- { x: 0, y: phone(1460, 1920), w: 1, h: phone(460, 1920), label: "Caption · music · nav" },
+ { x: 0, y: 0, w: 1, h: phone(215, 1920), label: "Top bar", region: "topBar" },
+ { x: 0, y: 0, w: phone(50, 1080), h: 1, label: "Cropped", region: "cropped" },
+ { x: 1 - phone(50, 1080), y: 0, w: phone(50, 1080), h: 1, label: "Cropped", region: "cropped" },
+ { x: phone(895, 1080), y: phone(730, 1920), w: phone(185, 1080), h: phone(730, 1920), label: "Actions", region: "actions" },
+ { x: 0, y: phone(1460, 1920), w: 1, h: phone(460, 1920), label: "Caption · music · nav", region: "caption" },
],
},
},
diff --git a/site/src/cut/lib/hostedError.test.ts b/site/src/cut/lib/hostedError.test.ts
index b48cad12..52d8fb84 100644
--- a/site/src/cut/lib/hostedError.test.ts
+++ b/site/src/cut/lib/hostedError.test.ts
@@ -1,30 +1,34 @@
import { describe, expect, test } from "bun:test";
import { NO_CREDITS_MESSAGE } from "./credits";
-import { readHostedError } from "./hostedError";
+import { readHostedFailure } from "./hostedError";
+import { UserError } from "./userError";
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status });
+const signIn = new UserError("sign_in", "Sign in.");
+const failed = new UserError("failed", "Failed.");
+const read = async (res: Response) => (await readHostedFailure(res, signIn, failed)).message;
-describe("readHostedError", () => {
+describe("readHostedFailure", () => {
test("401 asks to sign in and 402 says the credits line", async () => {
- expect(await readHostedError(json(401, { message: "x" }), "Sign in.", "Failed.")).toBe("Sign in.");
- expect(await readHostedError(json(402, { message: "x" }), "Sign in.", "Failed.")).toBe(NO_CREDITS_MESSAGE);
+ expect(await readHostedFailure(json(401, { message: "x" }), signIn, failed)).toBe(signIn);
+ const wall = await readHostedFailure(json(402, { message: "x" }), signIn, failed);
+ expect(wall.message).toBe(NO_CREDITS_MESSAGE);
+ expect((wall as UserError).code).toBe("credits_insufficient");
});
test("the provider's reason joins the headline", async () => {
const res = json(502, { message: "Generation failed.", details: { message: "Prompt was filtered." } });
- expect(await readHostedError(res, "Sign in.", "Failed.")).toBe("Generation failed. (Prompt was filtered.)");
- expect(await readHostedError(json(502, { details: { message: "Rate limited." } }), "Sign in.", "Failed.")).toBe(
- "Rate limited.",
- );
+ expect(await read(res)).toBe("Generation failed. (Prompt was filtered.)");
+ expect(await read(json(502, { details: { message: "Rate limited." } }))).toBe("Rate limited.");
});
test("a rejected request names its first bad field before the generic error", async () => {
const res = json(400, { error: "Invalid request", issues: [{ path: "claims.0", message: "Too long" }] });
- expect(await readHostedError(res, "Sign in.", "Failed.")).toBe("claims.0: Too long");
+ expect(await read(res)).toBe("claims.0: Too long");
});
test("an unreadable body falls back", async () => {
- expect(await readHostedError(new Response("oops", { status: 500 }), "Sign in.", "Failed.")).toBe("Failed.");
+ expect(await readHostedFailure(new Response("oops", { status: 500 }), signIn, failed)).toBe(failed);
});
});
diff --git a/site/src/cut/lib/hostedError.ts b/site/src/cut/lib/hostedError.ts
index 200bc850..25600e58 100644
--- a/site/src/cut/lib/hostedError.ts
+++ b/site/src/cut/lib/hostedError.ts
@@ -1,6 +1,7 @@
import { NO_CREDITS_MESSAGE } from "./credits";
+import { UserError } from "./userError";
-// The message a failed hosted call shows: sign in on 401, the credits line on
+// The failure a failed hosted call throws: sign in on 401, the credits line on
// 402, otherwise the route's own words. The provider's reason (a filtered
// prompt, a rate limit) rides under `details.message` and joins the headline;
// a rejected request names its first bad field.
@@ -17,14 +18,23 @@ interface ErrorBody {
const text = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined);
-/** The error line for a hosted response that came back not ok. `signIn` is
- * what a signed-out caller reads, e.g. "Sign in to Donkey to check facts." */
-export async function readHostedError(res: Response, signIn: string, fallback: string): Promise<string> {
+/** The account balance can't cover the generation — callers surface a link to
+ * buy credits alongside the message. */
+export class NoCreditsError extends UserError {
+ constructor() {
+ super("credits_insufficient", NO_CREDITS_MESSAGE);
+ }
+}
+
+/** The failure for a hosted response that came back not ok. `signIn` is what
+ * a signed-out caller reads, e.g. "Sign in to Donkey to check facts." A body
+ * with words of its own answers with them, as a plain Error. */
+export async function readHostedFailure(res: Response, signIn: UserError, fallback: UserError): Promise<Error> {
if (res.status === UNAUTHORIZED) {
return signIn;
}
if (res.status === PAYMENT_REQUIRED) {
- return NO_CREDITS_MESSAGE;
+ return new NoCreditsError();
}
const body = (await res.json().catch(() => null)) as ErrorBody | null;
@@ -33,7 +43,7 @@ export async function readHostedError(res: Response, signIn: string, fallback: s
const message = text(body?.message) ?? issueText ?? text(body?.error);
const detail = text(body?.details?.message);
if (detail && detail !== message) {
- return message ? `${message} (${detail})` : detail;
+ return new Error(message ? `${message} (${detail})` : detail);
}
- return message ?? fallback;
+ return message ? new Error(message) : fallback;
}
diff --git a/site/src/cut/lib/importQueue.test.ts b/site/src/cut/lib/importQueue.test.ts
index d78b98aa..5e856e5d 100644
--- a/site/src/cut/lib/importQueue.test.ts
+++ b/site/src/cut/lib/importQueue.test.ts
@@ -21,7 +21,7 @@ test("an upload the connection dropped picks back up when the connection returns
localUrl: "blob:take",
send: async () => {
sends++;
- if (sends === 1) throw new ConnectionLostError("Upload failed.");
+ if (sends === 1) throw new ConnectionLostError("upload_failed", "Upload failed.");
return "take.mov";
},
};
diff --git a/site/src/cut/lib/importQueue.ts b/site/src/cut/lib/importQueue.ts
index d96911fa..d06429f8 100644
--- a/site/src/cut/lib/importQueue.ts
+++ b/site/src/cut/lib/importQueue.ts
@@ -25,6 +25,7 @@ import { storedMediaUrl } from "./mediaSync";
import { CUT_UPLOADS } from "./chatRuntime";
import { connectionLost, isOffline, onReconnect } from "./network";
import { useEditor } from "./store";
+import { errorFields, UserError, type ErrorFields } from "./userError";
/** Blob URLs owned by the browser store's registry stay alive for the whole
* session; only tab-scoped object URLs are this queue's to revoke. */
@@ -163,11 +164,11 @@ export function markUploadStored(assetId: string, fileName: string) {
* demote a store-backed asset to tab-scoped (which would strip it from the
* saved document), and `server` so the indicator keeps calling a copy a copy.
* `updateAsset` merges shallowly; `upload` is replaced whole. */
-function uploadPatch(job: Job, progress: number, error?: string) {
+function uploadPatch(job: Job, progress: number, failure?: ErrorFields) {
return {
upload: {
progress,
- ...(error !== undefined ? { error } : {}),
+ ...failure,
...(storeBacked(job) ? { stored: true as const } : {}),
...(job.pending.asset.upload?.server ? { server: true as const } : {}),
},
@@ -304,7 +305,7 @@ async function run(job: Job) {
if (!wanted(job)) return storeBacked(job) ? stopStored(job) : cancelUpload(asset.id);
useEditor.getState().updateAsset(
asset.id,
- uploadPatch(job, 0, err instanceof Error ? err.message : "Upload failed.")
+ uploadPatch(job, 0, errorFields(err, new UserError("upload_failed", "Upload failed.")))
);
if (connectionLost(err)) {
scheduleResume(job);
diff --git a/site/src/cut/lib/interfaceLanguage.ts b/site/src/cut/lib/interfaceLanguage.ts
new file mode 100644
index 00000000..d6e71509
--- /dev/null
+++ b/site/src/cut/lib/interfaceLanguage.ts
@@ -0,0 +1,49 @@
+import type { Locale } from "@/i18n/locales";
+
+import { cloudRequest } from "./backend/cloud";
+import { chatOwner } from "./chatAssets";
+
+// The interface language as a tool target. In the editor, the chat session
+// that runs the turn takes the change: it saves the account's language and
+// reloads the page in it once the reply finishes, so the reload never cuts a
+// turn short. A session with no editor page (a cloud worker turn, a ChatGPT
+// command batch) saves the account's language on the hosted site, and the
+// editor opens in it the next time it loads.
+
+const ACCOUNT_LOCALE_PATH = "/api/cut-cloud/account/locale";
+
+/** Where a language change landed, for the tool's result. */
+export type LanguageChange = "page" | "account";
+
+const sinks = new Map<string, (locale: Locale) => void>();
+
+/** Register the mounted session's switch for its thread; returns the release. */
+export function registerLanguageSink(threadId: string, sink: (locale: Locale) => void): () => void {
+ sinks.set(threadId, sink);
+ return () => {
+ if (sinks.get(threadId) === sink) {
+ sinks.delete(threadId);
+ }
+ };
+}
+
+/** Change the interface language for the streaming turn's person. */
+export async function changeInterfaceLanguage(locale: Locale): Promise<LanguageChange> {
+ // The editor page: its session saves and reloads after the reply.
+ const sink = sinks.get(chatOwner() ?? "");
+ if (sink) {
+ sink(locale);
+ return "page";
+ }
+
+ // No page: the account keeps the choice for the next load.
+ const res = await cloudRequest(ACCOUNT_LOCALE_PATH, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ locale }),
+ });
+ if (!res.ok) {
+ throw new Error(`Could not save the account's language (${res.status}).`);
+ }
+ return "account";
+}
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 6b9f92f8..b6a66d0c 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -38,6 +38,7 @@ import {
} from "./residency";
import { probeMediaFile } from "./mediaRead";
import { storedMediaUrl } from "./mediaSync";
+import { UserError, errorFromBody, replyError } from "./userError";
import { reportSwallowed } from "./report";
import { useEditor } from "./store";
import { playheadAt } from "./playhead";
@@ -241,7 +242,7 @@ export function downloadLibraryAsset(
async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {
const res = await backendFor(r).fetch("/api/cut/library");
- if (!res.ok) throw new Error("Could not load the library.");
+ if (!res.ok) throw new UserError("library_load_failed", "Could not load the library.");
const data = (await res.json()) as LibraryData;
const shelf: LibraryData = {
assets: (data.assets ?? []).map((a) => ({ ...a, residency: r })),
@@ -309,7 +310,7 @@ export async function fetchLibrary(opts?: {
),
);
const got = parts.filter((p): p is LibraryData => p !== null);
- if (got.length === 0) throw new Error("Could not load the library.");
+ if (got.length === 0) throw new UserError("library_load_failed", "Could not load the library.");
const byNewest = <T extends { addedAt: number }>(items: T[]) =>
[...items].sort((a, b) => b.addedAt - a.addedAt);
return {
@@ -362,11 +363,11 @@ export async function importUrlToLibrary(
if (backend.kind === "cloud") {
const started = await apiJson<{ jobId?: string }>(res);
if (!res.ok || !started.jobId)
- throw new Error(started.error ?? "Could not import that URL.");
+ throw replyError(res.status, started, new UserError("url_import_failed", "Could not import that URL."));
const done = await pollCloudJob<{ assets?: LibraryAsset[] }>(
started.jobId,
backend,
- "Could not import that URL.",
+ new UserError("url_import_failed", "Could not import that URL."),
{
onState: (state) =>
onStage?.(state === "queued" ? "queued" : "downloading"),
@@ -375,7 +376,7 @@ export async function importUrlToLibrary(
// The library holds media, so a source that turned out to be only words
// fails here — the same line the engine's library import draws.
if (!done.assets?.length)
- throw new Error("That link has no media to import.");
+ throw new UserError("link_no_media", "That link has no media to import.");
return done.assets.map((a) => ({ ...a, residency }));
}
const body = await apiJson<LibraryAsset[]>(res);
@@ -387,11 +388,11 @@ export async function importUrlToLibrary(
// one, so the link gets a second chance there and the bytes come back down
// to this Mac. The engine's own reason stands if that side can't do it
// either: it is the shelf the user was importing to.
- const reason = body.error ?? "Could not import that URL.";
+ const reason = replyError(res.status, body, new UserError("url_import_failed", "Could not import that URL."));
try {
return await importUrlThroughCloud(url, residency, onStage, key);
} catch {
- throw new Error(reason);
+ throw reason;
}
}
@@ -422,11 +423,11 @@ async function importUrlThroughCloud(
});
const started = await apiJson<{ jobId?: string }>(res);
if (!res.ok || !started.jobId)
- throw new Error(started.error ?? "Could not import that URL.");
+ throw replyError(res.status, started, new UserError("url_import_failed", "Could not import that URL."));
const done = await pollCloudJob<{ assets?: LibraryAsset[] }>(
started.jobId,
cloudBackend,
- "Could not import that URL.",
+ new UserError("url_import_failed", "Could not import that URL."),
{
onState: (state) =>
onStage?.(state === "queued" ? "queued" : "downloading"),
@@ -435,7 +436,7 @@ async function importUrlThroughCloud(
// The library holds media, so a source that turned out to be only words
// fails here — the same line the engine's library import draws.
if (!done.assets?.length)
- throw new Error("That link has no media to import.");
+ throw new UserError("link_no_media", "That link has no media to import.");
const landed: LibraryAsset[] = [];
onStage?.("saving");
try {
@@ -446,7 +447,7 @@ async function importUrlThroughCloud(
// A page resuming this key after its earlier run landed the media
// finds the staged copy already dropped: the shelf holds it.
if (bytes.status === STAGED_GONE && landed.length === 0) return [];
- if (!bytes.ok) throw new Error("Could not import that URL.");
+ if (!bytes.ok) throw new UserError("url_import_failed", "Could not import that URL.");
const form = new FormData();
form.append("file", await bytes.blob(), staged.fileName);
form.append("name", staged.name);
@@ -473,7 +474,7 @@ async function importUrlThroughCloud(
});
const body = await apiJson<LibraryAsset>(saved);
if (!saved.ok)
- throw new Error(body.error ?? "Could not import that URL.");
+ throw replyError(saved.status, body, new UserError("url_import_failed", "Could not import that URL."));
landed.push({ ...body, residency: target });
}
} catch (e) {
@@ -505,7 +506,7 @@ export async function createLibraryFolder(
body: JSON.stringify({ name, parentId }),
});
const body = await apiJson<LibraryFolder>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not create folder.");
+ if (!res.ok) throw errorFromBody(body, new UserError("folder_create_failed", "Could not create folder."));
return { ...body, residency };
}
@@ -525,7 +526,7 @@ export async function updateLibraryFolder(
body: JSON.stringify(patch),
},
);
- if (!res.ok) throw new Error("Could not update folder.");
+ if (!res.ok) throw new UserError("folder_update_failed", "Could not update folder.");
return { ...((await res.json()) as Omit<LibraryFolder, "residency">), residency };
}
@@ -556,7 +557,7 @@ export async function deleteLibraryFolder(
let tree: string[] = [];
if (residency !== "cloud") {
const listing = await backendFor(residency).fetch("/api/cut/library");
- if (!listing.ok) throw new Error("Could not read the folder.");
+ if (!listing.ok) throw new UserError("folder_read_failed", "Could not read the folder.");
tree = subtreeOf((await listing.json() as LibraryData).folders, id);
}
const res = await backendFor(residency).fetch(
@@ -565,7 +566,7 @@ export async function deleteLibraryFolder(
method: "DELETE",
},
);
- if (!res.ok) throw new Error("Could not delete folder.");
+ if (!res.ok) throw new UserError("folder_delete_failed", "Could not delete folder.");
if (residency !== "cloud") {
const { deleteLibraryFolderNotes } = await import("@/cut/lib/notes");
await deleteLibraryFolderNotes(residency, tree);
@@ -585,7 +586,7 @@ export async function moveLibraryItem(
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, folderId }),
});
- if (!res.ok) throw new Error("Could not move item.");
+ if (!res.ok) throw new UserError("library_item_move_failed", "Could not move item.");
}
/**
@@ -604,7 +605,7 @@ export async function carryAssetTo(
const res = await backendFor(asset.residency).fetch(
`/api/cut/library/media/${encodeURIComponent(asset.fileName)}`,
);
- if (!res.ok) throw new Error("Could not read that file off its shelf.");
+ if (!res.ok) throw new UserError("library_shelf_read_failed", "Could not read that file off its shelf.");
// A font's cover is baked from its bytes on the way in, so the shelf it
// lands on draws its own — always the current sheet. A LUT has none.
const from = isLinkedAssetType(asset.type) ? undefined : libraryPosterUrl(asset);
@@ -643,16 +644,15 @@ async function checkFont(
file: File,
): Promise<{ label: string; poster: Blob | null }> {
if (file.size > MAX_FONT_BYTES) {
- throw new Error(
- `Fonts are limited to ${Math.round(MAX_FONT_BYTES / 1024 ** 2)}MB.`,
- );
+ const limit = Math.round(MAX_FONT_BYTES / 1024 ** 2);
+ throw new UserError("font_too_large", `Fonts are limited to ${limit}MB.`, { limit });
}
const bytes = await file.arrayBuffer();
const family = `lf-check-${file.size}`;
try {
await installFontFace(family, bytes);
} catch {
- throw new Error("That file isn't a font Cut can read.");
+ throw new UserError("font_unreadable", "That file isn't a font Cut can read.");
}
return {
label: fontLabelFor(bytes, file.name),
@@ -670,18 +670,20 @@ async function checkLut(
): Promise<{ label: string; meta: LinkedUploadMeta }> {
const maxBytes = CUT_COLOR.lutFileMaxBytes;
if (file.size > maxBytes) {
- throw new Error(
- `LUT files are limited to ${Math.round(maxBytes / 1024 ** 2)}MB.`,
- );
+ const limit = Math.round(maxBytes / 1024 ** 2);
+ throw new UserError("lut_too_large", `LUT files are limited to ${limit}MB.`, { limit });
}
const bytes = await file.arrayBuffer();
let parsed: ReturnType<typeof parseLutFile>;
try {
parsed = parseLutFile(file.name, new TextDecoder().decode(bytes));
} catch (e) {
- throw new Error(
- `That file isn't a LUT Cut can read. ${e instanceof Error ? e.message : ""}`.trim(),
- );
+ // The parser's reason rides as a value; with none the sentence stands alone.
+ const reason = e instanceof Error ? e.message.trim() : "";
+ if (!reason) {
+ throw new UserError("lut_unreadable", "That file isn't a LUT Cut can read.");
+ }
+ throw new UserError("lut_unreadable_reason", `That file isn't a LUT Cut can read. ${reason}`, { reason });
}
return {
label: lutFileName(file.name),
@@ -732,9 +734,7 @@ export async function uploadToLibrary(
!meta ||
(meta.type !== "image" && !isLinkedAssetType(meta.type) && !(meta.duration > 0))
) {
- throw new Error(
- "This image could not be read.",
- );
+ throw new UserError("image_unreadable", "This image could not be read.");
}
const key = await presignedUpload(
"/api/cut/library/presign",
@@ -766,7 +766,7 @@ export async function uploadToLibrary(
}),
});
const body = await apiJson<LibraryAsset>(res);
- if (!res.ok) throw new Error(body.error ?? "Upload failed.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("upload_failed", "Upload failed."));
return { ...body, residency };
}
const form = new FormData();
@@ -789,7 +789,7 @@ export async function uploadToLibrary(
return uploadToLibrary(prepared, residency, { ...keep, name: keep.name ?? file.name });
}, { ...keep, folderId: undefined });
}
- throw new Error("This image could not be read.");
+ throw new UserError("image_unreadable", "This image could not be read.");
}
form.append("meta", JSON.stringify(meta));
} else if (linkedMeta) {
@@ -812,7 +812,7 @@ export async function uploadToLibrary(
return uploadToLibrary(prepared, residency, { ...keep, name: keep.name ?? file.name });
}, { ...keep, folderId: undefined });
}
- if (!res.ok) throw new Error(body.error ?? "Upload failed.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("upload_failed", "Upload failed."));
return { ...body, residency };
}
@@ -820,7 +820,7 @@ export async function deleteFromLibrary(residency: Residency, id: string) {
const res = await backendFor(residency).fetch(`/api/cut/library/${id}`, {
method: "DELETE",
});
- if (!res.ok) throw new Error("Could not delete.");
+ if (!res.ok) throw new UserError("library_delete_failed", "Could not delete.");
}
/** Whether a library file on this shelf lands in the open project by a
@@ -850,14 +850,14 @@ async function copyLibraryFileToProject(
});
const body = await apiJson<{ fileName?: string }>(res);
if (!res.ok || !body.fileName)
- throw new Error(body.error ?? "Could not add from library.");
+ throw replyError(res.status, body, new UserError("library_add_failed", "Could not add from library."));
return body.fileName;
}
const bytes = await backendFor(residency).fetch(
`/api/cut/library/media/${encodeURIComponent(fileName)}`,
{ signal: opts?.signal },
);
- if (!bytes.ok) throw new Error("Could not read that library file.");
+ if (!bytes.ok) throw new UserError("library_file_read_failed", "Could not read that library file.");
return uploadProjectMediaTo(
target,
projectId,
@@ -877,9 +877,9 @@ export async function importLibraryAsset(
lib: LibraryAsset,
): Promise<MediaAsset> {
if (lib.type === "font")
- throw new Error("Fonts are used from the font menu, not the timeline.");
+ throw new UserError("font_not_for_timeline", "Fonts are used from the font menu, not the timeline.");
if (isLinkedAssetType(lib.type))
- throw new Error("A LUT is applied to a clip's color, from the Color panel.");
+ throw new UserError("lut_not_for_timeline", "A LUT is applied to a clip's color, from the Color panel.");
// The project's media takes the name the shelf shows, so a phone
// recording lands on the timeline under its title.
const name = lib.title || lib.name;
@@ -959,7 +959,7 @@ async function repairLibraryAssetMeta(
headers: { "Content-Type": "application/json" },
body: JSON.stringify(meta),
});
- if (!res.ok) throw new Error((await apiJson<unknown>(res)).error ?? "Could not update the library asset.");
+ if (!res.ok) throw errorFromBody(await apiJson<unknown>(res), new UserError("library_asset_update_failed", "Could not update the library asset."));
}
/** Copy a library asset into the open project and add it to the timeline at
@@ -986,7 +986,7 @@ export async function saveTemplate(
body: JSON.stringify({ projectId, ...input }),
});
const body = await apiJson<LibraryTemplate>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not save the template.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("template_save_failed", "Could not save the template."));
return { ...body, residency };
}
@@ -1011,7 +1011,7 @@ export async function carryTemplateTo(
`/api/cut/library/media/${encodeURIComponent(m.fileName)}`,
);
if (!res.ok)
- throw new Error("Could not read that template's media off its shelf.");
+ throw new UserError("template_media_read_failed", "Could not read that template's media off its shelf.");
files.push(new File([await res.blob()], m.fileName));
}
const input = {
@@ -1054,7 +1054,7 @@ export async function carryTemplateTo(
});
}
const body = await apiJson<LibraryTemplate>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not add the template.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("template_add_failed", "Could not add the template."));
await deleteTemplate(t.residency, t.id);
}
@@ -1068,11 +1068,9 @@ export async function addAssetToLibraryTemplate(
asset: MediaAsset,
): Promise<LibraryTemplateItem> {
if (template.residency !== getBackend().kind) {
- throw new Error(
- template.residency === "cloud"
- ? "That template is in the cloud; this project isn't."
- : "That template is on this Mac; this project isn't.",
- );
+ throw template.residency === "cloud"
+ ? new UserError("template_in_cloud", "That template is in the cloud; this project isn't.")
+ : new UserError("template_on_mac", "That template is on this Mac; this project isn't.");
}
const len = asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration;
const part =
@@ -1100,7 +1098,7 @@ export async function addAssetToLibraryTemplate(
},
);
const body = await apiJson<LibraryTemplate>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not add to the template.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("template_append_failed", "Could not add to the template."));
return { ...body, residency: template.residency };
}
@@ -1117,7 +1115,7 @@ export async function renameTemplate(
body: JSON.stringify({ name }),
},
);
- if (!res.ok) throw new Error("Could not rename the template.");
+ if (!res.ok) throw new UserError("template_rename_failed", "Could not rename the template.");
}
/** Rename a Library file on its own shelf. Every kind takes the same call. */
@@ -1135,11 +1133,11 @@ export async function renameLibraryAsset(
},
);
if (res.ok) return;
- const error = (await apiJson<unknown>(res)).error;
+ const body = await apiJson<unknown>(res);
// An engine from before renames answers the route with nothing.
- if (!error && residency === "local" && (res.status === 404 || res.status === 405))
- throw new Error("Update the Donkey app to rename files on this Mac.");
- throw new Error(error ?? "Could not rename the file.");
+ if (!body.error && residency === "local" && (res.status === 404 || res.status === 405))
+ throw new UserError("app_update_to_rename", "Update the Donkey app to rename files on this Mac.");
+ throw errorFromBody(body, new UserError("file_rename_failed", "Could not rename the file."));
}
export async function deleteTemplate(
@@ -1152,7 +1150,7 @@ export async function deleteTemplate(
method: "DELETE",
},
);
- if (!res.ok) throw new Error("Could not delete the template.");
+ if (!res.ok) throw new UserError("template_delete_failed", "Could not delete the template.");
}
/** Land a template's media in the open project, in `template.media` order, and
@@ -1173,7 +1171,7 @@ async function copyTemplateMediaToProject(
);
const body = await apiJson<{ media?: TemplateMedia[] }>(res);
if (!res.ok || !body.media)
- throw new Error(body.error ?? "Could not add the template.");
+ throw replyError(res.status, body, new UserError("template_add_failed", "Could not add the template."));
return body.media;
}
const out: TemplateMedia[] = [];
@@ -1303,6 +1301,6 @@ export async function saveAssetToLibrary(
}),
});
const body = await apiJson<LibraryAsset>(res);
- if (!res.ok) throw new Error(body.error ?? "Could not save to library.");
+ if (!res.ok) throw replyError(res.status, body, new UserError("library_save_failed", "Could not save to library."));
return { ...body, residency };
}
diff --git a/site/src/cut/lib/libraryIntake.ts b/site/src/cut/lib/libraryIntake.ts
index d2f30573..5d6863a0 100644
--- a/site/src/cut/lib/libraryIntake.ts
+++ b/site/src/cut/lib/libraryIntake.ts
@@ -11,6 +11,7 @@ import { estimatedShape, importUrlToLibrary, moveLibraryItem, uploadToLibrary, t
import type { LibraryUploadState } from "@/cut/lib/libraryUpload";
import { libraryKey, libraryScope, patchLibrary, refetchLibrary } from "@/cut/lib/queries";
import type { Residency } from "@/cut/lib/residency";
+import { UserError, errorFields, type ErrorFields } from "@/cut/lib/userError";
export type LibraryArrival = {
id: string;
@@ -24,9 +25,8 @@ export type LibraryArrival = {
stage: "preparing" | "uploading" | ImportStage;
startStage: "preparing" | "uploading" | ImportStage;
shape?: { width: number; height: number };
- error?: string;
run: () => Promise<void>;
-};
+} & ErrorFields;
export const useLibraryImports = create<{ items: LibraryArrival[] }>(() => ({ items: [] }));
const update = (fn: (items: LibraryArrival[]) => LibraryArrival[]) =>
@@ -59,18 +59,18 @@ export function importLibraryFiles(
let running: Promise<void> | undefined;
const work = async () => {
if (!wanted(id)) return;
- update((items) => items.map((item) => item.id === id ? { ...item, error: undefined, startedAt: Date.now() } : item));
+ update((items) => items.map((item) => item.id === id ? { ...item, error: undefined, errorCode: undefined, errorParams: undefined, startedAt: Date.now() } : item));
try {
const expanded = await expandLinkedFiles([file]);
if (!wanted(id)) return;
if (expanded.length !== 1 || expanded[0] !== file) {
const children = expanded.filter(accepts).map(prepare);
- if (!children.length) throw new Error("This archive contains no supported files.");
+ if (!children.length) throw new UserError("archive_no_supported_files", "This archive contains no supported files.");
update((items) => items.flatMap((item) => item.id === id ? children : [item]));
for (const child of children) await child.run();
return;
}
- if (!accepts(file)) throw new Error("This file contains no supported media.");
+ if (!accepts(file)) throw new UserError("file_no_supported_media", "This file contains no supported media.");
if (!asset) {
const residency = isLinkedFile(file) && !target.folderId ? await shelfForNewItem(file.size) : target.residency;
if (!wanted(id)) return;
@@ -84,14 +84,14 @@ export function importLibraryFiles(
if (!wanted(id)) return;
if (!client.getQueryData(libraryKey(libraryScope()))) {
await refetchLibrary(client);
- if (!client.getQueryData(libraryKey(libraryScope()))) throw new Error("Could not refresh the library. Retry to show the saved file.");
+ if (!client.getQueryData(libraryKey(libraryScope()))) throw new UserError("library_refresh_failed", "Could not refresh the library. Retry to show the saved file.");
}
const landed = asset;
patchLibrary(client, (data) => ({ ...data, assets: [landed, ...data.assets.filter((item) => item.id !== landed.id)] }));
if (isLinkedType(asset.type)) void syncLinkedLibrary();
dismissLibraryImport(id);
} catch (error) {
- if (wanted(id)) update((items) => items.map((item) => item.id === id ? { ...item, error: error instanceof Error ? error.message : "Could not import this file." } : item));
+ if (wanted(id)) update((items) => items.map((item) => item.id === id ? { ...item, ...errorFields(error, new UserError("file_import_failed", "Could not import this file.")) } : item));
}
};
return {
@@ -173,7 +173,7 @@ function linkArrival(saved: SavedLink, client: QueryClient): LibraryArrival {
// A retry restarts the clock on the tile and on the saved link.
if (useLibraryImports.getState().items.find((item) => item.id === id)?.error) {
link = { ...link, startedAt: Date.now() };
- update((items) => items.map((item) => item.id === id ? { ...item, error: undefined, stage: item.startStage, startedAt: link.startedAt } : item));
+ update((items) => items.map((item) => item.id === id ? { ...item, error: undefined, errorCode: undefined, errorParams: undefined, stage: item.startStage, startedAt: link.startedAt } : item));
}
await editLinks(owner, (links) => [...links.filter((l) => l.id !== id), link]);
try {
@@ -194,7 +194,7 @@ function linkArrival(saved: SavedLink, client: QueryClient): LibraryArrival {
}
dismissLibraryImport(id);
} catch (error) {
- if (wanted()) update((items) => items.map((item) => item.id === id ? { ...item, error: error instanceof Error ? error.message : "Could not import that URL." } : item));
+ if (wanted()) update((items) => items.map((item) => item.id === id ? { ...item, ...errorFields(error, new UserError("url_import_failed", "Could not import that URL.")) } : item));
await editLinks(owner, (links) => links.filter((l) => l.id !== id));
}
};
diff --git a/site/src/cut/lib/libraryProxy.ts b/site/src/cut/lib/libraryProxy.ts
index 3dfa12b6..f86e3c1d 100644
--- a/site/src/cut/lib/libraryProxy.ts
+++ b/site/src/cut/lib/libraryProxy.ts
@@ -23,11 +23,12 @@ import { compatCovers } from "./proxyNames";
import type { LibraryAsset, LibraryData } from "./library";
import { useLightbox, lightboxItemFromLibrary } from "./lightbox";
import { backendFor } from "./residency";
+import { UserError, errorFields, errorFromBody, type ErrorFields } from "./userError";
/** Where an asset's copy stands this session. */
export type LibraryProxyState =
| { kind: "making"; progress: number }
- | { kind: "failed"; error: string };
+ | ({ kind: "failed"; error: string } & ErrorFields);
interface LibraryProxies {
jobs: Record<string, LibraryProxyState>;
@@ -47,7 +48,7 @@ const setJob = (key: string, state: LibraryProxyState | null) =>
return { jobs };
});
-const FAILED = "Could not make a playable copy of this video.";
+const FAILED = new UserError("playable_copy_failed", "Could not make a playable copy of this video.");
/** A cloud build still queued when the poll gives up: the worker keeps going,
* and the shelf's next listing carries the copy. */
const STILL_QUEUED = "The playable copy is still being made.";
@@ -78,7 +79,7 @@ export async function ensureLibraryProxy(
try {
// A Mac app older than the route has nothing to build the copy with.
if (a.residency === "local" && !(await engineFeatures()).has("library.proxy")) {
- throw new Error("Update the Donkey app to play this video here.");
+ throw new UserError("app_update_to_play", "Update the Donkey app to play this video here.");
}
const backend = backendFor(a.residency);
const { proxyMaxHeight, proxyCrf } = CUT_COLOR;
@@ -88,7 +89,7 @@ export async function ensureLibraryProxy(
body: JSON.stringify({ maxHeight: proxyMaxHeight, crf: proxyCrf, ...(compat ? { compat } : {}) }),
});
const body = await apiJson<LibraryAsset | { jobId: string }>(res);
- if (!res.ok) throw new Error(body.error ?? FAILED);
+ if (!res.ok) throw errorFromBody(body, FAILED);
// The cloud queues the build on its worker; the Mac and the page answer
// with the asset once the copy is there.
@@ -99,7 +100,7 @@ export async function ensureLibraryProxy(
})
: body;
const proxyFile = landed.proxyFile;
- if (!proxyFile) throw new Error(FAILED);
+ if (!proxyFile) throw FAILED;
const updated: LibraryAsset = { ...a, proxyFile };
patch((d) => ({
...d,
@@ -111,8 +112,8 @@ export async function ensureLibraryProxy(
if (open?.libraryId === a.id) useLightbox.getState().open(lightboxItemFromLibrary(updated, open.bare));
setJob(key, null);
} catch (e) {
- const error = e instanceof Error ? e.message : FAILED;
- if (error === STILL_QUEUED) return;
- setJob(key, { kind: "failed", error });
+ const failure = errorFields(e, FAILED);
+ if (failure.error === STILL_QUEUED) return;
+ setJob(key, { kind: "failed", ...failure });
}
}
diff --git a/site/src/cut/lib/libraryShareCopy.ts b/site/src/cut/lib/libraryShareCopy.ts
index 2ddb288d..b9e9ed33 100644
--- a/site/src/cut/lib/libraryShareCopy.ts
+++ b/site/src/cut/lib/libraryShareCopy.ts
@@ -6,10 +6,11 @@ import {
moveLibraryItem, type LibraryData, type LibraryAsset, type LibraryTemplateItem,
} from "@/cut/lib/library";
import type { LibraryShareTarget } from "@/cut/lib/librarySharing";
+import { UserError } from "@/cut/lib/userError";
async function uploadFile(residency: Residency, fileName: string) {
const response = await backendFor(residency).fetch(`/api/cut/library/media/${encodeURIComponent(fileName)}`);
- if (!response.ok) throw new Error("Could not read the file for sharing.");
+ if (!response.ok) throw new UserError("share_file_read_failed", "Could not read the file for sharing.");
const blob = await response.blob();
return presignedUpload("/api/cut/library/presign", blob, fileName, cloudBackend);
}
@@ -34,7 +35,7 @@ export async function copyLibraryForSharing(
width: asset.width, height: asset.height, source: asset.source,
} }),
});
- if (!response.ok) throw new Error("Could not copy the asset to Cloud.");
+ if (!response.ok) throw new UserError("share_asset_copy_failed", "Could not copy the asset to Cloud.");
const landed = await response.json() as { id: string };
assets.push(landed.id);
if (folderId) await moveLibraryItem("cloud", landed.id, folderId);
@@ -47,19 +48,19 @@ export async function copyLibraryForSharing(
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...template, folderId, keys }),
});
- if (!response.ok) throw new Error("Could not copy the template to Cloud.");
+ if (!response.ok) throw new UserError("share_template_copy_failed", "Could not copy the template to Cloud.");
const landed = await response.json() as { id: string };
templates.push(landed.id);
};
try {
if (target.kind === "asset") {
const asset = library.assets.find((a) => a.id === target.id && a.residency === residency);
- if (!asset) throw new Error("Asset not found.");
+ if (!asset) throw new UserError("asset_not_found", "Asset not found.");
return { kind: "asset", id: await copyAsset(asset, null) };
}
const sourceFolders = library.folders.filter((f) => f.residency === residency);
const root = sourceFolders.find((f) => f.id === target.id);
- if (!root) throw new Error("Folder not found.");
+ if (!root) throw new UserError("folder_not_found", "Folder not found.");
const group = <T,>(items: T[], parentOf: (item: T) => string | null) => {
const groups = new Map<string | null, T[]>();
for (const item of items) {
@@ -78,7 +79,7 @@ export async function copyLibraryForSharing(
let rootId = "";
for (let i = 0; i < todo.length; i++) {
const { folder, parent } = todo[i];
- if (seen.has(folder.id)) throw new Error("This folder contains a cycle.");
+ if (seen.has(folder.id)) throw new UserError("folder_cycle", "This folder contains a cycle.");
seen.add(folder.id);
const copy = await createLibraryFolder(folder.name, "cloud", parent);
folders.push(copy.id);
@@ -99,7 +100,7 @@ export async function copyLibraryForSharing(
cleanup.push(...await Promise.allSettled([deleteLibraryFolder("cloud", id)]));
}
if (cleanup.some((result) => result.status === "rejected"))
- throw new Error("Copy failed. Some unshared copies remain in your Cloud library; remove them before retrying.");
+ throw new UserError("share_copy_leftovers", "Copy failed. Some unshared copies remain in your Cloud library; remove them before retrying.");
throw error;
}
}
diff --git a/site/src/cut/lib/linkedLibrary/luts.ts b/site/src/cut/lib/linkedLibrary/luts.ts
index 9baf7f82..28a267f0 100644
--- a/site/src/cut/lib/linkedLibrary/luts.ts
+++ b/site/src/cut/lib/linkedLibrary/luts.ts
@@ -20,6 +20,7 @@ import { cloudRequest } from "../backend/cloud";
import { parseLutBytes } from "../lutParse";
import { isLutFile, LUT_ACCEPT } from "../media";
import type { ProjectDoc } from "../types";
+import { UserError } from "../userError";
import {
linkedBytes,
linkId,
@@ -112,7 +113,7 @@ export async function loadLibraryLutFile(id: string): Promise<{ fileName: string
const builtin = builtinLutOf(id);
if (builtin) return { fileName: `${builtin.id}.cube`, bytes: new Uint8Array(await builtinBytes(builtin)) };
const item = listLinked(PREFIX).find((i) => libraryLutId(i.key) === id);
- if (!item) throw new Error(`The LUT ${id} is not in the library.`);
+ if (!item) throw new UserError("lut_not_in_library", `The LUT ${id} is not in the library.`, { id });
let lastError: unknown = null;
for (const copy of item.copies) {
try {
@@ -122,15 +123,20 @@ export async function loadLibraryLutFile(id: string): Promise<{ fileName: string
lastError = e; // That shelf isn't answering; another copy may still serve.
}
}
- const why = lastError instanceof Error ? ` ${lastError.message}` : "";
- throw new Error(`The LUT "${item.label}" could not be read.${why}`);
+ // The shelf's own reason, when it gave one, rides as a value.
+ const label = item.label;
+ if (!(lastError instanceof Error)) {
+ throw new UserError("lut_read_failed", `The LUT "${label}" could not be read.`, { label });
+ }
+ const reason = lastError.message;
+ throw new UserError("lut_read_failed_reason", `The LUT "${label}" could not be read. ${reason}`, { label, reason });
}
/** A built-in LUT's bytes, off the site: same-origin in the page, the bound
* session's origin in a headless run. */
async function builtinBytes(l: BuiltinLut): Promise<ArrayBuffer> {
const res = await cloudRequest(l.file);
- if (!res.ok) throw new Error(`The built-in LUT "${l.label}" could not be fetched (${res.status}).`);
+ if (!res.ok) throw new UserError("lut_builtin_fetch_failed", `The built-in LUT "${l.label}" could not be fetched (${res.status}).`, { label: l.label, status: res.status });
return res.arrayBuffer();
}
diff --git a/site/src/cut/lib/localStt.ts b/site/src/cut/lib/localStt.ts
index 81003652..f6df04bd 100644
--- a/site/src/cut/lib/localStt.ts
+++ b/site/src/cut/lib/localStt.ts
@@ -9,6 +9,7 @@
import { localBackend } from "./backend/local";
import { encodeWav } from "./cloudTranscribe";
import type { SubtitleCue } from "./types";
+import { errorFromBody, UserError } from "./userError";
const POLL_MS = 700;
@@ -51,19 +52,19 @@ async function engineTranscribe(
const res = await localBackend.fetch("/api/cut/stt", { method: "POST", body: form });
const body = (await res.json().catch(() => null)) as { id?: string; error?: string } | null;
if (!res.ok || !body?.id) {
- throw new Error(body?.error ?? "On-device transcription failed to start.");
+ throw errorFromBody(body, new UserError("local_transcription_start_failed", "On-device transcription failed to start."));
}
for (;;) {
await new Promise((r) => setTimeout(r, POLL_MS));
if (isStale?.()) return null;
const st = await localBackend.fetch(`/api/cut/stt/${body.id}`);
- if (!st.ok) throw new Error("The transcription job was lost.");
+ if (!st.ok) throw new UserError("transcription_job_gone", "The transcription job was lost.");
const status = (await st.json()) as {
status: string;
error?: string;
cues?: SubtitleCue[];
};
- if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");
+ if (status.status === "error") throw errorFromBody(status, new UserError("transcription_failed", "Transcription failed."));
if (status.status === "done") return status.cues ?? [];
}
}
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index f326bfd5..9a28fa9b 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -7,7 +7,8 @@ import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { registerBlobFile } from "./backend/browser/registry";
import { cloudBackend } from "./backend/cloud";
import { pollCloudJob } from "./cloudJob";
-import { quotaErrorMessage } from "./backend/cloud";
+import { creatorNames } from "./defaultNames";
+import { errorFromBody, replyError, UserError } from "./userError";
import { encodeWav } from "./cloudTranscribe";
import { allowance, canvasBytes, holdMemory } from "./memoryBudget";
import { normalizeLink } from "./link";
@@ -91,14 +92,14 @@ export async function createProjectFromFile(
folderId: string | null
): Promise<string | null> {
if (!isMediaFile(file)) return null;
- const name = file.name.replace(/\.[^./]+$/, "") || "Untitled";
+ const name = file.name.replace(/\.[^./]+$/, "") || creatorNames().untitled;
const res = await apiFetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, folderId }),
});
const project = await apiJson<ProjectSummary>(res);
- if (!res.ok || !project.id) throw new Error(project.error ?? "Could not create the project.");
+ if (!res.ok || !project.id) throw errorFromBody(project, new UserError("project_creation_failed", "Could not create the project."));
const asset = await importFileToProject(project.id, file);
// Media the engine rejects leaves an empty project rather than a dangling id.
@@ -229,9 +230,7 @@ export async function presignUpload(
});
const body = await apiJson<{ key?: string; url?: string; fileName?: string }>(res);
if (!res.ok || !body.key || !body.url) {
- const err = new Error(
- quotaErrorMessage(res.status, body) ?? body.error ?? "Upload failed."
- ) as Error & { status?: number };
+ const err = replyError(res.status, body, new UserError("upload_failed", "Upload failed.")) as Error & { status?: number };
err.status = res.status;
throw err;
}
@@ -268,7 +267,7 @@ export function putSigned(
body: file,
signal: opts?.signal,
}).then((res) => {
- if (!res.ok) throw new Error("Upload failed.");
+ if (!res.ok) throw new UserError("upload_failed", "Upload failed.");
opts?.onProgress?.(1);
});
}
@@ -283,8 +282,8 @@ export function putSigned(
};
}
xhr.onload = () =>
- xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error("Upload failed."));
- xhr.onerror = () => reject(new ConnectionLostError("Upload failed."));
+ xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new UserError("upload_failed", "Upload failed."));
+ xhr.onerror = () => reject(new ConnectionLostError("upload_failed", "Upload failed."));
xhr.onabort = () => reject(new DOMException("Upload cancelled.", "AbortError"));
opts?.signal?.addEventListener("abort", () => xhr.abort(), { once: true });
xhr.send(file);
@@ -308,16 +307,16 @@ function postFormWatched(
};
}
xhr.onload = () => {
- let body: { fileName?: string; error?: string } = {};
+ let body: { fileName?: string; error?: string; code?: string } = {};
try {
body = JSON.parse(xhr.responseText) as typeof body;
} catch {
// A reply that never reached a handler is plain text.
}
if (xhr.status >= 200 && xhr.status < 300 && body.fileName) resolve(body.fileName);
- else reject(new Error(body.error ?? "Upload failed."));
+ else reject(errorFromBody(body, new UserError("upload_failed", "Upload failed.")));
};
- xhr.onerror = () => reject(new ConnectionLostError("Upload failed."));
+ xhr.onerror = () => reject(new ConnectionLostError("upload_failed", "Upload failed."));
xhr.onabort = () => reject(new DOMException("Upload cancelled.", "AbortError"));
opts?.signal?.addEventListener("abort", () => xhr.abort(), { once: true });
xhr.send(form);
@@ -352,7 +351,7 @@ export async function uploadProjectMediaTo(
}
const res = await backend.fetch(path, { method: "POST", body: form, signal: opts?.signal });
const body = await apiJson<{ fileName?: string }>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ if (!res.ok || !body.fileName) throw errorFromBody(body, new UserError("upload_failed", "Upload failed."));
return body.fileName;
}
const signed = await presignUpload(
@@ -369,7 +368,7 @@ export async function uploadProjectMediaTo(
body: JSON.stringify({ key }),
});
const body = await apiJson<{ fileName?: string }>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ if (!res.ok || !body.fileName) throw errorFromBody(body, new UserError("upload_failed", "Upload failed."));
return body.fileName;
}
@@ -385,12 +384,12 @@ export async function uploadProjectImage(
projectId: string,
file: Blob,
fileName: string,
- opts?: { name?: string; origin?: "generated" | "sticker"; failMessage?: string; backend?: CutBackend }
+ opts?: { name?: string; origin?: "generated" | "sticker"; failMessage?: UserError | string; backend?: CutBackend }
): Promise<MediaAsset> {
// Callers whose work outlives navigation (finishing AI generations) pin the
// backend they started on; everyone else rides the active one.
const backend = opts?.backend ?? getBackend();
- const failMessage = opts?.failMessage ?? "Could not add the image.";
+ const failMessage = opts?.failMessage ?? new UserError("image_add_failed", "Could not add the image.");
if (backend.kind !== "cloud" || file.size < IMAGE_INLINE_MAX) {
const form = new FormData();
form.append("file", file, fileName);
@@ -402,7 +401,7 @@ export async function uploadProjectImage(
});
const body = await apiJson<MediaAsset>(res);
if (!res.ok || !body.fileName) {
- throw new Error(quotaErrorMessage(res.status, body) ?? body.error ?? failMessage);
+ throw replyError(res.status, body, failMessage);
}
return { ...body, url: await storedMediaUrl(projectId, body.fileName, backend) };
}
@@ -677,7 +676,7 @@ function sendCloudImport(
claim = { ...made, stored: storedUrl !== null };
} else {
const stashed = await stashUnclaimedMedia(projectId, file);
- if (!stashed) throw new Error(quotaErrorMessage(413, {}) ?? "Upload failed.");
+ if (!stashed) throw replyError(413, {}, new UserError("upload_failed", "Upload failed."));
claim = { signed: null, fileName: stashed.fileName, stored: true };
}
// Deleted, or left behind, while the claim ran: the copy comes back out
@@ -702,7 +701,7 @@ function sendCloudImport(
body: JSON.stringify({ key: claim.signed.key }),
});
const body = await apiJson<{ fileName?: string }>(res);
- if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");
+ if (!res.ok || !body.fileName) throw errorFromBody(body, new UserError("upload_failed", "Upload failed."));
return body.fileName;
};
}
@@ -719,7 +718,7 @@ export function sendStoredUpload(
): PendingImport["send"] {
return async (opts) => {
const file = await localMediaFile(projectId, fileName);
- if (!file) throw new Error("The local copy of this file is gone.");
+ if (!file) throw new UserError("local_copy_gone", "The local copy of this file is gone.");
const mime = file.type || "application/octet-stream";
// Steer the cloud's dedupe around the other pinned names, never this one:
// this drain is the pin's own claim.
@@ -741,7 +740,7 @@ export function sendStoredUpload(
res
);
if (!res.ok || !body.fileName || (!body.done && !(body.url && body.key))) {
- throw new Error(quotaErrorMessage(res.status, body) ?? body.error ?? "Upload failed.");
+ throw replyError(res.status, body, new UserError("upload_failed", "Upload failed."));
}
let finalName = body.fileName;
if (!body.done) {
@@ -761,7 +760,7 @@ export function sendStoredUpload(
body: JSON.stringify({ key: body.key }),
});
const cbody = await apiJson<{ fileName?: string }>(cres);
- if (!cres.ok || !cbody.fileName) throw new Error(cbody.error ?? "Upload failed.");
+ if (!cres.ok || !cbody.fileName) throw errorFromBody(cbody, new UserError("upload_failed", "Upload failed."));
finalName = cbody.fileName;
}
await renameLocalMedia(projectId, fileName, finalName);
@@ -953,7 +952,7 @@ export function importRemote(
signal?: AbortSignal;
}) => {
const dl = await fetch(init.url, { signal: opts?.signal });
- if (!dl.ok) throw new Error("Could not read the media.");
+ if (!dl.ok) throw new UserError("media_fetch_failed", "Could not read the media.");
const blob = await dl.blob();
return uploadProjectMediaTo(getBackend(), projectId, blob, storeAs, opts);
};
@@ -1026,7 +1025,7 @@ export async function importImage(
// no longer resolves, a dead link). Registering that would place a broken
// still and hand the first-asset aspect guess a meaningless size, so the
// import fails here instead.
- if (dims.width === 0 || dims.height === 0) throw new Error("Could not read the image.");
+ if (dims.width === 0 || dims.height === 0) throw new UserError("image_read_failed", "Could not read the image.");
// A stock image lands on the timeline where the caller places it, not in the
// Media panel — tag it so it stays out.
return importRemote(projectId, {
@@ -1079,6 +1078,9 @@ export async function importStockAudio(
});
}
+// A URL import that failed, worded the same whichever residency ran it.
+const urlImportFailed = () => new UserError("url_import_failed", "Could not import that URL.");
+
/** Download a URL (TikTok, YouTube, an X post, an article, …) into the project
* through the engine's bundled downloader and register what came back — one
* asset for a video, one per photo for a photo post, none at all for a source
@@ -1109,15 +1111,15 @@ export async function importUrlMedia(
if (backend.kind === "cloud") {
// The cloud route is async: it answers {jobId} and a worker does the fetch.
const started = await apiJson<{ jobId?: string }>(res);
- if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");
- body = await pollCloudJob(started.jobId, backend, "Could not import that URL.");
+ if (!res.ok || !started.jobId) throw errorFromBody(started, urlImportFailed());
+ body = await pollCloudJob(started.jobId, backend, urlImportFailed());
} else {
body = await apiJson<{ files?: { fileName: string; title: string }[]; text?: string }>(res);
}
// A source that is only words (a text post, an article, a page) imports as
// that text with no files, so an empty file list with text is a success.
if (!res.ok || (!body.files?.length && !body.text)) {
- throw new Error(body.error ?? "Could not import that URL.");
+ throw errorFromBody(body, urlImportFailed());
}
return adoptImportedFiles(projectId, body, backend);
}
@@ -1163,13 +1165,13 @@ async function importUrlThroughCloud(
body: JSON.stringify({ url, ...(opts.audio ? { audio: true } : {}) }),
});
const started = await apiJson<{ jobId?: string }>(res);
- if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not import that URL.");
+ if (!res.ok || !started.jobId) throw errorFromBody(started, urlImportFailed());
const done = await pollCloudJob<{
assets?: { id: string; fileName: string; name: string }[];
text?: string;
- }>(started.jobId, cloudBackend, "Could not import that URL.");
+ }>(started.jobId, cloudBackend, urlImportFailed());
// Words with no media are a successful import; nothing at all is a failure.
- if (!done.assets?.length && !done.text) throw new Error("Could not import that URL.");
+ if (!done.assets?.length && !done.text) throw urlImportFailed();
const files: { fileName: string; title: string }[] = [];
// Every staged copy is dropped from the cloud shelf, however this ends: a
// download or a local write that throws part way through would otherwise
@@ -1186,7 +1188,7 @@ async function importUrlThroughCloud(
for (const staged of done.assets ?? []) {
const path = `/api/cut/library/media/${encodeURIComponent(staged.fileName)}`;
const bytes = await cloudBackend.fetch(path);
- if (!bytes.ok) throw new Error("Could not import that URL.");
+ if (!bytes.ok) throw urlImportFailed();
const fileName = await uploadProjectMediaTo(
backend,
projectId,
@@ -1322,7 +1324,7 @@ async function* sourcePcm(
): AsyncGenerator<PcmChunk> {
const input = openMedia(sourceUrl);
const track = await audioTrackOf(input).finally(() => input.dispose());
- if (!track) throw new Error("This file has no audio track.");
+ if (!track) throw new UserError("media_no_audio_track", "This file has no audio track.");
if (to !== undefined && !(to > from)) return;
for await (const { buffer, timestamp } of audioChunks(sourceUrl, from, to)) {
yield {
@@ -1428,7 +1430,7 @@ export async function renderAudioSpanWav(
// Only the asked-for span is decoded, so pulling thirty seconds out of an
// hour-long file costs thirty seconds of work.
const span = await decodeAudioSpan(sourceUrl, Math.max(0, from), to);
- if (!span) throw new Error("This file has no audio track.");
+ if (!span) throw new UserError("media_no_audio_track", "This file has no audio track.");
const dur = span.duration;
if (!(dur > 0)) throw new Error("from/to describe an empty range.");
const rate = 16000; // encodeWav's fixed sample rate
@@ -1570,18 +1572,18 @@ export async function makeStillFrame(
detail: WatchDetail = "scan"
): Promise<WatchFrames> {
const img = await decodeRasterImageUrl(sourceUrl);
- if (!img || img.width === 0 || img.height === 0) throw new Error("Could not read the image.");
+ if (!img || img.width === 0 || img.height === 0) throw new UserError("image_read_failed", "Could not read the image.");
const g = watchGeometry(detail);
const [w, h] = cellDims(img.width, img.height, g.cell);
const canvas = createRasterCanvas(w, h);
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
- if (!ctx) throw new Error("Could not read the image.");
+ if (!ctx) throw new UserError("image_read_failed", "Could not read the image.");
ctx.imageSmoothingQuality = "high";
ctx.drawImage(img.source, 0, 0, w, h);
// A picture read through an element (a host that sends no CORS header)
// taints the canvas, and the encode is where that surfaces.
const image = await rasterCanvasToDataUrl(canvas, "image/jpeg", g.quality).catch(() => {
- throw new Error("Could not read the image.");
+ throw new UserError("image_read_failed", "Could not read the image.");
});
return {
frames: [{ t: 0, image, via: "first" }],
diff --git a/site/src/cut/lib/mediaConvert.ts b/site/src/cut/lib/mediaConvert.ts
index e44a0a03..3e00087b 100644
--- a/site/src/cut/lib/mediaConvert.ts
+++ b/site/src/cut/lib/mediaConvert.ts
@@ -28,6 +28,7 @@ import {
UnreadableMediaError,
} from "./mediaRead";
import type { ConvertMode } from "./convertMode";
+import { errorFromBody, UserError } from "./userError";
import { useEditor } from "./store";
import type { MediaAsset } from "./types";
@@ -137,7 +138,7 @@ export async function convertAssetToMp4(
asset: MediaAsset,
opts: ConvertOptions = {}
): Promise<ConvertOutcome> {
- if (asset.type === "image") throw new Error("Images have nothing to convert.");
+ if (asset.type === "image") throw new UserError("convert_image_refused", "Images have nothing to convert.");
const backend = opts.backend ?? getBackend();
const made = await convertProjectFile(
projectId,
@@ -196,6 +197,9 @@ interface ServerConvert {
error?: string;
}
+// A conversion that failed with nothing more to say.
+const convertFailed = () => new UserError("convert_failed", "Could not convert that file.");
+
const fromServer = (body: ServerConvert): FileConversion => ({
fileName: body.fileName!,
reencoded: !!body.transcodedVideo || !!body.transcodedAudio,
@@ -220,18 +224,18 @@ async function convertOnBackend(
let body: ServerConvert;
if (backend.kind === "cloud") {
const started = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string };
- if (!res.ok || !started.jobId) throw new Error(started.error ?? "Could not convert that file.");
+ if (!res.ok || !started.jobId) throw errorFromBody(started, convertFailed());
body = await pollCloudJob(
started.jobId,
backend,
- "Could not convert that file.",
- { timedOut: "The conversion took too long." }
+ convertFailed(),
+ { timedOut: new UserError("convert_timed_out", "The conversion took too long.") }
);
} else {
body = (await res.json().catch(() => ({}))) as ServerConvert;
- if (!res.ok) throw new Error(body.error ?? "Could not convert that file.");
+ if (!res.ok) throw errorFromBody(body, convertFailed());
}
- if (!body.fileName) throw new Error(body.error ?? "Could not convert that file.");
+ if (!body.fileName) throw errorFromBody(body, convertFailed());
return fromServer(body);
}
@@ -256,10 +260,10 @@ async function convertNearThePage(
catch { /* The browser still needs a decoder; hosted preparation supplies it. */ }
}
const response = resolveRegisteredBlob(source.url) ?? await fetch(source.url).then((res) => {
- if (!res.ok) throw new Error(`Could not read ${source.name}.`);
+ if (!res.ok) throw new UserError("file_read_failed", `Could not read ${source.name}.`, { name: source.name });
return res.blob();
});
- if (!response) throw new Error(`Could not read ${source.name}.`);
+ if (!response) throw new UserError("file_read_failed", `Could not read ${source.name}.`, { name: source.name });
return withCloudPreparedMedia(
new File([response], source.fileName, { type: response.type }),
(prepared) => land(projectId, source, prepared, opts),
@@ -333,10 +337,10 @@ async function convertInProcess(
(track === video || track === audio) &&
(reason === "undecodable_source_codec" || reason === "no_encodable_target_codec")
)) throw new ConversionUnavailableError("This media needs hosted conversion.");
- if (!conversion.isValid) throw new Error(`Could not convert ${source.name}.`);
+ if (!conversion.isValid) throw new UserError("file_convert_failed", `Could not convert ${source.name}.`, { name: source.name });
await conversion.execute();
const buffer = output.target.buffer;
- if (!buffer) throw new Error(`Could not convert ${source.name}.`);
+ if (!buffer) throw new UserError("file_convert_failed", `Could not convert ${source.name}.`, { name: source.name });
const made = await land(projectId, source, new Blob([buffer], { type: "video/mp4" }), opts);
return { ...made, reencoded };
} finally {
@@ -358,8 +362,8 @@ async function convertOnTheMac(
if (opts.mode === "reencode") form.append("mode", opts.mode);
const res = await engineFetch("/api/cut/convert", { method: "POST", body: form });
if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { error?: string };
- throw new Error(body.error ?? `Could not convert ${source.name}.`);
+ const body: unknown = await res.json().catch(() => null);
+ throw errorFromBody(body, new UserError("file_convert_failed", `Could not convert ${source.name}.`, { name: source.name }));
}
// The handoff only happens for footage this process cannot decode, which is
// footage the Mac had to re-encode.
diff --git a/site/src/cut/lib/mediaProxy.ts b/site/src/cut/lib/mediaProxy.ts
index 51eb8dcd..d0751c4e 100644
--- a/site/src/cut/lib/mediaProxy.ts
+++ b/site/src/cut/lib/mediaProxy.ts
@@ -46,6 +46,7 @@ import { encodeProxyInPage, proxyNameFor, proxyOnTheMac, type Landed } from "./p
import { compatCoverOf, compatCovers, compatProxyNameFor, isLightProxyName, type CompatCover } from "./proxyNames";
import { releaseProxyHold, useEditor } from "./store";
import type { MediaAsset, StoredAsset } from "./types";
+import { errorFields, errorFromBody, UserError, type ErrorFields } from "./userError";
/** Past this many pixels a frame is heavier than 1080p (a 2048×1080 DCI
* frame is not). */
@@ -100,7 +101,10 @@ export type ProxyState =
| { kind: "making"; progress: number }
/** No residency could make one; the preview plays the master. */
| { kind: "none" }
- | { kind: "failed"; error: string };
+ | ({ kind: "failed"; error: string } & ErrorFields);
+
+// A proxy that failed with nothing more to say.
+const proxyFailed = () => new UserError("proxy_failed", "Could not make the preview proxy.");
interface ProxyJobs {
jobs: Record<string, ProxyState>;
@@ -181,7 +185,7 @@ export async function ensureProxy(
const live = useEditor.getState().assets.find((a) => a.id === asset.id);
if (ask.kind === "compat" && live) void enrichAsset(live);
} catch (e) {
- jobs.set(asset.id, { kind: "failed", error: e instanceof Error ? e.message : "Could not make the preview proxy." });
+ jobs.set(asset.id, { kind: "failed", ...errorFields(e, proxyFailed()) });
}
} finally {
inFlight.delete(asset.id);
@@ -307,16 +311,16 @@ async function requestProxy(
body: JSON.stringify(body),
});
const started = (await res.json().catch(() => ({}))) as Partial<Landed> & { jobId?: string; error?: string };
- if (!res.ok) throw new Error(started.error ?? "Could not make the preview proxy.");
+ if (!res.ok) throw errorFromBody(started, proxyFailed());
if (started.fileName && typeof started.sizeBytes === "number") {
return { fileName: started.fileName, sizeBytes: started.sizeBytes };
}
- if (backend.kind !== "cloud" || !started.jobId) throw new Error(started.error ?? "Could not make the preview proxy.");
- const result = await pollCloudJob<Partial<Landed>>(started.jobId, backend, "Could not make the preview proxy.", {
- timedOut: "The preview proxy took too long.",
+ if (backend.kind !== "cloud" || !started.jobId) throw errorFromBody(started, proxyFailed());
+ const result = await pollCloudJob<Partial<Landed>>(started.jobId, backend, proxyFailed(), {
+ timedOut: new UserError("proxy_too_slow", "The preview proxy took too long."),
onProgress,
});
- if (!result.fileName || typeof result.sizeBytes !== "number") throw new Error("Could not make the preview proxy.");
+ if (!result.fileName || typeof result.sizeBytes !== "number") throw proxyFailed();
return { fileName: result.fileName, sizeBytes: result.sizeBytes };
}
diff --git a/site/src/cut/lib/micTranscribe.ts b/site/src/cut/lib/micTranscribe.ts
index 0abc3227..1ba6e955 100644
--- a/site/src/cut/lib/micTranscribe.ts
+++ b/site/src/cut/lib/micTranscribe.ts
@@ -5,6 +5,7 @@ import { confirmEngine } from "./api";
import { hasLocalCompute } from "./backend";
import { localBackend } from "./backend/local";
import { cloudTranscribeRecording } from "./cloudTranscribe";
+import { errorFromBody, UserError } from "./userError";
// Live dictation for the chat composer. The browser holds the mic permission,
// so capture happens in the page, and the transcription runs wherever it can.
@@ -101,7 +102,9 @@ export interface MicController {
stream: MediaStream | null;
/** Evolving transcript while recording. */
partial: string;
- error: string | null;
+ /** Why the last dictation ended, worded by the panel: a coded UserError
+ * (errors catalog) or the engine's or browser's own error. */
+ error: Error | null;
/** Begin capturing + transcribing. */
start: () => Promise<void>;
/** Finish, resolve the final transcript, and hand it to `onResult`. */
@@ -114,7 +117,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
const [state, setState] = useState<MicState>("idle");
const [stream, setStream] = useState<MediaStream | null>(null);
const [partial, setPartial] = useState("");
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<Error | null>(null);
const jobRef = useRef<string | null>(null);
/** Which transcriber this dictation is on; a run that loses the engine flips
@@ -201,7 +204,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
* engine never holds a session nothing is feeding and the user is never left
* watching an empty transcript. */
const fail = useCallback(
- (message: string) => {
+ (message: Error) => {
const job = jobRef.current;
jobRef.current = null;
if (job) void localBackend.fetch(`/api/cut/mic/${job}/cancel`, { method: "POST" }).catch(() => {});
@@ -220,7 +223,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
if (silenceTimer.current) clearTimeout(silenceTimer.current);
silenceTimer.current = setTimeout(() => {
if (gotAudioRef.current) return;
- fail("No audio is reaching Donkey from this microphone. Check the input device and try again.");
+ fail(new UserError("mic_no_audio", "No audio is reaching Donkey from this microphone. Check the input device and try again."));
}, FIRST_AUDIO_MS);
}, [fail]);
@@ -241,7 +244,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
recorderRef.current = null;
// The engine is still transcribing this one; only a dictation the
// recording *was* has nothing left to finish with.
- if (modeRef.current === "hosted") fail("The browser stopped recording the microphone.");
+ if (modeRef.current === "hosted") fail(new UserError("mic_recording_stopped", "The browser stopped recording the microphone."));
};
rec.start(RECORDER_SLICE_MS);
recorderRef.current = rec;
@@ -259,7 +262,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
* screen changes but the partial. Returns false when there was no recording
* to fall back on, in which case the dictation ended with `reason` shown. */
const degrade = useCallback(
- (reason: string): boolean => {
+ (reason: Error): boolean => {
if (!recorderRef.current) {
fail(reason);
return false;
@@ -300,14 +303,14 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
headers: { "Content-Type": "application/octet-stream" },
body: merged.buffer,
});
- if (!res.ok) throw new Error(`Donkey turned the audio away (${res.status}).`);
+ if (!res.ok) throw new UserError("mic_audio_refused", `Donkey turned the audio away (${res.status}).`, { status: res.status });
failuresRef.current = 0;
} catch (e) {
// A dropped chunk just shortens the transcript; a run of them means the
// engine is no longer taking this dictation, and the recording takes over.
failuresRef.current += 1;
if (failuresRef.current >= MAX_FEED_FAILURES) {
- degrade(e instanceof Error ? e.message : "Donkey stopped receiving the audio.");
+ degrade(e instanceof Error ? e : new UserError("mic_feed_stopped", "Donkey stopped receiving the audio."));
}
} finally {
feedingRef.current = false;
@@ -346,7 +349,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
}
// A session that died — a locale with no model on this Mac, a process
// that quit — has no transcript coming; the recording carries it instead.
- if (data.status === "error") degrade(data.error || "Dictation stopped on this Mac.");
+ if (data.status === "error") degrade(errorFromBody(data, new UserError("mic_engine_stopped", "Dictation stopped on this Mac.")));
} catch {
// Transient poll failure; the next tick retries. An engine that is gone
// shows up in the feeds, which are what carry the audio.
@@ -380,7 +383,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
const ctx = new AudioContext();
ctxRef.current = ctx;
await ctx.resume();
- if (ctx.state !== "running") throw new Error("This page is not allowed to capture audio right now.");
+ if (ctx.state !== "running") throw new UserError("mic_capture_denied", "This page is not allowed to capture audio right now.");
const url = URL.createObjectURL(new Blob([PCM_WORKLET], { type: "text/javascript" }));
try {
await ctx.audioWorklet.addModule(url);
@@ -411,12 +414,12 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
// instead of on a transcript that quietly stopped growing.
ctx.onstatechange = () => {
if (ctxRef.current === ctx && ctx.state !== "running") {
- degrade("The browser stopped audio capture for this page.");
+ degrade(new UserError("mic_capture_stopped", "The browser stopped audio capture for this page."));
}
};
return true;
} catch (e) {
- return degrade(e instanceof Error ? e.message : "This browser could not capture the microphone.");
+ return degrade(e instanceof Error ? e : new UserError("mic_capture_failed", "This browser could not capture the microphone."));
}
},
[degrade]
@@ -433,7 +436,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
media = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch {
setState("idle");
- setError("Microphone access was blocked. Allow the microphone for this site, then try again.");
+ setError(new UserError("mic_blocked", "Microphone access was blocked. Allow the microphone for this site, then try again."));
return;
}
streamRef.current = media;
@@ -450,7 +453,7 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
if (modeRef.current === "hosted" && !recording) {
teardownAudio();
setState("idle");
- setError("This browser could not record the microphone.");
+ setError(new UserError("mic_no_recorder", "This browser could not record the microphone."));
return;
}
setStream(media);
@@ -518,13 +521,13 @@ export function useMicTranscription(onResult: (text: string) => void): MicContro
recChunksRef.current = [];
teardownAudio();
if (blob.size === 0) {
- setError("Nothing was recorded from the microphone.");
+ setError(new UserError("mic_nothing_recorded", "Nothing was recorded from the microphone."));
return "";
}
try {
return await cloudTranscribeRecording(blob, navigator.language);
} catch (e) {
- setError(e instanceof Error ? e.message : "Transcription failed.");
+ setError(e instanceof Error ? e : new UserError("mic_transcription_failed", "Transcription failed."));
// Whatever the engine had said before it dropped out beats nothing.
return partialRef.current;
}
diff --git a/site/src/cut/lib/network.ts b/site/src/cut/lib/network.ts
index 4818054b..a023e0d4 100644
--- a/site/src/cut/lib/network.ts
+++ b/site/src/cut/lib/network.ts
@@ -2,6 +2,8 @@
// browser connection state and reads as online: its network failures surface
// as the errors they are.
+import { UserError } from "./userError";
+
/** True while the browser says it has no connection. */
export function isOffline(): boolean {
return globalThis.navigator?.onLine === false;
@@ -12,8 +14,9 @@ export function onReconnect(work: () => void): void {
globalThis.addEventListener?.("online", work);
}
-/** A request the connection dropped: no answer came back at all. */
-export class ConnectionLostError extends Error {}
+/** A request the connection dropped: no answer came back at all. It carries
+ * the code of the failure the person reads, e.g. `upload_failed`. */
+export class ConnectionLostError extends UserError {}
/** Whether `err` is fetch giving up on the network, by the TypeError every
* browser throws for it, e.g. Chrome's "Failed to fetch", or Firefox's "Error
diff --git a/site/src/cut/lib/noteOutbox.ts b/site/src/cut/lib/noteOutbox.ts
index 6327ecb8..f76c8ae0 100644
--- a/site/src/cut/lib/noteOutbox.ts
+++ b/site/src/cut/lib/noteOutbox.ts
@@ -24,6 +24,7 @@ import { confirmedEngineUser, currentEngineUser } from "./api";
import type { NoteLocation } from "./noteReference";
import { backendFor } from "./residency";
import type { CutNote } from "./notes";
+import { UserError } from "./userError";
/** One note as a write sends it. */
export interface NoteWrite {
@@ -201,7 +202,7 @@ async function send(note: NoteWrite, updatedAt: number, mode: SendMode): Promise
export async function sendNoteNow(note: NoteWrite): Promise<CutNote> {
const sent = await send(note, Date.now(), "now");
if (sent.kind !== "landed") {
- throw new Error("Could not save the note.");
+ throw new UserError("note_save_failed", "Could not save the note.");
}
return sent.note;
}
@@ -231,7 +232,7 @@ export async function flushNote(id: string, mode: SendMode = "now"): Promise<Cut
writePending(account, id, null);
}
if (sent.kind === "refused") {
- throw new Error("Could not save the note.");
+ throw new UserError("note_save_failed", "Could not save the note.");
}
retryStep = 0;
return sent.note;
diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.ts
index e96b6905..242a543f 100644
--- a/site/src/cut/lib/notes.ts
+++ b/site/src/cut/lib/notes.ts
@@ -13,9 +13,11 @@
*/
import { noteReadSchema, noteSaveSchema, parseNoteLink, type NoteLocation } from "@/cut/lib/noteReference";
+import { creatorNames } from "./defaultNames";
import { settleParents } from "./folderTree";
import { dropPendingNote, flushNote, sendNoteNow, stageNote, withPendingNotes, type NoteWrite } from "./noteOutbox";
import { backendFor } from "./residency";
+import { UserError } from "./userError";
export { folderTrail, folderWithin, subtreeOf } from "./folderTree";
@@ -84,7 +86,7 @@ const json = (body: unknown): RequestInit => ({
* off a folder nobody can open. */
export async function fetchNotes(): Promise<NotesData> {
const res = await notesFetch("/api/cut/notes");
- if (!res.ok) throw new Error("Could not load notes.");
+ if (!res.ok) throw new UserError("notes_load_failed", "Could not load notes.");
const body = (await res.json()) as Partial<NotesData>;
return {
notes: withPendingNotes(body.notes ?? []).filter((n) => n.deletedAt === null),
@@ -107,7 +109,7 @@ export async function writeNoteFromTool(raw: unknown): Promise<CutNote> {
const { id, ...changes } = input;
const prior = id ? await readNote({ id }) : null;
if (!prior && !input.title?.trim() && !input.body?.trim()) throw new Error("A new note needs a title or body.");
- return saveNote({ id: prior?.id ?? crypto.randomUUID(), title: prior?.title ?? "Untitled", body: prior?.body ?? "",
+ return saveNote({ id: prior?.id ?? crypto.randomUUID(), title: prior?.title ?? creatorNames().untitled, body: prior?.body ?? "",
colorIndex: prior?.colorIndex ?? 0, folderId: prior?.folderId ?? null, labelIds: prior?.labelIds ?? [],
...(prior ? {} : { libraryLocation: null }), ...changes });
}
@@ -121,7 +123,7 @@ export async function saveNote(note: NoteWrite): Promise<CutNote> {
return sendNoteNow(note);
}
const saved = await flushNote(note.id);
- if (!saved) throw new Error("Could not save the note.");
+ if (!saved) throw new UserError("note_save_failed", "Could not save the note.");
return saved;
}
@@ -130,7 +132,7 @@ export async function deleteNote(id: string): Promise<void> {
const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(id)}`, {
method: "DELETE",
});
- if (!res.ok) throw new Error("Could not delete the note.");
+ if (!res.ok) throw new UserError("note_delete_failed", "Could not delete the note.");
}
/** Create, rename or move a folder under `id`. A create mints the id here so
@@ -145,7 +147,7 @@ export async function saveNoteFolder(
`/api/cut/notes/folders/${encodeURIComponent(id)}`,
json(folder),
);
- if (!res.ok) throw new Error("Could not save the folder.");
+ if (!res.ok) throw new UserError("note_folder_save_failed", "Could not save the folder.");
return (await res.json()) as CutNoteFolder;
}
@@ -156,7 +158,7 @@ export async function deleteLibraryFolderNotes(residency: "browser" | "local", f
...json({ residency, folderIds }),
method: "POST",
});
- if (!res.ok) throw new Error("Could not delete the folder’s notes.");
+ if (!res.ok) throw new UserError("note_folder_notes_delete_failed", "Could not delete the folder’s notes.");
}
/** Delete a folder and everything under it: its folders and their notes. */
@@ -164,7 +166,7 @@ export async function deleteNoteFolder(id: string): Promise<void> {
const res = await notesFetch(`/api/cut/notes/folders/${encodeURIComponent(id)}`, {
method: "DELETE",
});
- if (!res.ok) throw new Error("Could not delete the folder.");
+ if (!res.ok) throw new UserError("note_folder_delete_failed", "Could not delete the folder.");
}
/** Create or rename a label under `id`. A create mints the id here so the
@@ -174,7 +176,7 @@ export async function saveNoteLabel(id: string, name: string): Promise<CutNoteLa
`/api/cut/notes/labels/${encodeURIComponent(id)}`,
json({ name }),
);
- if (!res.ok) throw new Error("Could not save the label.");
+ if (!res.ok) throw new UserError("label_save_failed", "Could not save the label.");
return (await res.json()) as CutNoteLabel;
}
@@ -183,5 +185,5 @@ export async function deleteNoteLabel(id: string): Promise<void> {
const res = await notesFetch(`/api/cut/notes/labels/${encodeURIComponent(id)}`, {
method: "DELETE",
});
- if (!res.ok) throw new Error("Could not delete the label.");
+ if (!res.ok) throw new UserError("label_delete_failed", "Could not delete the label.");
}
diff --git a/site/src/cut/lib/pi/cutAgent.test.ts b/site/src/cut/lib/pi/cutAgent.test.ts
index 623cf65b..631cbf90 100644
--- a/site/src/cut/lib/pi/cutAgent.test.ts
+++ b/site/src/cut/lib/pi/cutAgent.test.ts
@@ -133,7 +133,7 @@ describe("the quality gate in the turn loop", () => {
dropPiSession(threadId);
const h = harness({ gateVerdicts: [0.1, 0.9] });
await drain(
- streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), deps: h.deps })
+ streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), locale: "en", deps: h.deps })
);
// Round 1 watched, round 2 tried to close and was held, round 3 closed.
expect(h.roundsUsed()).toBe(3);
@@ -160,7 +160,7 @@ describe("the quality gate in the turn loop", () => {
dropPiSession(threadId);
const h = harness({ gateVerdicts: [0.95] });
await drain(
- streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), deps: h.deps })
+ streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), locale: "en", deps: h.deps })
);
expect(h.roundsUsed()).toBe(2);
expect(h.judgeAsks.filter((q) => q.includes("finished")).length).toBe(1);
@@ -176,7 +176,7 @@ describe("the quality gate in the turn loop", () => {
});
h.deps.execTool = async () => ({ id: "c1", muted: true });
await drain(
- streamCutChat({ threadId, model: "chat", messages: ask("mute the first clip"), deps: h.deps })
+ streamCutChat({ threadId, model: "chat", messages: ask("mute the first clip"), locale: "en", deps: h.deps })
);
expect(h.roundsUsed()).toBe(2);
expect(h.judgeAsks.filter((q) => q.includes("finished")).length).toBe(0);
@@ -189,7 +189,7 @@ describe("the quality gate in the turn loop", () => {
const h = harness({ gateVerdicts: [0.01, 0.9], call: { name: "get_state", args: {} } });
h.deps.execTool = async () => ({ videoTrack: [], media: [] });
await drain(
- streamCutChat({ threadId, model: "chat", messages: ask("replicate this video"), deps: h.deps })
+ streamCutChat({ threadId, model: "chat", messages: ask("replicate this video"), locale: "en", deps: h.deps })
);
expect(h.judgeAsks.filter((q) => q.includes("finished")).length).toBe(1);
expect(JSON.stringify(h.modelPayloads[2])).toContain("Build it with tools now");
@@ -202,7 +202,7 @@ describe("the quality gate in the turn loop", () => {
const h = harness({ gateVerdicts: [0.01] });
h.deps.judgeSettings = { ...CUT_JUDGE, instantAction: false, qualityGate: false };
await drain(
- streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), deps: h.deps })
+ streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), locale: "en", deps: h.deps })
);
expect(h.roundsUsed()).toBe(2);
expect(h.judgeAsks.filter((q) => q.includes("finished")).length).toBe(0);
diff --git a/site/src/cut/lib/pi/cutAgent.ts b/site/src/cut/lib/pi/cutAgent.ts
index e12a9556..645f4fd8 100644
--- a/site/src/cut/lib/pi/cutAgent.ts
+++ b/site/src/cut/lib/pi/cutAgent.ts
@@ -1,4 +1,5 @@
import type { UIMessage, UIMessageChunk } from "ai";
+import type { Locale } from "@/i18n/locales";
import { Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
import type { Message, UserMessage } from "@earendil-works/pi-ai";
import type { AgentTool } from "@earendil-works/pi-agent-core";
@@ -675,12 +676,15 @@ export function streamCutChat({
threadId,
model,
messages,
+ locale,
abortSignal,
deps,
}: {
threadId: string;
model: string;
messages: UIMessage[];
+ /** The person's interface language; replies are written in it. */
+ locale: Locale;
abortSignal?: AbortSignal;
deps: CutAgentDeps;
}): ReadableStream<UIMessageChunk> {
@@ -786,7 +790,7 @@ export function streamCutChat({
const agent = new Agent({
initialState: {
- systemPrompt: systemPrompt(),
+ systemPrompt: systemPrompt(locale),
model: donkeyModel(roundModel, thinkingLevel),
messages: sessionFor(threadId, messages.filter((m) => m !== lastUser)),
tools,
diff --git a/site/src/cut/lib/projectCopy.ts b/site/src/cut/lib/projectCopy.ts
index 6778de99..1c6a417a 100644
--- a/site/src/cut/lib/projectCopy.ts
+++ b/site/src/cut/lib/projectCopy.ts
@@ -12,6 +12,7 @@ import { uploadProjectMediaTo } from "./media";
import { localMediaFile } from "./mediaSync";
import type { ProjectDoc, StoredAsset } from "./types";
import { compatCoverOf } from "./proxyNames";
+import { UserError } from "./userError";
/** Move a project's conversations onto the copy.
*
@@ -52,7 +53,7 @@ export async function copyProjectAcross(
let created: string | null = null;
try {
const docRes = await src.fetch(`/api/cut/projects/${projectId}`);
- if (!docRes.ok) throw new Error("Could not read the project.");
+ if (!docRes.ok) throw new UserError("project_read_failed", "Could not read the project.");
const doc = (await docRes.json()) as ProjectDoc;
const name = opts.rename ? opts.rename(doc.name ?? "") : (doc.name ?? "");
const createRes = await dst.fetch("/api/cut/projects", {
@@ -61,7 +62,7 @@ export async function copyProjectAcross(
body: JSON.stringify({ name }),
});
const summary = (await createRes.json()) as { id?: string };
- if (!createRes.ok || !summary.id) throw new Error("Could not create the project.");
+ if (!createRes.ok || !summary.id) throw new UserError("project_creation_failed", "Could not create the project.");
created = summary.id;
const assets = Array.isArray(doc.assets) ? doc.assets : [];
const names = new Map<string, string>();
@@ -90,7 +91,7 @@ export async function copyProjectAcross(
const bytes = await src.fetch(
`/api/cut/projects/${projectId}/media/${encodeURIComponent(f.fileName)}`
);
- if (!bytes.ok) throw new Error(`Could not read “${f.name}”.`);
+ if (!bytes.ok) throw new UserError("media_read_failed", `Could not read “${f.name}”.`, { name: f.name });
blob = await bytes.blob();
}
names.set(f.fileName, await uploadProjectMediaTo(dst, summary.id, blob, f.fileName));
@@ -121,7 +122,7 @@ export async function copyProjectAcross(
headers: { "Content-Type": "application/json" },
body: JSON.stringify(copied),
});
- if (!putRes.ok) throw new Error("Could not save the project.");
+ if (!putRes.ok) throw new UserError("project_doc_save_failed", "Could not save the project.");
await copyChatThreads(src, dst, projectId, summary.id);
if (!carryProxies) {
// The worker builds the proxies the copy left behind; the editor writes
diff --git a/site/src/cut/lib/projectList.test.tsx b/site/src/cut/lib/projectList.test.tsx
index 29786967..568a93eb 100644
--- a/site/src/cut/lib/projectList.test.tsx
+++ b/site/src/cut/lib/projectList.test.tsx
@@ -9,6 +9,7 @@ import { projectDocRef } from "./projectLink";
import { listOwnProjects, setHostDocStore } from "./projectReference";
import { useEditor } from "./store";
import type { ProjectSummary } from "./types";
+import { WithIntl } from "@/i18n/testing";
// Another project reaches the assistant two ways: an @ attachment that
// carries its id, or a title the model looks up with list_projects.
@@ -98,7 +99,11 @@ describe("a project attachment", () => {
});
test("reads as a pill that opens the project in a new tab", () => {
- const html = renderToStaticMarkup(<UnmentionedRefPills text="copy its styles" refs={[ref]} />);
+ const html = renderToStaticMarkup(
+ <WithIntl>
+ <UnmentionedRefPills text="copy its styles" refs={[ref]} />
+ </WithIntl>,
+ );
expect(html).toContain("Projects / Graphics Ref");
expect(html).toContain("/p/gfx");
expect(html).toContain("target=\"_blank\"");
diff --git a/site/src/cut/lib/projectOperation.ts b/site/src/cut/lib/projectOperation.ts
index 47e52ac6..30d50cf8 100644
--- a/site/src/cut/lib/projectOperation.ts
+++ b/site/src/cut/lib/projectOperation.ts
@@ -2,6 +2,7 @@ import { getBackend, type CutBackend, type CutCaps, type CutMode } from "@/cut/l
import { captureCloudBackend, cloudBackend, knownDocVersion } from "@/cut/lib/backend/cloud";
import { captureLocalBackend, localBackend } from "@/cut/lib/backend/local";
import { projectRevision } from "@/cut/lib/projectRevision";
+import { UserError } from "@/cut/lib/userError";
/** Execution context captured before asynchronous work starts. Server routes
* remain responsible for authenticating and authorizing every request. */
@@ -14,7 +15,7 @@ export type ProjectOperation = {
};
export function projectOperation(projectId: string, backend = getBackend()): ProjectOperation {
- if (backend.kind === "shared") throw new Error("A shared project is read-only.");
+ if (backend.kind === "shared") throw new UserError("project_read_only", "A shared project is read-only.");
const captured = backend === cloudBackend ? captureCloudBackend() : backend === localBackend ? captureLocalBackend() : backend;
return {
projectId, backend: captured, residency: captured.kind,
diff --git a/site/src/cut/lib/proxyEncode.ts b/site/src/cut/lib/proxyEncode.ts
index c388419f..b372d1ad 100644
--- a/site/src/cut/lib/proxyEncode.ts
+++ b/site/src/cut/lib/proxyEncode.ts
@@ -30,6 +30,7 @@ import { audioTrackOf, openMedia, probeMediaFile, videoTrackOf } from "./mediaRe
import { encoderLead } from "./encoderLead";
import { ensureProresDecoder } from "./proresDecoder";
import { convertPlanes, isPlanarFormat, planesPassThrough, proxySize } from "./proxyPlanes";
+import { errorFromBody, UserError } from "./userError";
/** The proxy's file name beside its master (server/proxy.ts `proxyNameFor`). */
export const proxyNameFor = (fileName: string) =>
@@ -183,7 +184,7 @@ export async function encodeProxyInPage(
const file = await handle.getFile();
const probe = await probeMediaFile(file);
const want = rotated % 180 === 0 ? target.width : target.height;
- if (!probe.hasVideo || probe.width !== want) throw new Error("The preview proxy did not read back.");
+ if (!probe.hasVideo || probe.width !== want) throw new UserError("proxy_readback_failed", "The preview proxy did not read back.");
landed = true;
onProgress(1);
return { fileName, sizeBytes: file.size };
@@ -252,8 +253,8 @@ export async function proxyOnTheMac(
if (compat) form.append("compat", compat);
const res = await engineFetch("/api/cut/proxy", { method: "POST", body: form });
if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { error?: string };
- throw new Error(body.error ?? "Could not make the preview proxy.");
+ const body: unknown = await res.json().catch(() => null);
+ throw errorFromBody(body, new UserError("proxy_failed", "Could not make the preview proxy."));
}
return res.blob();
}
diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.ts
index 11dc05c9..99c2234c 100644
--- a/site/src/cut/lib/refMedia.ts
+++ b/site/src/cut/lib/refMedia.ts
@@ -16,6 +16,7 @@ import { reportSwallowed } from "./report";
import { createRasterCanvas, rasterCanvasToDataUrl } from "./raster";
import { useEditor } from "./store";
import { formatTime } from "./time";
+import { UserError } from "./userError";
// Turn refs and dropped files into what the hosted models take. Generation
// routes read `inputs.images = [{ data, mimeType }]`: stock images upload
@@ -152,7 +153,7 @@ export async function videoSafeInline(img: InlineImage): Promise<InlineImage> {
if (img.mimeType === "image/jpeg" || img.mimeType === "image/png") return img;
const blob = await (await fetch(`data:${img.mimeType};base64,${img.data}`)).blob();
const fitted = await encodeWithin(blob);
- if (!fitted) throw new Error("A reference image is in a format the video model can't read.");
+ if (!fitted) throw new UserError("ref_format_unreadable", "A reference image is in a format the video model can't read.");
return fitted;
}
@@ -175,9 +176,9 @@ async function readRefBytes(ref: AssetRef): Promise<Blob> {
// A rejected fetch never reached a server: DNS, CORS, mixed content, or a
// refused connection.
const why = err instanceof Error ? err.message : String(err);
- throw new Error(`Could not reach “${ref.name}” at ${where} — ${why}.`);
+ throw new UserError("ref_unreachable", `Could not reach “${ref.name}” at ${where} — ${why}.`, { name: ref.name, where, why });
}
- if (!res.ok) throw new Error(`Could not load “${ref.name}” — ${res.status} from ${where}.`);
+ if (!res.ok) throw new UserError("ref_load_failed", `Could not load “${ref.name}” — ${res.status} from ${where}.`, { name: ref.name, status: res.status, where });
return res.blob();
}
@@ -217,7 +218,10 @@ async function captureFrame(
const input = openMedia(url);
try {
const track = await videoTrackOf(input);
- if (!track) throw new Error(`Could not read ${mediaAddress(url)} for a reference frame.`);
+ if (!track) {
+ const where = mediaAddress(url);
+ throw new UserError("ref_frame_unreadable", `Could not read ${where} for a reference frame.`, { where });
+ }
const dur = duration || (await input.computeDuration()) || 2;
// A pinned moment reads exactly there (kept inside the source); otherwise
// the same poster spot the cards show, so the reference matches the preview.
@@ -227,7 +231,7 @@ async function captureFrame(
: Math.min(1, Math.max(0.1, dur / 10));
const width = Math.min(opts?.width ?? MAX_W, await track.getDisplayWidth());
const frame = await frameSink(track, { width }).getCanvas(at);
- if (!frame) throw new Error("The video has no readable frame.");
+ if (!frame) throw new UserError("video_frame_unreadable", "The video has no readable frame.");
const canvas = frame.canvas;
return splitDataUrl(
canvas instanceof OffscreenCanvas
@@ -251,7 +255,7 @@ const sourceDuration = (ref: AssetRef): number | undefined =>
* spot otherwise. Audio and text have no picture and reject. */
export async function refToInlineImage(ref: AssetRef): Promise<InlineImage> {
if (ref.kind === "audio" || ref.kind === "text") {
- throw new Error(`“${ref.name}” has no picture — it can't be a visual reference.`);
+ throw new UserError("ref_no_picture", `“${ref.name}” has no picture — it can't be a visual reference.`, { name: ref.name });
}
if (ref.kind === "image") return blobToInline(await readRefBytes(ref));
return captureFrame(ref.url, sourceDuration(ref), ref.t !== undefined ? { at: ref.t } : undefined);
@@ -280,7 +284,7 @@ export async function copyRefImage(ref: AssetRef): Promise<void> {
canvas.getContext("2d")!.drawImage(bitmap, 0, 0);
bitmap.close();
return new Promise<Blob>((resolve, reject) =>
- canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Could not encode the frame."))), "image/png")
+ canvas.toBlob((b) => (b ? resolve(b) : reject(new UserError("frame_encode_failed", "Could not encode the frame."))), "image/png")
);
})();
await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);
@@ -339,7 +343,7 @@ export async function refsFromDroppedFiles(
/** A text ref's contents (a dropped script, notes, subtitles…). */
export async function readRefText(ref: AssetRef): Promise<string> {
const res = await fetch(ref.url);
- if (!res.ok) throw new Error(`Could not read “${ref.name}”.`);
+ if (!res.ok) throw new UserError("media_read_failed", `Could not read “${ref.name}”.`, { name: ref.name });
return res.text();
}
diff --git a/site/src/cut/lib/removal/bakeJobs.ts b/site/src/cut/lib/removal/bakeJobs.ts
index 93521765..6d991c8d 100644
--- a/site/src/cut/lib/removal/bakeJobs.ts
+++ b/site/src/cut/lib/removal/bakeJobs.ts
@@ -32,6 +32,7 @@ import { removalFingerprint, type ClipRemoval, type VideoClip } from "../types";
import { useBrushUi } from "./brushUi";
import { hostedBakeMatte, type HostedBakeTicket } from "./hostedBake";
import { localBakeMatte, MatteBakeCancelled } from "./localBake";
+import { UserError, errorFields, type UserErrorParams } from "../userError";
type MatteQuality = "local" | "hq";
@@ -77,6 +78,8 @@ export interface MatteBakeJob {
* estimate has nothing to stand on yet. */
startedAt?: number;
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
}
interface MatteBakes {
@@ -366,7 +369,7 @@ function ensureBake(clipId: string, slot: MatteSlot, opts: { whileBrushing?: boo
quality: want,
status: "error",
progress: 0,
- error: e instanceof Error ? e.message : "The matte could not be baked.",
+ ...errorFields(e instanceof Error ? e : null, new UserError("matte_bake_failed", "The matte could not be baked.")),
});
});
}
@@ -442,7 +445,9 @@ async function runBakeNow(
const file = new File([baked.blob], `matte-${quality}-${fp}.mp4`, { type: "video/mp4" });
const matteAsset = await importFileToProject(state.projectId, file);
- if (!matteAsset) throw new Error("The matte could not be saved into the project.");
+ if (!matteAsset) {
+ throw new UserError("matte_save_failed", "The matte could not be saved into the project.");
+ }
matteAsset.name = `${asset.name} matte`;
matteAsset.origin = "matte";
diff --git a/site/src/cut/lib/removal/hostedBake.ts b/site/src/cut/lib/removal/hostedBake.ts
index 9c645de5..c344320d 100644
--- a/site/src/cut/lib/removal/hostedBake.ts
+++ b/site/src/cut/lib/removal/hostedBake.ts
@@ -30,8 +30,8 @@ import {
refineMatteAgainstFrame,
} from "@donkeycut/effects-kit";
import { openCanvasVideo, scaledEvenSize, type CanvasVideoEncoder } from "../canvasVideo";
-import { NO_CREDITS_MESSAGE } from "../credits";
import { ClipReader } from "../exportRender";
+import { NoCreditsError } from "../hostedError";
import { hostedPost } from "../hosted";
import { storeHostedBlob } from "../hostedBlobs";
import { falMatteModels } from "@/lib/inference/matte-models";
@@ -39,6 +39,7 @@ import { createRasterCanvas, decodeRasterImageUrl, type RasterSurface } from "..
import type { MediaAsset, RemovalSeeds, VideoClip } from "../types";
import { liveReader } from "../liveReader";
import { MatteBakeCancelled } from "./localBake";
+import { UserError } from "../userError";
/** Segment sent to the tracker: capped resolution and rate — the mask comes
* back at the same shape, and tracking cost scales with both. The bitrate
@@ -55,18 +56,19 @@ const CARRY_POINTS_MAX = 6;
/** The hosted tier answered 402: credits unlock it, the local matte stands.
* Carries the app-wide balance message so every surface renders it the same
* way, with the credits link. */
-export class MatteNeedsCredits extends Error {
- constructor() {
- super(NO_CREDITS_MESSAGE);
- }
-}
+export class MatteNeedsCredits extends NoCreditsError {}
/** The tracker settled a generation as failed — the charge is spent and the
* track is dead. The run forgets the dead part in the ticket it reports, so
* a retry re-buys that piece alone and resumes the rest. Transient errors
* (a poll that couldn't reach the route) throw plain errors instead, and
* the whole ticket stands for a resume. */
-export class MatteTrackFailed extends Error {}
+export class MatteTrackFailed extends Error {
+ /** What the person reads: the tracker's own words, or a coded failure. */
+ constructor(readonly reason: Error) {
+ super(reason.message);
+ }
+}
type Point = { x: number; y: number; frame: number; label: 0 | 1; object: string };
@@ -101,7 +103,9 @@ async function renderSegment(
onProgress?: (fraction: number) => void
): Promise<{ blob: Blob; from: number; w: number; h: number; frames: number }> {
const first = await reader.frameAt(from);
- if (first.kind !== "ready") throw new Error("The clip's picture could not be read.");
+ if (first.kind !== "ready") {
+ throw new UserError("clip_picture_unreadable", "The clip's picture could not be read.");
+ }
const { w, h } = scaledEvenSize(first.width, first.height, SEGMENT_SHORT);
const seconds = frames / MATTE_FPS;
const enc = await openCanvasVideo({
@@ -280,7 +284,9 @@ async function pollTrack(
const deadline = Date.now() + DEADLINE_MS;
while (gen.status === "in_progress" || gen.status === "pending") {
checkAborted(opts.signal);
- if (Date.now() > deadline) throw new Error("The quality cutout is taking too long.");
+ if (Date.now() > deadline) {
+ throw new UserError("matte_cutout_timeout", "The quality cutout is taking too long.");
+ }
await new Promise((r2) => setTimeout(r2, POLL_MS));
checkAborted(opts.signal);
const poll = await hostedPost("/api/inference/assets/refresh", {
@@ -293,19 +299,24 @@ async function pollTrack(
providerPollingUrl: gen.providerPollingUrl,
metadata: gen.metadata ?? {},
});
- if (!poll.ok) throw new Error("The quality cutout failed.");
+ if (!poll.ok) {
+ throw new UserError("matte_cutout_failed", "The quality cutout failed.");
+ }
gen = (await poll.json()) as Generation;
onFrac(Math.min(1, 1 - (deadline - Date.now()) / DEADLINE_MS));
}
if (gen.status !== "completed") {
- const message =
- typeof (gen.error as { message?: string } | undefined)?.message === "string"
- ? (gen.error as { message: string }).message
- : "The quality cutout failed.";
- throw new MatteTrackFailed(message);
+ const message = (gen.error as { message?: string } | undefined)?.message;
+ throw new MatteTrackFailed(
+ typeof message === "string"
+ ? new Error(message)
+ : new UserError("matte_cutout_failed", "The quality cutout failed."),
+ );
}
const maskUrl = gen.outputs.find((o) => o.url)?.url;
- if (!maskUrl) throw new MatteTrackFailed("The tracker returned no mask.");
+ if (!maskUrl) {
+ throw new MatteTrackFailed(new UserError("matte_tracker_no_mask", "The tracker returned no mask."));
+ }
return maskUrl;
}
@@ -340,7 +351,9 @@ async function refinePart(
let localUrl: string | null = null;
if (typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
const got = await fetch(maskUrl).catch(() => null);
- if (!got?.ok) throw new Error("The tracked mask could not be downloaded.");
+ if (!got?.ok) {
+ throw new UserError("matte_mask_download_failed", "The tracked mask could not be downloaded.");
+ }
localUrl = URL.createObjectURL(await got.blob());
}
const readUrl = localUrl ?? maskUrl;
@@ -354,7 +367,9 @@ async function refinePart(
const maskReader = new ClipReader(maskAsset, () => readUrl);
try {
const firstMask = await maskReader.frameAt(0);
- if (firstMask.kind !== "ready") throw new Error("The tracked mask could not be read.");
+ if (firstMask.kind !== "ready") {
+ throw new UserError("matte_mask_unreadable", "The tracked mask could not be read.");
+ }
let s = sink.current;
if (!s) {
const { w, h } = scaledEvenSize(firstMask.width, firstMask.height, MATTE_SHORT);
@@ -424,7 +439,7 @@ async function refinePart(
/**
* Run the hosted quality bake for a clip and return the refined matte, ready
* to store as the project's matte asset. Throws `MatteNeedsCredits` on a 402,
- * `MatteTrackFailed` when the tracker settled a paid run as dead, and
+ * the tracker's reason when it settled a paid run as dead, and
* `MatteBakeCancelled` on abort. Each part's submit bills, so the caller
* persists the ticket handed to `onSubmitted` and passes it back as `resume`
* after a reload — the run then re-attaches to every submitted part and pays
@@ -441,7 +456,9 @@ export async function hostedBakeMatte(
} = {}
): Promise<{ blob: Blob; in: number }> {
const r = clip.removal;
- if (!r) throw new Error("The clip has no removal to bake.");
+ if (!r) {
+ throw new UserError("matte_no_removal", "The clip has no removal to bake.");
+ }
const still = asset.type === "image";
const from = still ? 0 : Math.max(0, clip.in);
const to = still ? from + 1 / MATTE_FPS : Math.min(clip.out, asset.duration || clip.out);
@@ -501,8 +518,8 @@ export async function hostedBakeMatte(
}
if (custom && !concept && points.length === 0) {
throw p === 0
- ? new Error("No selection to track.")
- : new MatteTrackFailed("The selection was lost at a part boundary.");
+ ? new UserError("matte_no_selection", "No selection to track.")
+ : new UserError("matte_selection_lost", "The selection was lost at a part boundary.");
}
const parameters = {
...(concept ? { prompt: concept } : {}),
@@ -511,7 +528,9 @@ export async function hostedBakeMatte(
checkAborted(opts.signal);
const blobRef = await storeHostedBlob(segment.blob, "donkey-cut");
- if (!blobRef) throw new Error("The segment could not reach storage.");
+ if (!blobRef) {
+ throw new UserError("matte_segment_upload_failed", "The segment could not reach storage.");
+ }
frac(0.2);
const submit = await hostedPost("/api/inference/assets", {
@@ -524,7 +543,9 @@ export async function hostedBakeMatte(
parameters,
});
if (submit.status === 402) throw new MatteNeedsCredits();
- if (!submit.ok) throw new Error("The quality cutout could not start.");
+ if (!submit.ok) {
+ throw new UserError("matte_cutout_start_failed", "The quality cutout could not start.");
+ }
gen = (await submit.json()) as Generation;
gens[p] = gen;
// The submit is the billable moment: from here the ticket outlives the
@@ -546,7 +567,7 @@ export async function hostedBakeMatte(
gens[p] = null;
opts.onSubmitted?.(ticket(Math.max(p + 1, gens.length)));
}
- throw e;
+ throw e instanceof MatteTrackFailed ? e.reason : e;
}
checkAborted(opts.signal);
const last = await refinePart(
@@ -562,9 +583,12 @@ export async function hostedBakeMatte(
}
const s = sink.current;
- if (!s) throw new MatteTrackFailed("The tracker returned no mask.");
+ if (!s) {
+ throw new UserError("matte_tracker_no_mask", "The tracker returned no mask.");
+ }
if (!s.lit) {
- throw new MatteTrackFailed(
+ throw new UserError(
+ "matte_tracker_found_nothing",
"The tracker found nothing to keep — describe the subject or paint it."
);
}
diff --git a/site/src/cut/lib/removal/localBake.ts b/site/src/cut/lib/removal/localBake.ts
index c175ee3e..caf74012 100644
--- a/site/src/cut/lib/removal/localBake.ts
+++ b/site/src/cut/lib/removal/localBake.ts
@@ -15,6 +15,7 @@ import { personSegmenter, segmentSubjectAlpha } from "../cutout";
import { createRasterCanvas } from "../raster";
import type { MediaAsset, VideoClip } from "../types";
import { liveReader } from "../liveReader";
+import { UserError } from "../userError";
export class MatteBakeCancelled extends Error {
constructor() {
@@ -35,7 +36,9 @@ export async function localBakeMatte(
opts: { onProgress?: (fraction: number) => void; signal?: AbortSignal } = {}
): Promise<{ blob: Blob; in: number }> {
const segmenter = await personSegmenter();
- if (!segmenter) throw new Error("On-device segmentation is unavailable in this browser.");
+ if (!segmenter) {
+ throw new UserError("segmentation_unavailable", "On-device segmentation is unavailable in this browser.");
+ }
const still = asset.type === "image";
const from = still ? 0 : Math.max(0, clip.in);
const to = still ? from + 1 / MATTE_FPS : Math.min(clip.out, asset.duration || clip.out);
@@ -45,7 +48,9 @@ export async function localBakeMatte(
const reader = liveReader(asset);
try {
const first = await reader.frameAt(from);
- if (first.kind !== "ready") throw new Error("The clip's picture could not be read.");
+ if (first.kind !== "ready") {
+ throw new UserError("clip_picture_unreadable", "The clip's picture could not be read.");
+ }
const { w, h } = scaledEvenSize(first.width, first.height, MATTE_SHORT);
const enc = await openCanvasVideo({
width: w,
diff --git a/site/src/cut/lib/removalVideo.ts b/site/src/cut/lib/removalVideo.ts
index 2e6389c5..1cdcdcf1 100644
--- a/site/src/cut/lib/removalVideo.ts
+++ b/site/src/cut/lib/removalVideo.ts
@@ -18,6 +18,7 @@ import { matteStage } from "./matteAlpha";
import { createRasterCanvas, decodeRasterImageUrl, type RasterSurface } from "./raster";
import { CLIP_MIN_SECONDS, type MediaAsset, type VideoClip } from "./types";
import { liveReader } from "./liveReader";
+import { UserError } from "./userError";
export interface RemovalPieces {
rgb: Blob;
@@ -81,7 +82,9 @@ export async function renderRemovalPieces(
const reader = liveReader(asset);
try {
const first = await reader.frameAt(still ? 0 : clip.in);
- if (first.kind !== "ready") throw new Error("The removal clip's picture could not be read.");
+ if (first.kind !== "ready") {
+ throw new UserError("removal_picture_unreadable", "The removal clip's picture could not be read.");
+ }
const { w, h } = scaledEvenSize(first.width, first.height, opts.maxShort);
const px = w * h;
const rgbOut = await openCanvasVideo({
@@ -104,7 +107,9 @@ export async function renderRemovalPieces(
const readCtx = readSurface.getContext("2d", {
willReadFrequently: true,
}) as CanvasRenderingContext2D | null;
- if (!readCtx) throw new Error("No drawing surface for the removal layer.");
+ if (!readCtx) {
+ throw new UserError("removal_surface_missing", "No drawing surface for the removal layer.");
+ }
// The compositor renders the layer with the preview's own code; its
// drawing canvas never draws, the scratches do the work.
diff --git a/site/src/cut/lib/sharingClient.ts b/site/src/cut/lib/sharingClient.ts
index cc382736..a9b504e9 100644
--- a/site/src/cut/lib/sharingClient.ts
+++ b/site/src/cut/lib/sharingClient.ts
@@ -1,6 +1,7 @@
import { cloudBackend } from "@/cut/lib/backend/cloud";
import { libraryShareApiPath, type LibraryShareTarget, type ShareSettings } from "@/cut/lib/librarySharing";
import type { ShareFeatures } from "@/cut/lib/types";
+import { UserError } from "@/cut/lib/userError";
export type ShareResource = { projectId: string } | { libraryTarget: LibraryShareTarget };
export type SharingSettings = ShareSettings & { features?: ShareFeatures };
@@ -15,6 +16,6 @@ export async function requestSharing(resource: ShareResource, method = "GET", se
...(settings ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(settings) } : {}),
cache: "no-store",
});
- if (!response.ok) throw new Error("Could not load or save sharing.");
+ if (!response.ok) throw new UserError("sharing_request_failed", "Could not load or save sharing.");
return await response.json() as { share: SharingState | null };
}
diff --git a/site/src/cut/lib/soundBind.ts b/site/src/cut/lib/soundBind.ts
index f11466b0..8834a71e 100644
--- a/site/src/cut/lib/soundBind.ts
+++ b/site/src/cut/lib/soundBind.ts
@@ -10,6 +10,7 @@ import { syncSourceSound } from "./media";
import { CUT_SOUND } from "./soundSettings";
import { useEditor } from "./store";
import { assetIsSilent, type MediaAsset } from "./types";
+import { UserError } from "./userError";
import { queueWatchSweep } from "./watch/sweep";
interface BoundSound {
@@ -39,12 +40,25 @@ export async function bindRecording(
const s = useEditor.getState();
const video = s.assets.find((a) => a.id === videoId);
const rec = s.assets.find((a) => a.id === audioId);
- if (!video || video.type !== "video") throw new Error("That video is no longer in the project.");
- if (!rec) throw new Error("That recording is no longer in the project.");
- if (rec.type !== "audio") throw new Error(`"${rec.name}" is not an audio file.`);
- if (assetIsSilent(video))
- throw new Error(`"${video.name}" has no sound of its own to line the recording up against.`);
- if (!(video.duration > 0) || !(rec.duration > 0)) throw new Error("Both files must finish importing first.");
+ if (!video || video.type !== "video") {
+ throw new UserError("sync_video_missing", "That video is no longer in the project.");
+ }
+ if (!rec) {
+ throw new UserError("sync_recording_missing", "That recording is no longer in the project.");
+ }
+ if (rec.type !== "audio") {
+ throw new UserError("sync_recording_not_audio", `"${rec.name}" is not an audio file.`, { name: rec.name });
+ }
+ if (assetIsSilent(video)) {
+ throw new UserError(
+ "sync_video_silent",
+ `"${video.name}" has no sound of its own to line the recording up against.`,
+ { name: video.name },
+ );
+ }
+ if (!(video.duration > 0) || !(rec.duration > 0)) {
+ throw new UserError("sync_files_importing", "Both files must finish importing first.");
+ }
const { syncProbeSeconds, syncMaxSeconds, syncMinConfidence } = CUT_SOUND;
const [cameraFrom, cameraTo] = probeWindow(video, syncProbeSeconds, near);
const answer = await syncSourceSound(video.url, rec.url, {
@@ -54,9 +68,18 @@ export async function bindRecording(
});
if (!answer || answer.confidence < syncMinConfidence) {
const read = answer ? ` (confidence ${answer.confidence.toFixed(2)}, needs ${syncMinConfidence})` : "";
- throw new Error(
- `No clear alignment between "${rec.name}" and "${video.name}"${read}. They may be different takes, or share too little sound.`
- );
+ const message = `No clear alignment between "${rec.name}" and "${video.name}"${read}. They may be different takes, or share too little sound.`;
+
+ // The weak-match line names the score it got and the score it needs.
+ if (answer) {
+ throw new UserError("sync_alignment_weak", message, {
+ recording: rec.name,
+ video: video.name,
+ confidence: answer.confidence.toFixed(2),
+ needs: syncMinConfidence,
+ });
+ }
+ throw new UserError("sync_alignment_none", message, { recording: rec.name, video: video.name });
}
const offset = Math.round(answer.offset * 1e5) / 1e5;
useEditor.getState().setAssetSoundFrom(video.id, { assetId: rec.id, offset });
diff --git a/site/src/cut/lib/soundPresets.ts b/site/src/cut/lib/soundPresets.ts
index aef745c2..fa105be6 100644
--- a/site/src/cut/lib/soundPresets.ts
+++ b/site/src/cut/lib/soundPresets.ts
@@ -12,6 +12,7 @@ import { normalizeSound, type ClipSound } from "@donkeycut/effects-kit";
import { deleteTemplate, fetchLibrary, saveTemplate } from "./library";
import type { Residency } from "./residency";
import type { LibraryTemplate } from "./types";
+import { UserError } from "./userError";
export interface SoundPreset {
id: string;
@@ -49,7 +50,9 @@ export async function saveSoundPreset(
sound: ClipSound
): Promise<SoundPreset | null> {
const normalized = normalizeSound(sound);
- if (!normalized) throw new Error("A flat treatment is nothing to save.");
+ if (!normalized) {
+ throw new UserError("sound_preset_flat", "A flat treatment is nothing to save.");
+ }
const saved = await saveTemplate(projectId, {
name,
duration: 0,
diff --git a/site/src/cut/lib/sourceRemux.ts b/site/src/cut/lib/sourceRemux.ts
index a5166832..328bb02b 100644
--- a/site/src/cut/lib/sourceRemux.ts
+++ b/site/src/cut/lib/sourceRemux.ts
@@ -3,6 +3,7 @@ import {
Mp4OutputFormat, Output, StreamTarget, type Input, type EncodedPacket, type InputVideoTrack, type InputAudioTrack, type Rotation,
} from "mediabunny";
import type { SourceSegment } from "@/cut/lib/sourceExportPlan";
+import { UserError } from "@/cut/lib/userError";
// MP4 edits express the playback window while keeping the dependency frames
// around each cut. The mdat stays on disk; only the movie index is rewritten.
@@ -12,7 +13,7 @@ function boxes(bytes: Uint8Array, start = 8): Box[] {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
for (let at = start; at < bytes.length;) {
const size = view.getUint32(at);
- if (size < 8 || at + size > bytes.length) throw new Error("Invalid MP4 movie index.");
+ if (size < 8 || at + size > bytes.length) throw new UserError("mp4_index_invalid", "Invalid MP4 movie index.");
result.push({ type: String.fromCharCode(...bytes.subarray(at + 4, at + 8)), bytes: bytes.slice(at, at + size) });
at += size;
}
@@ -40,7 +41,7 @@ function setDuration(bytes: Uint8Array, ticks: number, track = false) {
export function trimMovieIndex(bytes: Uint8Array, offsets: number[], duration: number): Uint8Array {
const children = boxes(bytes);
const header = children.find((b) => b.type === "mvhd");
- if (!header) throw new Error("MP4 has no movie header.");
+ if (!header) throw new UserError("mp4_header_missing", "MP4 has no movie header.");
const movieScale = timeScale(header.bytes);
setDuration(header.bytes, duration * movieScale);
let index = 0;
@@ -51,7 +52,7 @@ export function trimMovieIndex(bytes: Uint8Array, offsets: number[], duration: n
const tkhd = track.find((b) => b.type === "tkhd");
const mdia = track.find((b) => b.type === "mdia");
const mdhd = mdia && boxes(mdia.bytes).find((b) => b.type === "mdhd");
- if (!tkhd || !mdhd || offset === undefined) throw new Error("Invalid MP4 trim track.");
+ if (!tkhd || !mdhd || offset === undefined) throw new UserError("mp4_trim_track_invalid", "Invalid MP4 trim track.");
setDuration(tkhd.bytes, duration * movieScale, true);
// Version 1 stores both the segment duration and media time in 64 bits.
const edit = new Uint8Array(28);
@@ -73,7 +74,7 @@ export type SourceWriter = {
/** A codec-compatible copy needs neither a decoder nor an encoder. */
export async function prepareTrimRemux(input: Input, trim: SourceSegment, codec: "h264" | "hevc", audioInput: Input = input) {
if (!Number.isFinite(trim.from) || !Number.isFinite(trim.to) || trim.from < 0 || trim.to <= trim.from) {
- throw new Error("Invalid source trim range.");
+ throw new UserError("source_trim_range_invalid", "Invalid source trim range.");
}
const video = await input.getPrimaryVideoTrack();
const audio = await audioInput.getPrimaryAudioTrack();
@@ -143,7 +144,7 @@ export async function prepareTrimRemux(input: Input, trim: SourceSegment, codec:
audioOut?.close();
stop();
await output.finalize();
- if (!movie) throw new Error("Trim export produced no movie index.");
+ if (!movie) throw new UserError("trim_export_no_index", "Trim export produced no movie index.");
const edited = trimMovieIndex(movie.bytes, offsets, trim.to - trim.from);
await writer.write(edited, movie.position);
await writer.truncate(movie.position + edited.length);
@@ -164,7 +165,7 @@ export async function prepareSourceRemux(inputs: Map<string, Input>, segments: S
if (!segments.length) return null;
const tracks: { segment: SourceSegment; video: InputVideoTrack; audio: InputAudioTrack | null; sink: EncodedPacketSink; first: EncodedPacket; config: VideoDecoderConfig; rotation: Rotation; signature: string }[] = [];
for (const segment of segments) {
- if (!(segment.from >= 0 && segment.to > segment.from && Number.isFinite(segment.to))) throw new Error("Invalid source export range.");
+ if (!(segment.from >= 0 && segment.to > segment.from && Number.isFinite(segment.to))) throw new UserError("source_export_range_invalid", "Invalid source export range.");
const input = inputs.get(segment.file)!;
const video = await input.getPrimaryVideoTrack();
const audio = await input.getPrimaryAudioTrack();
@@ -222,7 +223,7 @@ export async function prepareSourceRemux(inputs: Map<string, Input>, segments: S
videoOut.close();
await output.finalize();
stop();
- if (!movie) throw new Error("Source export produced no movie index.");
+ if (!movie) throw new UserError("source_export_no_index", "Source export produced no movie index.");
const edited = trimMovieIndex(movie.bytes, [preroll], duration);
await writer.write(edited, movie.position); await writer.truncate(movie.position + edited.length);
progress(1);
diff --git a/site/src/cut/lib/stageFrame.ts b/site/src/cut/lib/stageFrame.ts
index 428b3370..5d7ce80d 100644
--- a/site/src/cut/lib/stageFrame.ts
+++ b/site/src/cut/lib/stageFrame.ts
@@ -20,6 +20,7 @@
* using them, so a copy on either side clears the other and ⌘V has one answer.
*/
+import { creatorNames } from "./defaultNames";
import { renderProjectFrame } from "./exportRender";
import { uploadProjectImage } from "./media";
import { previewAt } from "./playhead";
@@ -137,7 +138,7 @@ function stillNames(at: number): { fileName: string; name: string } {
const stamp = stampOf(at);
return {
fileName: `frame-${stamp.replace(":", "m")}s-${crypto.randomUUID().slice(0, 4)}.png`,
- name: `Frame ${stamp}`,
+ name: creatorNames().frame(stamp),
};
}
diff --git a/site/src/cut/lib/stems.ts b/site/src/cut/lib/stems.ts
index 04a7b524..667a7d50 100644
--- a/site/src/cut/lib/stems.ts
+++ b/site/src/cut/lib/stems.ts
@@ -13,6 +13,7 @@
*/
import { assetIsSilent, type AudioClip, type MediaAsset, type VideoClip } from "./types";
+import { UserError } from "./userError";
import { wavHeader } from "./wav";
/** One stem: what it is called, the file it lands in, and what it carries —
@@ -298,7 +299,7 @@ export async function writeStoredZip(
crc = crc32(b, crc);
size += b.length;
}
- if (size !== e.size) throw new Error(`${e.name} changed size while it was being packed.`);
+ if (size !== e.size) throw new UserError("stem_changed_while_packing", `${e.name} changed size while it was being packed.`, { name: e.name });
const entry = { name: e.name, size, crc };
offsets.push(at);
await put(zipLocalHeader(entry));
diff --git a/site/src/cut/lib/stickerCreate.ts b/site/src/cut/lib/stickerCreate.ts
index 421a1469..59a8d391 100644
--- a/site/src/cut/lib/stickerCreate.ts
+++ b/site/src/cut/lib/stickerCreate.ts
@@ -15,6 +15,7 @@ import { hostedPost } from "./hosted";
import { enrichAsset, uploadProjectImage } from "./media";
import { useEditor } from "./store";
import { mediaSlug, type MediaAsset } from "./types";
+import { UserError, errorFromBody } from "./userError";
/** The die-cut framing that makes a generation come back sticker-shaped: one
* centered subject on a plain background the cutout pass can lift it off. */
@@ -55,11 +56,13 @@ export async function createCustomSticker(
});
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
- throw new Error(body.error ?? "Image generation failed.");
+ throw errorFromBody(body, new UserError("image_generation_failed", "Image generation failed."));
}
const gen = (await res.json()) as { outputs: { dataBase64?: string; contentType?: string }[] };
const out = gen.outputs?.find((o) => o.dataBase64);
- if (!out?.dataBase64) throw new Error("The provider returned no image.");
+ if (!out?.dataBase64) {
+ throw new UserError("image_output_missing", "The provider returned no image.");
+ }
const source = new Blob([bytesFromBase64(out.dataBase64)], {
type: out.contentType ?? "image/png",
});
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 9b1864f0..23536c76 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -1,5 +1,6 @@
"use client";
import { noteProjectRevision } from "./projectRevision";
+import { creatorNames } from "./defaultNames";
import { freeItemName } from "./itemName";
import { clipLen, timelineEnd } from "./timelineEnd";
@@ -70,6 +71,7 @@ import type { CameraKey } from "@donkeycut/effects-kit";
import { mapTimelineItems, pasteTimelineItems, splitTimelineItems, shiftedTimelineItems, timelineCopies, timelinePlacementDelta, timelineRange } from "./timelineItems";
import { fillSlot } from "./genvideo/fillSlot";
import { apiFetch, apiJson, getBackend, hasLocalCompute } from "./backend";
+import { errorFields, errorFromBody, replyError, UserError, type ErrorFields } from "./userError";
import { fetchSignedMediaUrls, pinDocBase } from "./backend/cloud";
import { cancelRevoke, resolveRegisteredBlob, revokeRegistered } from "./backend/browser/registry";
import { markSignedBatch } from "./mediaLinks";
@@ -439,6 +441,8 @@ export interface EditorState {
* from the server is never saved straight back to it. */
loadEpoch: number;
loadError: string | null;
+ /** loadError with its code, for the page to word it. */
+ loadFailure: ErrorFields | null;
saveState: SaveState;
/** Raised when an open resumed unsaved edits from the dirty disk snapshot:
* autosave sees it, clears it, and pushes the resumed document up. */
@@ -534,6 +538,8 @@ export interface EditorState {
subtitles: SubtitlesBlock;
subtitleStatus: SubtitleStatus;
subtitleError: string | null;
+ /** subtitleError with its code, for the page to word it. */
+ subtitleFailure: ErrorFields | null;
/** Epoch ms when the running transcription/translation started — the panel
* shows a ticking elapsed beside its spinner. */
subtitleStartedAt: number | null;
@@ -691,8 +697,9 @@ export interface EditorState {
* owned them) and clear the gen sets, so post-run edits to generated clips
* undo like any other edit. */
releaseGenClips: () => void;
- /** Place a title element; a drop (or the assistant) passes where it landed. */
- addOverlay: (aim?: { at?: number; lane?: number; seed?: TitleSeed }) => void;
+ /** Place a title element; a drop (or the assistant) passes where it landed,
+ * and the editor passes the placeholder `text` in the page's language. */
+ addOverlay: (aim?: { at?: number; lane?: number; seed?: TitleSeed; text?: string }) => void;
/** Add a vector shape element on the title lanes at the playhead. */
/** Place a shape element; a drop passes where it landed. */
addShape: (shape: ShapeKind, aim?: { at?: number; lane?: number }) => void;
@@ -1407,9 +1414,21 @@ function resizeClipFootprint(clip: VideoClip, patch: Partial<VideoClip>) {
useEditor.getState().updateClipTransient(clip.id, patch);
settleClipFootprint(clip.id, patch);
}
+// A failure as the store keeps it: the English the assistant and logs read,
+// and its code beside it for the page to word.
+const textOf = (failure: unknown) => (failure instanceof Error ? failure.message : String(failure));
+const subtitleFailed = (failure: unknown) => ({
+ subtitleError: textOf(failure),
+ subtitleFailure: errorFields(failure, textOf(failure)),
+});
+const loadFailed = (failure: unknown) => ({
+ loadError: textOf(failure),
+ loadFailure: errorFields(failure, textOf(failure)),
+});
+
const staleLaneError = {
subtitleStatus: "error" as const,
- subtitleError: "Subtitle tracks changed while working — run it again.",
+ ...subtitleFailed(new UserError("subtitle_tracks_changed", "Subtitle tracks changed while working — run it again.")),
};
/** Earliest start at/after `t` where a `len`-long item fits between the
@@ -1508,7 +1527,7 @@ export async function runTranscription(projectId: string, spec: object): Promise
if (getBackend().kind !== "local") {
const s = spec as CloudTranscribeSpec;
if (s.clips.length === 0 && s.audio.length === 0) {
- throw new Error("Add audio or video to the timeline first.");
+ throw new UserError("timeline_media_required", "Add audio or video to the timeline first.");
}
const stale = () => useEditor.getState().projectId !== projectId;
const mix = await renderMix(projectId, s, useEditor.getState().assets);
@@ -1538,14 +1557,18 @@ export async function runTranscription(projectId: string, spec: object): Promise
body: JSON.stringify(spec),
});
const body = await apiJson<{ id?: string }>(res);
- if (!res.ok || !body.id) throw new Error(body.error ?? "Transcription failed to start.");
+ if (!res.ok || !body.id) {
+ throw errorFromBody(body, new UserError("transcription_start_failed", "Transcription failed to start."));
+ }
for (;;) {
await new Promise((r) => setTimeout(r, 600));
if (useEditor.getState().projectId !== projectId) return null;
const st = await apiFetch(`/api/cut/projects/${projectId}/transcribe?job=${body.id}`);
- if (!st.ok) throw new Error("The transcription job was lost — try again.");
+ if (!st.ok) throw new UserError("transcription_job_lost", "The transcription job was lost — try again.");
const status = (await st.json()) as { status: string; error?: string; cues?: SubtitleCue[] };
- if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");
+ if (status.status === "error") {
+ throw errorFromBody(status, new UserError("transcription_failed", "Transcription failed."));
+ }
if (status.status === "done") {
return useEditor.getState().projectId === projectId ? (status.cues ?? []) : null;
}
@@ -2055,7 +2078,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
set({
projectId: id,
loaded: false,
- loadError: null,
+ loadError: null, loadFailure: null,
saveState: "saved",
resumePush: false,
// A share view is the one that refuses edits, and the surface opening
@@ -2094,7 +2117,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
subtitles: emptySubtitles(),
subtitleLane: 0,
subtitleStatus: "idle",
- subtitleError: null,
+ subtitleError: null, subtitleFailure: null,
exportOpen: false,
genvideo: undefined,
renders: [],
@@ -2117,7 +2140,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
projectName: "",
loaded: false,
loadEpoch: 0,
- loadError: null,
+ loadError: null, loadFailure: null,
saveState: "saved",
resumePush: false,
readOnly: false,
@@ -2155,7 +2178,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
subtitles: emptySubtitles(),
subtitleLane: 0,
subtitleStatus: "idle",
- subtitleError: null,
+ subtitleError: null, subtitleFailure: null,
subtitleStartedAt: null,
exportOpen: false,
dropActive: null,
@@ -2292,10 +2315,10 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if ([401, 403, 404].includes(res.status)) {
pinDocBase(id, null);
dropCachedDoc(id);
- set({ loaded: false, loadError: "This project no longer exists.", resumePush: false });
+ set({ loaded: false, ...loadFailed(new UserError("project_gone", "This project no longer exists.")), resumePush: false });
return;
}
- throw new Error("This project could not be loaded.");
+ throw new UserError("project_load_failed", "This project could not be loaded.");
}
const doc = (await res.json()) as ProjectDoc;
if (!current()) return;
@@ -2449,7 +2472,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// a version behind at worst, and autosave retries until the link is
// back.
if (current() && !paintedFromCache) {
- set({ loadError: err instanceof Error ? err.message : String(err) });
+ set(loadFailed(err));
}
} finally {
if (current()) hydrating = false;
@@ -2836,7 +2859,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
aspect: opts?.ownAspect === false ? s.aspect : timelineAspect(s, id),
subtitleLane: 0,
subtitleStatus: opened.subtitles.cues.length > 0 ? "ready" : "idle",
- subtitleError: null,
+ subtitleError: null, subtitleFailure: null,
selection: null,
multiSelection: [],
selectedKey: null,
@@ -3290,7 +3313,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
addElement("text", (start, end, lane) => ({
id: uid(),
kind: "text",
- text: "Your text",
+ text: aim?.text ?? creatorNames().text,
start,
end,
x: 0.5,
@@ -4635,11 +4658,11 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const lane = s.subtitleLane;
const spec = cutTranscribeSpec(s, trackLocale(s.subtitles, lane));
if (!spec) {
- set({ subtitleStatus: "error", subtitleError: "Add a video to the timeline first." });
+ set({ subtitleStatus: "error", ...subtitleFailed(new UserError("timeline_video_required", "Add a video to the timeline first.")) });
return;
}
const epoch = laneEpoch;
- set({ subtitleStatus: "running", subtitleError: null, subtitleStartedAt: Date.now() });
+ set({ subtitleStatus: "running", subtitleError: null, subtitleFailure: null, subtitleStartedAt: Date.now() });
try {
const heard = await runTranscription(projectId, spec);
if (heard === null) return; // switched projects mid-run
@@ -4680,27 +4703,31 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (get().projectId !== projectId) return;
set({
subtitleStatus: "error",
- subtitleError: err instanceof Error ? err.message : String(err),
+ ...subtitleFailed(err),
});
}
},
generateClipSubtitles: async (clipId) => {
const s = get();
- if (!s.projectId) throw new Error("Open a project first.");
+ if (!s.projectId) throw new UserError("project_open_required", "Open a project first.");
if (s.subtitleStatus === "running") {
- throw new Error("Subtitles are already generating — try again in a moment.");
+ throw new UserError("subtitles_busy", "Subtitles are already generating — try again in a moment.");
}
const projectId = s.projectId;
const sp = clipWindow(s.clips, s.assets, clipId);
- if (!sp) throw new Error("The clip is no longer on the timeline.");
+ if (!sp) throw new UserError("clip_not_on_timeline", "The clip is no longer on the timeline.");
const src = soundSourceOf(sp.asset, s.assets);
- if (assetIsSilent(sp.asset) && !src.bound) throw new Error("This clip is a still — it has no sound.");
- if (sp.clip.reverse) throw new Error("This clip plays backward — its sound is not speech.");
+ if (assetIsSilent(sp.asset) && !src.bound) throw new UserError("clip_has_no_sound", "This clip is a still — it has no sound.");
+ if (sp.clip.reverse) {
+ throw new UserError("clip_plays_backward", "This clip plays backward — its sound is not speech.");
+ }
// A recording bound to the video is what the clip says; it is read on
// the video's clock, starting late where it rolled late.
const heard = src.bound ? soundWindow(sp.clip, src, 0, sp.len) : null;
- if (src.bound && !heard) throw new Error("The recording bound to this video holds none of this clip.");
+ if (src.bound && !heard) {
+ throw new UserError("bound_recording_misses_clip", "The recording bound to this video holds none of this clip.");
+ }
const lane = s.subtitleLane;
const epoch = laneEpoch;
// The clip's own sound, deliberately unmuted: this transcribes what the
@@ -4735,13 +4762,13 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
]
: [],
};
- set({ subtitleStatus: "running", subtitleError: null, subtitleStartedAt: Date.now() });
+ set({ subtitleStatus: "running", subtitleError: null, subtitleFailure: null, subtitleStartedAt: Date.now() });
try {
const cues = await runTranscription(projectId, spec);
if (cues === null) return; // switched projects mid-run
if (laneEpoch !== epoch) {
set(staleLaneError);
- throw new Error(staleLaneError.subtitleError);
+ throw new UserError("subtitle_tracks_changed", staleLaneError.subtitleError);
}
// The job timed cues against the lone clip, so shift them (and their
// word timings) onto the clip's timeline span. New cues replace any
@@ -4779,22 +4806,22 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;
if (!getBackend().caps.captionAi) {
- set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ set({ subtitleStatus: "error", ...subtitleFailed(new UserError("cloud_mode_unavailable", "Not available in cloud mode yet.")) });
return;
}
const projectId = s.projectId;
const spans = getClipSpans(s.clips, s.assets);
if (spans.length === 0) {
- set({ subtitleStatus: "error", subtitleError: "Add a video to the timeline first." });
+ set({ subtitleStatus: "error", ...subtitleFailed(new UserError("timeline_video_required", "Add a video to the timeline first.")) });
return;
}
const duration = totalDuration(s.clips);
const lane = s.subtitleLane;
const epoch = laneEpoch;
- set({ subtitleStatus: "running", subtitleError: null, subtitleStartedAt: Date.now() });
+ set({ subtitleStatus: "running", subtitleError: null, subtitleFailure: null, subtitleStartedAt: Date.now() });
try {
const frames = await captureTimelineFrames(spans);
- if (frames.length === 0) throw new Error("Could not read any frames from the cut.");
+ if (frames.length === 0) throw new UserError("cut_frames_unreadable", "Could not read any frames from the cut.");
const res = await apiFetch("/api/cut/ai/visual-subtitles", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -4808,7 +4835,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
cues?: { start: number; end: number; text: string }[];
}>(res);
if (!res.ok || !Array.isArray(body.cues)) {
- throw new Error(body.error ?? "Captioning failed.");
+ throw replyError(res.status, body, new UserError("captioning_failed", "Captioning failed."));
}
if (get().projectId !== projectId) return; // switched projects mid-run
if (laneEpoch !== epoch) return set(staleLaneError);
@@ -4832,7 +4859,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (get().projectId !== projectId) return;
set({
subtitleStatus: "error",
- subtitleError: err instanceof Error ? err.message : String(err),
+ ...subtitleFailed(err),
});
}
},
@@ -4841,7 +4868,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const s = get();
if (!s.projectId || s.subtitleStatus === "running") return;
if (!getBackend().caps.captionAi) {
- set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ set({ subtitleStatus: "error", ...subtitleFailed(new UserError("cloud_mode_unavailable", "Not available in cloud mode yet.")) });
return;
}
const lane = s.subtitleLane;
@@ -4856,7 +4883,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
set((cur) => ({
subtitles: { ...cur.subtitles, style },
subtitleStatus: "running",
- subtitleError: null,
+ subtitleError: null, subtitleFailure: null,
subtitleStartedAt: Date.now(),
}));
// Rewrite only the active track — other languages keep their text.
@@ -4916,7 +4943,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (get().projectId !== projectId) return;
set({
subtitleStatus: "ready",
- subtitleError: err instanceof Error ? err.message : String(err),
+ ...subtitleFailed(err),
});
}
},
@@ -4926,7 +4953,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const lane = s.subtitleLane;
if (!s.projectId || s.subtitleStatus === "running" || fromLane === lane) return;
if (!getBackend().caps.captionAi) {
- set({ subtitleStatus: "error", subtitleError: "Not available in cloud mode yet." });
+ set({ subtitleStatus: "error", ...subtitleFailed(new UserError("cloud_mode_unavailable", "Not available in cloud mode yet.")) });
return;
}
const laneOf = (c: SubtitleCue) => c.lane ?? 0;
@@ -4935,7 +4962,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const locale = trackLocale(s.subtitles, lane);
const projectId = s.projectId;
const epoch = laneEpoch;
- set({ subtitleStatus: "running", subtitleError: null, subtitleStartedAt: Date.now() });
+ set({ subtitleStatus: "running", subtitleError: null, subtitleFailure: null, subtitleStartedAt: Date.now() });
try {
const res = await apiFetch("/api/cut/ai/captions", {
method: "POST",
@@ -4948,7 +4975,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const body = await apiJson<{ texts?: string[]; error?: string }>(res);
if (get().projectId !== projectId) return;
if (!res.ok || !Array.isArray(body.texts) || body.texts.length !== source.length) {
- throw new Error(body.error || "Could not translate the captions.");
+ throw replyError(res.status, body, new UserError("captions_translate_failed", "Could not translate the captions."));
}
if (laneEpoch !== epoch) return set(staleLaneError);
push();
@@ -4976,7 +5003,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (get().projectId !== projectId) return;
set({
subtitleStatus: "error",
- subtitleError: err instanceof Error ? err.message : String(err),
+ ...subtitleFailed(err),
});
}
},
diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.ts
index 36c6970f..487c96ed 100644
--- a/site/src/cut/lib/textRender.ts
+++ b/site/src/cut/lib/textRender.ts
@@ -19,6 +19,7 @@ import { faceEmAscent } from "./fontEm";
import { allowance, holdMemory } from "./memoryBudget";
import { createRasterCanvas, decodeRasterImage, rasterCanvasToPng } from "./raster";
import { fontStack, type MediaAsset, type Overlay } from "./types";
+import { UserError } from "./userError";
// The shared text metrics and painters live in the effects kit; these
// re-exports keep the app's preview components on the same constants.
@@ -203,7 +204,8 @@ export async function requireStickers(overlays: Overlay[], assets: MediaAsset[])
continue;
}
const why = stickerMisses.get(asset.id) ?? "no picture";
- throw new Error(`The sticker "${o.name ?? asset.name}" could not be read (${why}).`);
+ const name = o.name ?? asset.name;
+ throw new UserError("sticker_unreadable", `The sticker "${name}" could not be read (${why}).`, { name, reason: why });
}
}
diff --git a/site/src/cut/lib/time.ts b/site/src/cut/lib/time.ts
index 698181ed..48533be9 100644
--- a/site/src/cut/lib/time.ts
+++ b/site/src/cut/lib/time.ts
@@ -1,18 +1,37 @@
+import type { Locale } from "@/i18n/locales";
+
/** Whole days left until an ISO timestamp, floored at zero — anything inside
* the last day reads as 0, so "today" means today. */
export function daysUntil(iso: string): number {
return Math.max(0, Math.floor((new Date(iso).getTime() - Date.now()) / 86_400_000));
}
-/** A moment as a shelf reads it: minutes and hours while it is recent, then
- * the calendar date, with the year only once it is not this one. */
-export function formatDate(ts: number) {
+// English reads the narrow style ("5m ago"); elsewhere the narrow style can
+// drop the words entirely (French "-5 min"), so the other languages read the
+// short one ("il y a 5 min").
+const RELATIVE_STYLE: Partial<Record<Locale, Intl.RelativeTimeFormatStyle>> = { en: "narrow" };
+const RELATIVE = new Map<Locale, Intl.RelativeTimeFormat>();
+
+function relativeFormats(locale: Locale) {
+ let formats = RELATIVE.get(locale);
+ if (!formats) {
+ formats = new Intl.RelativeTimeFormat(locale, { style: RELATIVE_STYLE[locale] ?? "short" });
+ RELATIVE.set(locale, formats);
+ }
+ return formats;
+}
+
+/** A moment as a shelf reads it: `justNow` (the caller's catalog line) for the
+ * last minute, minutes and hours while it is recent, then the calendar date,
+ * with the year only once it is not this one. */
+export function formatDate(ts: number, locale: Locale, justNow: string) {
const d = new Date(ts);
const mins = Math.floor((Date.now() - ts) / 60000);
- if (mins < 1) return "just now";
- if (mins < 60) return `${mins}m ago`;
- if (mins < 60 * 24) return `${Math.floor(mins / 60)}h ago`;
- return d.toLocaleDateString(undefined, {
+ const relative = relativeFormats(locale);
+ if (mins < 1) return justNow;
+ if (mins < 60) return relative.format(-mins, "minute");
+ if (mins < 60 * 24) return relative.format(-Math.floor(mins / 60), "hour");
+ return d.toLocaleDateString(locale, {
month: "short",
day: "numeric",
...(d.getFullYear() !== new Date().getFullYear() ? { year: "numeric" } : {}),
diff --git a/site/src/cut/lib/trackMotion.ts b/site/src/cut/lib/trackMotion.ts
index 77bd223b..75f69c2a 100644
--- a/site/src/cut/lib/trackMotion.ts
+++ b/site/src/cut/lib/trackMotion.ts
@@ -26,6 +26,7 @@ import {
} from "./trackKeys";
import { trackTargetOf, type TrackTarget, type TrackUse } from "./trackTargets";
import { clipPoseAt, isEffectOverlay, type MediaAsset, type VideoClip } from "./types";
+import { UserError } from "./userError";
/** The shortest stretch worth a track: a couple of frames. */
const MIN_TRACK_SECONDS = 0.05;
@@ -54,8 +55,12 @@ export async function trackMotion(req: TrackRequest) {
const s = useEditor.getState();
const o = s.overlays.find((x) => x.id === req.id);
const own = o ? undefined : s.clips.find((c) => c.id === req.id);
- if (!o && !own) throw new Error("No overlay element or video clip with that id.");
- if (o && req.use === "mask" && isEffectOverlay(o)) throw new Error("Effect elements have no pixels to mask.");
+ if (!o && !own) {
+ throw new UserError("track_item_missing", "No overlay element or video clip with that id.");
+ }
+ if (o && req.use === "mask" && isEffectOverlay(o)) {
+ throw new UserError("track_effect_mask", "Effect elements have no pixels to mask.");
+ }
// The item's clock as the read starts: keys count from here, so a move
// during the read cannot slide them off the footage.
@@ -63,15 +68,22 @@ export async function trackMotion(req: TrackRequest) {
const source = trackSource(s.clips, s.assets, req, own, span);
const asset = s.assets.find((a) => a.id === source.assetId);
const picture = asset?.type === "video" && asset.width && asset.height ? { width: asset.width, height: asset.height } : null;
- if (!asset || !picture) throw new Error("The source clip has no video picture to track.");
+ if (!asset || !picture) {
+ throw new UserError("track_source_no_picture", "The source clip has no video picture to track.");
+ }
// The stretch tracked: where the item and the source overlap, narrowed by
// from/to, sampled evenly on the timeline's clock.
const srcEnd = source.start + clipLen(source);
const a = Math.max(span.start, source.start, req.from ?? -Infinity);
const b = Math.min(span.end, srcEnd, req.to ?? Infinity);
- if (b - a < MIN_TRACK_SECONDS)
- throw new Error(`The item and the source clip share no stretch to track (${round2(source.start)}–${round2(srcEnd)}s holds the footage).`);
+ if (b - a < MIN_TRACK_SECONDS) {
+ throw new UserError(
+ "track_no_overlap",
+ `The item and the source clip share no stretch to track (${round2(source.start)}–${round2(srcEnd)}s holds the footage).`,
+ { from: round2(source.start), to: round2(srcEnd) },
+ );
+ }
const tune = CUT_TRACKING;
const fps = Math.min(tune.sampleFps, tune.maxFrames / (b - a));
const n = Math.max(2, Math.floor((b - a) * fps) + 1);
@@ -99,14 +111,22 @@ export async function trackMotion(req: TrackRequest) {
};
if (req.use === "read") return { ...summary, path: trackPath(times, framed) };
const label = trackTargetOf(req.target).label.toLowerCase();
- if (found === 0) throw new Error(`No ${label} found in the source between ${round2(a)}s and ${round2(b)}s.`);
+ if (found === 0) {
+ throw new UserError("track_target_not_found", `No ${label} found in the source between ${round2(a)}s and ${round2(b)}s.`, {
+ target: req.target,
+ from: round2(a),
+ to: round2(b),
+ });
+ }
// The item as it stands now: the read took a while, and the person may
// have moved it meanwhile.
const now = useEditor.getState();
const liveO = o && now.overlays.find((x) => x.id === o.id);
const liveClip = own && now.clips.find((c) => c.id === own.id);
- if (!liveO && !liveClip) throw new Error("The item was deleted while it was being tracked.");
+ if (!liveO && !liveClip) {
+ throw new UserError("track_item_deleted", "The item was deleted while it was being tracked.");
+ }
const item: TrackItem = liveO ? { kind: "overlay", overlay: liveO } : { kind: "clip", clip: liveClip! };
const local = times.map((t) => t - span.start);
@@ -145,15 +165,26 @@ function trackSource(
const isVideo = (c: VideoClip) => assets.find((x) => x.id === c.assetId)?.type === "video";
if (req.sourceId !== undefined) {
const named = clips.find((c) => c.id === req.sourceId);
- if (!named) throw new Error("No video clip with that source_id.");
+ if (!named) {
+ throw new UserError("track_source_missing", "No video clip with that source_id.");
+ }
if (req.use === "follow" && named.id === own?.id) {
- throw new Error("A clip cannot follow its own footage — pass the source_id of the clip it should ride.");
+ throw new UserError(
+ "track_follow_self",
+ "A clip cannot follow its own footage — pass the source_id of the clip it should ride.",
+ );
}
return named;
}
if (own && req.use !== "follow" && isVideo(own)) return own;
const under = clipUnder(clips, span, req.id, isVideo);
- if (!under) throw new Error(`No other video clip plays under that ${own ? "clip" : "element"} — pass source_id.`);
+ if (!under) {
+ throw new UserError(
+ "track_source_none_under",
+ `No other video clip plays under that ${own ? "clip" : "element"} — pass source_id.`,
+ { kind: own ? "clip" : "element" },
+ );
+ }
return under;
}
diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.ts
index 506c2a16..ff05cc06 100644
--- a/site/src/cut/lib/tts.ts
+++ b/site/src/cut/lib/tts.ts
@@ -3,7 +3,8 @@
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
import { bytesFromBase64 } from "./bytes";
import { wavHeader } from "./wav";
-import { readHostedError } from "./hostedError";
+import { NoCreditsError, readHostedFailure } from "./hostedError";
+import { UserError } from "./userError";
import { hostedPost } from "./hosted";
import { CUT_JUDGE } from "./chatRuntime";
import { askJudge, choice } from "./judge";
@@ -223,12 +224,8 @@ interface PcmClip {
rate: number;
}
-/** The account balance can't cover the generation — callers surface a link to
- * buy credits alongside the message. */
-export class NoCreditsError extends Error {}
-
-const readError = (res: Response, fallback: string) =>
- readHostedError(res, "Sign in to Donkey to generate voiceovers.", fallback);
+const readFailure = (res: Response, fallback: UserError) =>
+ readHostedFailure(res, new UserError("sign_in_to_generate_voiceovers", "Sign in to Donkey to generate voiceovers."), fallback);
/** One hosted Gemini speech call: text in, decoded PCM out. A direction is a
* natural-language delivery instruction ("Say warmly, like an old friend");
@@ -250,14 +247,15 @@ async function synthesizeSegment(
: {}),
});
if (!res.ok) {
- const message = await readError(res, "Voice generation failed.");
- throw res.status === 402 ? new NoCreditsError(message) : new Error(message);
+ throw await readFailure(res, new UserError("voice_generation_failed", "Voice generation failed."));
}
const gen = (await res.json()) as {
outputs?: { dataBase64?: string; contentType?: string }[];
};
const out = gen.outputs?.find((o) => o.dataBase64);
- if (!out?.dataBase64) throw new Error("The provider returned no audio.");
+ if (!out?.dataBase64) {
+ throw new UserError("audio_output_missing", "The provider returned no audio.");
+ }
const bytes = bytesFromBase64(out.dataBase64);
const rate = Number(out.contentType?.match(/rate=(\d+)/)?.[1]) || 24000;
@@ -349,13 +347,21 @@ export async function renderSpeechClip(
const raw = segments
.map((s) => ({ text: s.text.trim(), at: Math.max(0, s.at) }))
.filter((s) => s.text);
- if (raw.length === 0) throw new Error("Nothing to say.");
- if (raw.length > MAX_SEGMENTS) throw new Error(`At most ${MAX_SEGMENTS} lines at once.`);
+ if (raw.length === 0) {
+ throw new UserError("speech_text_empty", "Nothing to say.");
+ }
+ if (raw.length > MAX_SEGMENTS) {
+ throw new UserError("speech_lines_too_many", `At most ${MAX_SEGMENTS} lines at once.`, { max: MAX_SEGMENTS });
+ }
if (raw.some((s) => s.text.length > MAX_SEGMENT_CHARS)) {
- throw new Error(`Each line must stay under ${MAX_SEGMENT_CHARS} characters.`);
+ throw new UserError("speech_line_too_long", `Each line must stay under ${MAX_SEGMENT_CHARS} characters.`, {
+ max: MAX_SEGMENT_CHARS,
+ });
}
if (raw.reduce((n, s) => n + s.text.length, 0) > MAX_TOTAL_CHARS) {
- throw new Error(`The script must stay under ${MAX_TOTAL_CHARS} characters.`);
+ throw new UserError("speech_script_too_long", `The script must stay under ${MAX_TOTAL_CHARS} characters.`, {
+ max: MAX_TOTAL_CHARS,
+ });
}
// The one place a free-text direction becomes speech settings: a model reads
@@ -391,7 +397,11 @@ export async function renderSpeechClip(
// Name the line that failed so a one-bad-cue batch is actionable.
if (lines.length > 1 && e instanceof Error && !(e instanceof NoCreditsError)) {
const snippet = lines[i].text.length > 40 ? `${lines[i].text.slice(0, 40)}…` : lines[i].text;
- throw new Error(`Line ${i + 1} ("${snippet}"): ${e.message}`);
+ throw new UserError("speech_line_failed", `Line ${i + 1} ("${snippet}"): ${e.message}`, {
+ line: i + 1,
+ snippet,
+ reason: e.message,
+ });
}
throw e;
}
@@ -439,7 +449,9 @@ export async function speechClipToAsset(
const label = name?.trim() || "AI voice";
const file = new File([blob], `${mediaSlug(label, "ai-voice")}.wav`, { type: "audio/wav" });
const asset = await importFileToProject(projectId, file);
- if (!asset) throw new Error("Could not save the voiceover into the project.");
+ if (!asset) {
+ throw new UserError("voiceover_save_failed", "Could not save the voiceover into the project.");
+ }
asset.name = label;
asset.origin = "voiceover";
if (language) asset.language = language;
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index d820f0bb..88759838 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -33,6 +33,7 @@ import type { ClipEffect, CodeFormat, SourceProfile, TextWeight } from "@donkeyc
import type { CameraCard } from "./cameraCard";
import { getBackend, type CutBackend } from "./backend";
import type { VideoProject } from "./genvideo/types";
+import type { UserErrorParams } from "./userError";
export type AssetType = "video" | "audio" | "image" | "font" | "lut";
@@ -356,6 +357,9 @@ export interface AssetUpload {
progress: number;
/** Set when the upload failed; the asset is retryable until it is removed. */
error?: string;
+ /** The failure's catalog code and values, so the tile words it in the reader's language. */
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** The bytes are held durably in the browser store, so the asset is safe to
* save and the upload safe to resume after a reload. */
stored?: boolean;
@@ -1930,6 +1934,8 @@ export interface RenderRecord {
startedAt: number;
status: "running" | "done" | "error";
error?: string;
+ errorCode?: string;
+ errorParams?: Record<string, string | number>;
/** The project asset the finished render landed as. */
assetId?: string;
}
diff --git a/site/src/cut/lib/userError.test.ts b/site/src/cut/lib/userError.test.ts
new file mode 100644
index 00000000..c7bc9f34
--- /dev/null
+++ b/site/src/cut/lib/userError.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, test } from "bun:test";
+
+import { err } from "./backend/browser/respond";
+import { errorBody, errorFields, errorFromBody, failureCode, failureText, replyError, UserError } from "./userError";
+import { errorRecord, errorReply } from "../server/util";
+
+// A failure crosses JSON as `{ error, code, params }` (a reply) or
+// `{ error, errorCode, errorParams }` (a record). Either way the reader gets
+// back the same code, values and English it was raised with.
+
+const roundTrip = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
+
+describe("a coded failure across a reply body", () => {
+ test("keeps its code, values and English", () => {
+ const raised = new UserError("file_read_failed", "Could not read clip.mov.", { name: "clip.mov" });
+ const read = errorFromBody(roundTrip(errorBody(raised, "fallback")), "fallback");
+ expect(read instanceof UserError).toBe(true);
+ expect(failureCode(read)).toEqual({ code: "file_read_failed", params: { name: "clip.mov" } });
+ expect(read.message).toBe("Could not read clip.mov.");
+ });
+
+ test("an uncoded failure keeps its own words and no code", () => {
+ const read = errorFromBody(roundTrip(errorBody(new Error("ffmpeg exited 1"), "fallback")), "fallback");
+ expect(read instanceof UserError).toBe(false);
+ expect(read.message).toBe("ffmpeg exited 1");
+ });
+
+ test("an empty body reads as the fallback", () => {
+ const fallback = new UserError("folder_create_failed", "Could not create folder.");
+ expect(errorFromBody(null, fallback)).toBe(fallback);
+ expect(errorFromBody({}, "Upload failed.").message).toBe("Upload failed.");
+ });
+
+ test("a system error's code never reads as a catalog code", () => {
+ const enoent = Object.assign(new Error("ENOENT: no such file"), { code: "ENOENT" });
+ expect(failureCode(enoent)).toBeNull();
+ expect(errorBody(enoent, "x")).toEqual({ error: "ENOENT: no such file" });
+ });
+});
+
+describe("a coded failure across a record", () => {
+ test("rides beside `error` as errorCode and errorParams", () => {
+ const fields = errorFields(new UserError("export_canceled", "Export canceled."), "Export failed.");
+ expect(fields).toEqual({ error: "Export canceled.", errorCode: "export_canceled", errorParams: {} });
+ const job = roundTrip({ status: "error", progress: 0.4, ...fields });
+ expect(failureCode(job)).toEqual({ code: "export_canceled", params: {} });
+ expect(failureText(job)).toBe("Export canceled.");
+ expect(errorFromBody(job, "x") instanceof UserError).toBe(true);
+ });
+});
+
+describe("replies on each residency", () => {
+ test("the browser backend answers a UserError with its code", async () => {
+ const res = err(new UserError("project_not_found", "Project not found."), 404);
+ expect(res.status).toBe(404);
+ expect(await res.json()).toEqual({ error: "Project not found.", code: "project_not_found", params: {} });
+ });
+
+ test("the engine words a full disk as the coded disk_full", () => {
+ const full = Object.assign(new Error("ENOSPC: write /Users/x/Movies"), { code: "ENOSPC" });
+ expect(errorReply(full, "x")).toMatchObject({ code: "disk_full" });
+ expect(errorRecord(full, "x")).toMatchObject({ errorCode: "disk_full" });
+ });
+
+ test("a storage wall's code-only body reads as the wall", () => {
+ const read = replyError(413, { error: "storage_quota_exceeded", bytes: 1, quotaBytes: 2 }, "Upload failed.");
+ expect(failureCode(read)).toEqual({ code: "storage_quota_exceeded", params: {} });
+ expect(read.message).toBe("Cloud storage is full.");
+ });
+});
diff --git a/site/src/cut/lib/userError.ts b/site/src/cut/lib/userError.ts
new file mode 100644
index 00000000..46efa455
--- /dev/null
+++ b/site/src/cut/lib/userError.ts
@@ -0,0 +1,143 @@
+// A failure the person reads. It carries a code from the `errors` catalog
+// (src/i18n/messages/<locale>/errors.json) and the values its message names,
+// so each surface words it in the reader's language; the English message
+// stays for logs, the chat model, and anything that only reads `message`.
+//
+// throw new UserError("note_save_failed", "Could not save the note.");
+// throw new UserError("file_too_large", "That file is over 4 GB.", { limit: "4 GB" });
+
+import { operationFailure } from "./operationFailure";
+
+export type UserErrorParams = Record<string, string | number>;
+
+export class UserError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ readonly params: UserErrorParams = {},
+ ) {
+ super(message);
+ this.name = "UserError";
+ }
+}
+
+/** A failure as a JSON reply carries it: the English under `error`, the code
+ * and values beside it when it has them. Engine, browser-backend and cloud
+ * replies all answer in this shape. */
+export type ErrorBody = { error: string; code?: string; params?: UserErrorParams };
+
+/** A failure as a record that holds other fields carries it: a job's status,
+ * a persisted tile, an upload row. */
+export type ErrorFields = { error?: string; errorCode?: string; errorParams?: UserErrorParams };
+
+const isParams = (value: unknown): value is UserErrorParams =>
+ !!value && typeof value === "object" && !Array.isArray(value);
+
+/** The code and values of a failure that has one, whatever carried it: a
+ * UserError, an OperationError's failure, a reply body's `code`, a record's
+ * `errorCode`. */
+export function failureCode(error: unknown): { code: string; params: UserErrorParams } | null {
+ if (error instanceof UserError) {
+ return { code: error.code, params: error.params };
+ }
+ if (!error || typeof error !== "object") {
+ return null;
+ }
+ const failure = (error as { failure?: { code?: unknown } }).failure;
+ if (typeof failure?.code === "string") {
+ return { code: failure.code, params: {} };
+ }
+
+ // Any other Error's `code` is a system's (ENOENT, ENOSPC), never a catalog key.
+ if (error instanceof Error) {
+ return null;
+ }
+
+ // A record's `errorCode` names its failure; a bare `code` is a reply body's.
+ const { errorCode, errorParams, code, params } = error as {
+ errorCode?: unknown;
+ errorParams?: unknown;
+ code?: unknown;
+ params?: unknown;
+ };
+ if (typeof errorCode === "string") {
+ return { code: errorCode, params: isParams(errorParams) ? errorParams : {} };
+ }
+ return typeof code === "string" ? { code, params: isParams(params) ? params : {} } : null;
+}
+
+/** The English of a failure, whatever carried it: an Error, a string, a
+ * reply body's or record's `error`. Empty when there is none. */
+export function failureText(error: unknown): string {
+ if (error instanceof Error) {
+ return error.message;
+ }
+ if (typeof error === "string") {
+ return error;
+ }
+ const text = (error as { error?: unknown } | null)?.error;
+ return typeof text === "string" ? text : "";
+}
+
+/** The reply body for a failure. A coded failure keeps its code; an Error
+ * with words of its own (an upstream tool's) keeps them; anything else
+ * answers with `fallback`.
+ *
+ * Response.json(errorBody(e, new UserError("export_start_failed", "Export failed to start.")), { status: 500 })
+ */
+export function errorBody(failure: unknown, fallback: UserError | string): ErrorBody {
+ const coded = failureCode(failure);
+ const text = failureText(failure);
+ if (coded && text) {
+ return { error: text, code: coded.code, params: coded.params };
+ }
+ if (text) {
+ return { error: text };
+ }
+ return typeof fallback === "string" ? { error: fallback } : errorBody(fallback, fallback.message);
+}
+
+/** The record fields for a failure, the way errorBody words it. */
+export function errorFields(failure: unknown, fallback: UserError | string): Required<Pick<ErrorFields, "error">> & ErrorFields {
+ const body = errorBody(failure, fallback);
+ return {
+ error: body.error,
+ ...(body.code ? { errorCode: body.code, errorParams: body.params ?? {} } : {}),
+ };
+}
+
+/** The failure a reply body or record carried, rebuilt for the page: a
+ * UserError when it has a code, its own words when it has only those, and
+ * `fallback` when it carried nothing.
+ *
+ * if (!res.ok) throw errorFromBody(await res.json().catch(() => null), new UserError("folder_create_failed", "Could not create folder."));
+ */
+export function errorFromBody(body: unknown, fallback: UserError | string): Error {
+ const text = failureText(body);
+ if (!text) {
+ return typeof fallback === "string" ? new Error(fallback) : fallback;
+ }
+ const coded = failureCode(body);
+ return coded ? new UserError(coded.code, text, coded.params) : new Error(text);
+}
+
+const PAYMENT_REQUIRED = 402;
+const PAYLOAD_TOO_LARGE = 413;
+
+/** The failure a reply that came back not ok carried. A credits or storage
+ * wall answers with its code under `error` (`{ error: "storage_quota_exceeded" }`),
+ * so it reads as the wall's own failure, in the reply's own `message` when it
+ * sent one; any other reply as errorFromBody.
+ *
+ * if (!res.ok) throw replyError(res.status, body, new UserError("project_duplicate_failed", "Could not duplicate the project."));
+ */
+export function replyError(status: number, body: unknown, fallback: UserError | string): Error {
+ if (status === PAYMENT_REQUIRED || status === PAYLOAD_TOO_LARGE) {
+ const wall = operationFailure(status, body);
+ if (wall) {
+ const own = (body as { message?: unknown } | null)?.message;
+ return new UserError(wall.code, typeof own === "string" && own ? own : wall.message);
+ }
+ }
+ return errorFromBody(body, fallback);
+}
diff --git a/site/src/cut/lib/voiceover.ts b/site/src/cut/lib/voiceover.ts
index d5775375..28691bc6 100644
--- a/site/src/cut/lib/voiceover.ts
+++ b/site/src/cut/lib/voiceover.ts
@@ -1,6 +1,7 @@
import { enrichAsset } from "@/cut/lib/media";
import { useEditor } from "@/cut/lib/store";
import { renderSpeechClip, speechClipToAsset, type SpeechLayout } from "@/cut/lib/tts";
+import { UserError } from "@/cut/lib/userError";
/** Default duck: everything else drops to 40% while a voiceover speaks. */
export const DUCK_DEFAULT = 0.4;
@@ -70,9 +71,13 @@ export async function generateSubtitlesReadout(
opts?: { cueIds?: string[]; direction?: string; language?: string; duck?: number }
) {
const projectId = useEditor.getState().projectId;
- if (!projectId) throw new Error("Open a project first.");
+ if (!projectId) {
+ throw new UserError("project_open_required", "Open a project first.");
+ }
const cues = readoutCues(opts?.cueIds);
- if (cues.length === 0) throw new Error("No subtitles to read.");
+ if (cues.length === 0) {
+ throw new UserError("subtitles_none_to_read", "No subtitles to read.");
+ }
const { blob, offset, layout, language } = await renderReadout(voice, cues, opts);
const asset = await speechClipToAsset(projectId, blob, "Subtitles readout", language);
diff --git a/site/src/cut/lib/wav.ts b/site/src/cut/lib/wav.ts
index 44d110bf..90bf3414 100644
--- a/site/src/cut/lib/wav.ts
+++ b/site/src/cut/lib/wav.ts
@@ -1,3 +1,5 @@
+import { UserError } from "./userError";
+
/** How a WAV's samples are coded: integer PCM or IEEE float. */
export type WavCoding = "pcm" | "float";
@@ -15,7 +17,7 @@ export function wavHeader(
): Uint8Array<ArrayBuffer> {
const bytes = bits / 8;
const data = frames * channels * bytes;
- if (data + 36 > 0xffffffff) throw new Error("Audio this long does not fit in a WAV file.");
+ if (data + 36 > 0xffffffff) throw new UserError("wav_too_long", "Audio this long does not fit in a WAV file.");
const b = new Uint8Array(44);
const v = new DataView(b.buffer);
const ascii = (at: number, s: string) => [...s].forEach((ch, i) => (b[at + i] = ch.charCodeAt(0)));
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index d66a763b..62a6f349 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -15,7 +15,7 @@ import { STOCK_SFX_CATEGORIES } from "@/cut/lib/stock";
import { SPLIT_EDIT_MAX_S } from "@/cut/lib/soundSource";
import { SWEEP_TARGET } from "@/cut/lib/frameDiff";
import { builtinLutCatalogText } from "@/cut/lib/builtinLuts";
-import { AI_PANEL_TOOLS } from "@/cut/components/AiPanel.tools";
+import { AI_PANEL_TOOLS, INTERFACE_LANGUAGE_LIST, languageName } from "@/cut/components/AiPanel.tools";
import {
geminiOmniDefaultResolution,
geminiOmniDurationSeconds,
@@ -73,6 +73,7 @@ import {
WHEEL_ZONES,
TEXT_WEIGHTS,
} from "@donkeycut/effects-kit";
+import type { Locale } from "@/i18n/locales";
import type { AiToolDef } from "../../lib/aiToolDef";
import { GOOGLE_FONT_IDS } from "../../lib/fontCatalog";
import { FONTS, TIMELINE_IDS, TIMELINE_LABELS, TRANSITION_STYLE_IDS } from "../../lib/types";
@@ -643,7 +644,8 @@ Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everyw
};
/** System prompt shared by all providers. */
-export function systemPrompt(): string {
+/** The system prompt, written for a person whose editor reads in `locale`. */
+export function systemPrompt(locale: Locale): string {
return `You are the AI editor built into a video editor. Your voice is plain, warm, and brief. Describe your own output factually; superlatives about your own work — "masterpiece", "stunning", "incredibly", "professional-grade" and their kin — are banned. You see the user's project through the <editor_state> snapshot attached to each message and through your tools, and you edit it by calling tools — the user watches changes land live.
Rules:
@@ -670,6 +672,7 @@ Rules:
- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. When it lands on a card, close with a statement of where it is ("The voiceover is on the card — drag it in or tell me to place it."). Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the storyboard — the user reviews the frames (regenerate_shot redraws any before approval, no credits), then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after). Close a plan message with the approval path as a statement: "Approve it — say so or hit Approve on the card — and I'll render the shots." Tweaks before approval are theirs to name.
- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen, and write each look down with note_source — sheets are conversation-local, notes stay on the source; listen_audio plays a source's audio — an audio asset or a video/clip's own track, one stretch per call, with \`coveredTo\` and \`unheardSeconds\` saying how far it reached and what nobody has played (an ask about how a whole source sounds listens on from \`unheardFrom\` until that is 0); detect_silence finds dead air; find_highlights ranks the stretches of a long source worth clipping, from what is said over them; detect_beats reads the music's beat grid (persisted on the asset, drawn as dots on its clips, snapped to by every drag) for cutting to the music; capture_frame shows one rendered frame, at the time you pass or the playhead; compare_to_source scores the cut against the source it copies and shows the two side by side, which is how copied work is checked; detect_cuts, sample_color, track_element and track_camera measure a source's cuts, colours, moving elements and camera moves as numbers. The watching-and-cutting skill has the flow.
- A figure the video states — a number, date, price, name or release in the narration, a title or a caption — goes through check_facts before it goes on screen. Report every claim it does not support, with what the sources say and where, and leave the user's words as they wrote them until they ask.
+- The editor's interface is in ${languageName(locale)}. Write every reply in ${languageName(locale)}; when the person writes in another language, reply in theirs. A request to change the language the editor itself shows (its menus and buttons) is set_interface_language — the languages are ${INTERFACE_LANGUAGE_LIST}.
- End on a statement. The final sentence of every reply states what changed, what failed, or the one suggestion you're making; "let me know if", "would you like", "do you want me to", and every other trailing offer or question are banned closers. The only question that may end a reply is the single clarifying one a genuinely ambiguous or blocked ask earns.`;
}
diff --git a/site/src/cut/server/ai/claudeFailure.test.ts b/site/src/cut/server/ai/claudeFailure.test.ts
index cf0fe68a..d3b02caf 100644
--- a/site/src/cut/server/ai/claudeFailure.test.ts
+++ b/site/src/cut/server/ai/claudeFailure.test.ts
@@ -8,17 +8,22 @@ describe("Claude provider failures", () => {
type: "assistant", error: "rate_limit",
message: { content: [{ type: "text", text: "You've hit your session limit · resets 11:30pm (Asia/Seoul)" }] },
});
- expect(failure).toBe("Claude: You've hit your session limit · resets 11:30pm (Asia/Seoul)\n\nTry again after your usage limit resets.");
+ expect(failure?.message).toBe("Claude: You've hit your session limit · resets 11:30pm (Asia/Seoul)\n\nTry again after your usage limit resets.");
+ expect(failure?.code).toBe("claude_rate_limit");
+ expect(failure?.params).toEqual({ detail: "You've hit your session limit · resets 11:30pm (Asia/Seoul)" });
expect(turnClose({ end: failure ? "failed" : "done", spoke: false, extensions: 0 })).toBeNull();
});
test("authentication failures give the sign-in action", () => {
- expect(claudeFailure({ type: "assistant", error: "authentication_failed", message: { content: [] } })).toContain("Sign in to Claude again");
+ const failure = claudeFailure({ type: "assistant", error: "authentication_failed", message: { content: [] } });
+ expect(failure?.message).toBe("Claude: The request failed.\n\nSign in to Claude again.");
+ expect(failure?.code).toBe("claude_sign_in");
+ expect(failure?.params).toEqual({ detail: "" });
});
test("a success-shaped SDK error is still a failure", () => {
- expect(claudeFailure({ type: "result", subtype: "success", is_error: true, result: "Account limit reached" })).toContain("Account limit reached");
+ expect(claudeFailure({ type: "result", subtype: "success", is_error: true, result: "Account limit reached" })?.message).toContain("Account limit reached");
});
test("execution failures preserve the SDK errors array", () => {
- expect(claudeFailure({ type: "result", subtype: "error_during_execution", errors: ["Connection closed"] })).toContain("Connection closed");
+ expect(claudeFailure({ type: "result", subtype: "error_during_execution", errors: ["Connection closed"] })?.message).toBe("Claude: Connection closed\n\nTry again in a moment.");
});
test("ordinary replies and budget exhaustion retain their existing handling", () => {
expect(claudeFailure({ type: "assistant", message: { content: [{ type: "text", text: "Done" }] } })).toBeNull();
diff --git a/site/src/cut/server/ai/claudeFailure.ts b/site/src/cut/server/ai/claudeFailure.ts
index 387dfad4..ac707e9f 100644
--- a/site/src/cut/server/ai/claudeFailure.ts
+++ b/site/src/cut/server/ai/claudeFailure.ts
@@ -1,21 +1,52 @@
+import { UserError } from "../../lib/userError";
+
+// What the person reads when Claude fails: the provider's own words (the
+// `detail` value, empty when it sent none) and the step that fixes it. Each
+// code has a message in the errors catalog, so the panel
+// words it in the page's language; the English message stays for the stream
+// and the logs.
+
+/** The failure codes, by what the person does next. */
+const FAILURE_ACTIONS = {
+ claude_rate_limit: "Try again after your usage limit resets.",
+ claude_sign_in: "Sign in to Claude again.",
+ claude_billing: "Check your Claude billing.",
+ claude_failed: "Try again in a moment.",
+} as const;
+
+type FailureCode = keyof typeof FAILURE_ACTIONS;
+
+const REQUEST_FAILED = "The request failed.";
+
+function failure(code: FailureCode, detail: string): UserError {
+ return new UserError(code, `Claude: ${detail || REQUEST_FAILED}\n\n${FAILURE_ACTIONS[code]}`, { detail });
+}
+
+/** The code for an assistant message's SDK error. */
+function errorCode(error: string): FailureCode {
+ if (error === "rate_limit") {
+ return "claude_rate_limit";
+ }
+ if (error === "authentication_failed" || error === "oauth_org_not_allowed") {
+ return "claude_sign_in";
+ }
+ if (error === "billing_error") {
+ return "claude_billing";
+ }
+ return "claude_failed";
+}
+
/** SDK failures can arrive as assistant messages without text stream events. */
-export function claudeFailure(message: Record<string, unknown>): string | null {
+export function claudeFailure(message: Record<string, unknown>): UserError | null {
if (message.type === "assistant" && typeof message.error === "string") {
const body = message.message as { content?: { type: string; text?: string }[] } | undefined;
const detail = body?.content?.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n").trim();
- const action = message.error === "rate_limit"
- ? "Try again after your usage limit resets."
- : message.error === "authentication_failed" || message.error === "oauth_org_not_allowed"
- ? "Sign in to Claude again."
- : message.error === "billing_error"
- ? "Check your Claude billing."
- : "Try again in a moment.";
- return `Claude: ${detail || "The request failed."}\n\n${action}`;
+ return failure(errorCode(message.error), detail ?? "");
}
if (message.type === "result" && message.subtype === "error_max_turns") return null;
if (message.type === "result" && (message.is_error === true || (message.subtype !== "success" && message.subtype !== "error_max_turns"))) {
const details = Array.isArray(message.errors) ? message.errors.filter((value): value is string => typeof value === "string").join("\n") : message.result;
- return `Claude: ${typeof details === "string" && details.trim() ? details.trim() : "The request failed."}\n\nTry again in a moment.`;
+ return failure("claude_failed", typeof details === "string" ? details.trim() : "");
}
return null;
}
diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.ts
index 93a49eb5..89200064 100644
--- a/site/src/cut/server/ai/headlessTools.ts
+++ b/site/src/cut/server/ai/headlessTools.ts
@@ -82,6 +82,7 @@ const PAGE_SESSION_TOOLS: ReadonlySet<string> = new Set([
"file_asset",
"import_url",
"check_facts",
+ "set_interface_language",
]);
// Converting media is the one media job this process can do: ffmpeg is right
diff --git a/site/src/cut/server/cloud/account.ts b/site/src/cut/server/cloud/account.ts
new file mode 100644
index 00000000..a95f6214
--- /dev/null
+++ b/site/src/cut/server/cloud/account.ts
@@ -0,0 +1,24 @@
+// The account settings a headless session may change for its user: the
+// interface language, which the chat's set_interface_language tool saves
+// when no editor page is there to do it.
+import { prisma } from "@/lib/prisma";
+import { isLocale } from "@/i18n/locales";
+import { caught, err } from "./util";
+
+const HTTP_BAD_REQUEST = 400;
+
+export const accountCloud = {
+ async setLocale(userId: string, req: Request) {
+ try {
+ const body = (await req.json().catch(() => null)) as { locale?: unknown } | null;
+ const locale = body?.locale;
+ if (!isLocale(locale)) {
+ return err("A supported locale is required.", HTTP_BAD_REQUEST);
+ }
+ await prisma.user.update({ where: { id: userId }, data: { locale } });
+ return Response.json({ locale });
+ } catch (e) {
+ return caught(e, "Could not save the language.");
+ }
+ },
+};
diff --git a/site/src/cut/server/cloud/captions.ts b/site/src/cut/server/cloud/captions.ts
index 71a51ba9..790e0562 100644
--- a/site/src/cut/server/cloud/captions.ts
+++ b/site/src/cut/server/cloud/captions.ts
@@ -32,6 +32,7 @@ import {
visualSubtitlesPrompt,
type CaptionInput,
} from "../ai/captionPrompts";
+import { errorBody, UserError } from "@/cut/lib/userError";
import { err } from "./util";
const PROVIDER = "gemini";
@@ -63,7 +64,7 @@ async function geminiOnce(
parts: GeminiPart[]
): Promise<string> {
const clientConfig = geminiClientConfig(process.env);
- if (!clientConfig.configured) throw new Error("Captions are not configured on this deployment.");
+ if (!clientConfig.configured) throw new UserError("captions_unconfigured", "Captions are not configured on this deployment.");
let raw: unknown;
try {
const client = defaultGeminiClientFactory(clientConfig.options);
@@ -86,7 +87,7 @@ async function geminiOnce(
const credit = creditErrorResponse(error);
if (credit) throw new RespondWith(credit);
const mapped = geminiApiError("The caption model is unavailable.", error);
- throw new RespondWith(err(mapped.message, mapped.statusCode ?? 502));
+ throw new RespondWith(err(new UserError("caption_model_unavailable", mapped.message), mapped.statusCode ?? 502));
}
const usage = (raw as { usageMetadata?: unknown }).usageMetadata;
try {
@@ -225,7 +226,7 @@ export const captionsCloud = {
timeout(BATCH_TIMEOUT_MS),
]);
const arr = parseStringArray(raw, batch.length);
- if (!arr) throw new Error("The reply came back malformed.");
+ if (!arr) throw new UserError("caption_reply_malformed", "The reply came back malformed.");
return arr;
};
try {
@@ -240,7 +241,7 @@ export const captionsCloud = {
return Response.json({ texts: flat });
} catch (e) {
if (e instanceof RespondWith) return e.response;
- return err(e instanceof Error ? e.message : "Could not write captions.", 500);
+ return Response.json(errorBody(e, new UserError("captions_write_failed", "Could not write captions.")), { status: 500 });
}
},
@@ -295,7 +296,7 @@ export const captionsCloud = {
const raw = await geminiOnce(userId, route, "visual_subtitles", parts);
const parsed = parseJsonPayload(raw);
if (!Array.isArray(parsed)) {
- return err("The caption model returned an unreadable response — try again.", 502);
+ return err(new UserError("caption_reply_unreadable", "The caption model returned an unreadable response — try again."), 502);
}
const cues = parsed
.filter(
@@ -316,7 +317,7 @@ export const captionsCloud = {
return Response.json({ cues });
} catch (e) {
if (e instanceof RespondWith) return e.response;
- return err(e instanceof Error ? e.message : "Could not caption the visuals.", 500);
+ return Response.json(errorBody(e, new UserError("visual_captions_failed", "Could not caption the visuals.")), { status: 500 });
}
},
};
diff --git a/site/src/cut/server/cloud/copyQueue.test.ts b/site/src/cut/server/cloud/copyQueue.test.ts
index f34abd77..c188ae27 100644
--- a/site/src/cut/server/cloud/copyQueue.test.ts
+++ b/site/src/cut/server/cloud/copyQueue.test.ts
@@ -40,6 +40,8 @@ const prisma = {
cutProject: { findFirst: mock(async () => project) },
cutMediaObject: { findMany: mock(async ({ where }: { where: Parameters<typeof matches>[1] }) => objects.filter((o) => matches(o, where))) },
cutChatThread: { findMany: mock(async () => []) },
+ // The duplicate is named in the owner's saved language.
+ user: { findUnique: mock(async () => ({ locale: "en" })) },
$transaction: mock(async (fn: (t: typeof tx) => Promise<unknown>) => fn(tx)),
};
await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });
diff --git a/site/src/cut/server/cloud/copyQueue.ts b/site/src/cut/server/cloud/copyQueue.ts
index abfa24e7..a5e7d8e3 100644
--- a/site/src/cut/server/cloud/copyQueue.ts
+++ b/site/src/cut/server/cloud/copyQueue.ts
@@ -8,14 +8,17 @@
// copy requests drains one copy at a time instead of stampeding R2 and the
// database all at once.
import { randomUUID } from "node:crypto";
+import { defaultNames } from "@/cut/lib/defaultNames";
import type { ProjectDoc } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import { creatorLocaleOf } from "./creatorLocale";
import { copy, projectMediaKey } from "./r2";
import { normalizeEmails, normalizeFeatures } from "./share";
import { filterDocForShare, resolveShare, type ShareRow } from "./sharedView";
import { addUsage, quotaCheck } from "./usage";
+import { errorFields, UserError } from "@/cut/lib/userError";
import { caught, err } from "./util";
const COPY_QUEUE_NAME = "donkey-cut-copy";
@@ -28,8 +31,29 @@ const STALE_QUEUED_MS = 30_000;
// failure instead of spinning the viewer forever.
const STALE_RUNNING_MS = 10 * 60_000;
-const QUOTA_MESSAGE =
- "Your cloud storage is full — free some space, then copy again.";
+// The failures a copy job records on its row, by their English. The row
+// keeps only that English, so a status reply finds the code by looking the
+// stored message up here; a thrown exception's text stays uncoded.
+const COPY_FAILURES = {
+ stalled: new UserError("copy_stalled", "The copy stalled — try again."),
+ storageFull: new UserError(
+ "copy_storage_full",
+ "Your cloud storage is full — free some space, then copy again."
+ ),
+ shareRemoved: new UserError("share_removed", "The share was removed."),
+ accessLost: new UserError("share_access_lost", "You no longer have access to this project."),
+ projectDeleted: new UserError("project_deleted", "The project was deleted."),
+} as const;
+
+// Refusals the copy and duplicate requests answer with.
+const SIGN_IN_TO_COPY = new UserError("copy_sign_in_required", "Sign in to copy this project.");
+const COPY_NOT_FOUND = new UserError("copy_not_found", "Copy not found.");
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
+
+/** The coded failure a row's stored message is, when this module wrote it. */
+function recordedFailure(message: string): UserError | string {
+ return Object.values(COPY_FAILURES).find((failure) => failure.message === message) ?? message;
+}
// --- Queue publish (Cloudflare Queues REST API; producers outside Workers
// publish over HTTP). The queue id is looked up from the name once per
@@ -154,18 +178,18 @@ async function copyPlan(share: ShareRow) {
/** A share copy's source: access re-checked at drain time, doc filtered to
* the shared surfaces, mid-flight brief-to-video runs dropped (the copy is
* the viewer's project — a live plan would auto-resume on their account),
- * chats only when chat is shared. Returns the permanent-failure message when
+ * chats only when chat is shared. Returns the permanent failure when
* the copy can no longer happen. */
-async function shareSource(job: { shareId: string | null; userId: string }): Promise<CopySource | string> {
+async function shareSource(job: { shareId: string | null; userId: string }): Promise<CopySource | UserError> {
const share = job.shareId
? await prisma.cutProjectShare.findUnique({ where: { id: job.shareId } })
: null;
- if (!share) return "The share was removed.";
+ if (!share) return COPY_FAILURES.shareRemoved;
if (!(await viewerAllowed(share, job.userId))) {
- return "You no longer have access to this project.";
+ return COPY_FAILURES.accessLost;
}
const plan = await copyPlan(share);
- if (!plan) return "The project was deleted.";
+ if (!plan) return COPY_FAILURES.projectDeleted;
const chats = plan.features.chat
? await prisma.cutChatThread.findMany({
where: { userId: share.userId, projectId: share.projectId },
@@ -196,11 +220,11 @@ async function shareSource(job: { shareId: string | null; userId: string }): Pro
async function duplicateSource(job: {
projectId: string | null;
userId: string;
-}): Promise<CopySource | string> {
+}): Promise<CopySource | UserError> {
const row = job.projectId
? await prisma.cutProject.findFirst({ where: { id: job.projectId, userId: job.userId } })
: null;
- if (!row) return "The project was deleted.";
+ if (!row) return COPY_FAILURES.projectDeleted;
const media = await completeMedia(job.userId, row.id);
const { doc, proxies } = await withProxies(job.userId, row.id, row.doc as unknown as ProjectDoc, media);
const chats = await prisma.cutChatThread.findMany({
@@ -208,12 +232,13 @@ async function duplicateSource(job: {
select: { id: true, data: true },
});
const gv = doc.genvideo;
+ const names = await defaultNames(await creatorLocaleOf(job.userId));
return {
doc: {
...doc,
genvideo: gv && (gv.phase === "done" || gv.phase === "failed") ? gv : undefined,
},
- name: `${doc.name} copy`,
+ name: names.copy(doc.name),
folderId: row.folderId,
media,
proxies,
@@ -259,14 +284,14 @@ async function statusResponse(job: NonNullable<Awaited<ReturnType<typeof prisma.
} else if (job.state === "running" && idleMs > STALE_RUNNING_MS) {
await prisma.cutCopyJob.updateMany({
where: { id: job.id, state: "running" },
- data: { state: "error", error: "The copy stalled — try again." },
+ data: { state: "error", error: COPY_FAILURES.stalled.message },
});
job = (await prisma.cutCopyJob.findUnique({ where: { id: job.id } })) ?? job;
}
return Response.json({
state: job.state,
newProjectId: job.newProjectId ?? undefined,
- error: job.error ?? undefined,
+ ...(job.error ? errorFields(recordedFailure(job.error), job.error) : {}),
});
}
@@ -278,14 +303,14 @@ export const copyJobs = {
const view = await resolveShare(token, req);
if (view instanceof Response) return view;
const session = await auth.api.getSession({ headers: req.headers });
- if (!session?.user) return err("Sign in to copy this project.", 401);
+ if (!session?.user) return err(SIGN_IN_TO_COPY, 401);
const plan = await copyPlan(view.share);
- if (!plan) return err("Project not found.", 404);
+ if (!plan) return err(PROJECT_NOT_FOUND, 404);
const over = await quotaCheck(session.user.id, plan.added);
if (over) return over;
return await enqueue({ kind: "share", shareId: view.share.id, userId: session.user.id });
} catch (e) {
- return caught(e, "Could not copy the project.");
+ return caught(e, new UserError("project_copy_failed", "Could not copy the project."));
}
},
@@ -294,13 +319,13 @@ export const copyJobs = {
async requestDuplicate(userId: string, projectId: string) {
try {
const row = await prisma.cutProject.findFirst({ where: { id: projectId, userId } });
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
const media = await completeMedia(userId, projectId);
const over = await quotaCheck(userId, mediaBytes(media));
if (over) return over;
return await enqueue({ kind: "duplicate", projectId, userId });
} catch (e) {
- return caught(e, "Could not duplicate the project.");
+ return caught(e, new UserError("project_duplicate_failed", "Could not duplicate the project."));
}
},
@@ -309,18 +334,18 @@ export const copyJobs = {
const view = await resolveShare(token, req);
if (view instanceof Response) return view;
const session = await auth.api.getSession({ headers: req.headers });
- if (!session?.user) return err("Sign in to copy this project.", 401);
+ if (!session?.user) return err(SIGN_IN_TO_COPY, 401);
const job = await prisma.cutCopyJob.findFirst({
where: { id: jobId, userId: session.user.id, shareId: view.share.id },
});
- if (!job) return err("Copy not found.", 404);
+ if (!job) return err(COPY_NOT_FOUND, 404);
return statusResponse(job);
},
/** Poll any of the caller's own copy jobs (authed surface). */
async ownerStatus(userId: string, jobId: string) {
const job = await prisma.cutCopyJob.findFirst({ where: { id: jobId, userId } });
- if (!job) return err("Copy not found.", 404);
+ if (!job) return err(COPY_NOT_FOUND, 404);
return statusResponse(job);
},
};
@@ -338,10 +363,10 @@ export async function executeCopyJob(jobId: string): Promise<Response> {
// Already running, settled, or unknown — double delivery lands here.
if (claimed.count === 0) return Response.json({ ok: true });
- const fail = async (message: string) => {
+ const fail = async (failure: UserError) => {
await prisma.cutCopyJob.update({
where: { id: jobId },
- data: { state: "error", error: message },
+ data: { state: "error", error: failure.message },
});
return Response.json({ ok: true });
};
@@ -350,9 +375,9 @@ export async function executeCopyJob(jobId: string): Promise<Response> {
const job = await prisma.cutCopyJob.findUnique({ where: { id: jobId } });
if (!job) return Response.json({ ok: true });
const src = job.kind === "duplicate" ? await duplicateSource(job) : await shareSource(job);
- if (typeof src === "string") return fail(src);
+ if (src instanceof UserError) return fail(src);
const over = await quotaCheck(job.userId, src.added);
- if (over) return fail(QUOTA_MESSAGE);
+ if (over) return fail(COPY_FAILURES.storageFull);
const now = Date.now();
const copyDoc: ProjectDoc = { ...src.doc, name: src.name, createdAt: now, updatedAt: now };
diff --git a/site/src/cut/server/cloud/creatorLocale.ts b/site/src/cut/server/cloud/creatorLocale.ts
new file mode 100644
index 00000000..e0a83a91
--- /dev/null
+++ b/site/src/cut/server/cloud/creatorLocale.ts
@@ -0,0 +1,14 @@
+import { isLocale, type Locale } from "@/i18n/locales";
+import { requestedLocale } from "@/cut/lib/defaultNames";
+import { prisma } from "@/lib/prisma";
+
+/** The language a cloud write names new content in: the one its request
+ * named, else the account's saved language (a headless runner names none),
+ * else the default. */
+export async function creatorLocaleOf(userId: string, named?: unknown): Promise<Locale> {
+ if (isLocale(named)) {
+ return named;
+ }
+ const user = await prisma.user.findUnique({ select: { locale: true }, where: { id: userId } });
+ return requestedLocale(user?.locale);
+}
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 2e139348..cb408765 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -18,6 +18,7 @@ import type { DocExportAudio } from "../../lib/exportPresets";
import { compatCoverIn, compatCovers, isLightProxyName, PROXY_SOURCE_FAULT, type CompatCover } from "../../lib/proxyNames";
import { addUsage, outputByteCeiling, quotaCheck } from "./usage";
import { caught, err, redirect } from "./util";
+import { errorFields, failureCode, UserError, type ErrorFields } from "@/cut/lib/userError";
const HOUR_MS = 60 * 60 * 1000;
@@ -106,15 +107,15 @@ type JobRow = {
};
/** Why a client-supplied render spec cannot run, or null when it can. */
-function specRefusal(spec: Record<string, unknown>): string | null {
+function specRefusal(spec: Record<string, unknown>): UserError | null {
const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : NaN);
const inRange = (v: unknown, lo: number, hi: number) => n(v) >= lo && n(v) <= hi;
if (!inRange(spec.width, 2, MAX_RENDER_EDGE) || !inRange(spec.height, 2, MAX_RENDER_EDGE))
- return "Render size is out of range.";
- if (!inRange(spec.fps, 1, MAX_RENDER_FPS)) return "Frame rate is out of range.";
+ return new UserError("render_size_out_of_range", "Render size is out of range.");
+ if (!inRange(spec.fps, 1, MAX_RENDER_FPS)) return new UserError("render_fps_out_of_range", "Frame rate is out of range.");
if (!(n(spec.duration) > 0) || n(spec.duration) > MAX_RENDER_SECONDS)
- return "Render length is out of range.";
- if (Array.isArray(spec.clips) && spec.clips.length > MAX_RENDER_CLIPS) return "Too many clips.";
+ return new UserError("render_length_out_of_range", "Render length is out of range.");
+ if (Array.isArray(spec.clips) && spec.clips.length > MAX_RENDER_CLIPS) return new UserError("render_too_many_clips", "Too many clips.");
return null;
}
@@ -190,11 +191,36 @@ async function dropUnregisteredExport(
await del(keys.filter((k) => !kept.has(k)));
}
+const EXPORT_CANCELED = new UserError("export_canceled", "Export canceled.");
+
+type RowFailure = Pick<ErrorFields, "errorCode" | "errorParams">;
+
+/** The code the worker recorded beside a failed row's error (worker/main.ts
+ * keeps it in `result`), so the page words the failure in its language. */
+function rowFailure(result: unknown): RowFailure {
+ const coded = failureCode(result);
+ return coded ? { errorCode: coded.code, errorParams: coded.params } : {};
+}
+
+/** The recorded failure of each failed row among `rows`, read in one query:
+ * only a failed row's result is fetched, and only once it has failed. */
+async function rowFailures(rows: Pick<JobRow, "id" | "state">[]): Promise<Map<string, RowFailure>> {
+ const failed = rows.filter((r) => r.state === "error").map((r) => r.id);
+ if (failed.length === 0) return new Map();
+ const found = await prisma.cutRenderJob.findMany({ where: { id: { in: failed } }, select: { id: true, result: true } });
+ return new Map(found.map((r) => [r.id, rowFailure(r.result)]));
+}
+
/** Engine job status ("queued" | "running" | "done" | "error") from a row's
* state; a canceled row reads as the engine's canceled-export error. */
-function engineStatus(row: Pick<JobRow, "state" | "error">): { status: string; error?: string } {
- if (row.state === "canceled") return { status: "error", error: row.error ?? "Export canceled." };
- return { status: row.state, error: row.error ?? undefined };
+function engineStatus(
+ row: Pick<JobRow, "state" | "error">,
+ failure: RowFailure = {}
+): { status: string; error?: string } & RowFailure {
+ if (row.state === "canceled") {
+ return row.error ? { status: "error", error: row.error } : { status: "error", ...errorFields(EXPORT_CANCELED, "") };
+ }
+ return { status: row.state, error: row.error ?? undefined, ...(row.error ? failure : {}) };
}
/** Everything the job routes read except the two big JSON columns. The spec
@@ -272,7 +298,7 @@ export async function queueDocExport(
audio: DocExportAudio = {}
): Promise<{ id: string; outName: string } | Response> {
const project = await getProject(userId, projectId);
- if (!project) return err("Project not found.", 404);
+ if (!project) return err(new UserError("project_not_found", "Project not found."), 404);
const capped = await renderJobCheck(userId);
if (capped) return capped;
const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
@@ -311,7 +337,7 @@ export async function queueImportUrl(
projectId: string,
opts: { url: string; audio?: boolean; key?: string; name?: string }
): Promise<{ id: string } | Response> {
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 404);
const open = await importJobFor(userId, opts.key);
if (open) return { id: open.id };
const capped = await renderJobCheck(userId);
@@ -355,7 +381,7 @@ export const jobsCloud = {
target?: string;
};
if (!Array.isArray(files) || files.length === 0) return err("files is required.", 400);
- if (files.length > MAX_OVERLAY_FILES) return err("Too many overlays.", 400);
+ if (files.length > MAX_OVERLAY_FILES) return err(new UserError("render_too_many_overlays", "Too many overlays."), 400);
// Retained exports pass their storage and render gates before staging inputs.
if (target === undefined || target === "export") {
const capped = await renderJobCheck(userId);
@@ -369,7 +395,7 @@ export const jobsCloud = {
if (f.bytes! > MAX_OVERLAY_BYTES) return err(`${f.name} is too large to render in the cloud.`, 413);
total += f.bytes!;
}
- if (total > MAX_OVERLAY_BATCH_BYTES) return err("The cut's files are too large to render in the cloud.", 413);
+ if (total > MAX_OVERLAY_BATCH_BYTES) return err(new UserError("render_files_too_large", "The cut's files are too large to render in the cloud."), 413);
const batchId = crypto.randomUUID().slice(0, 12);
const out = await Promise.all(
files.map(async (f) => {
@@ -383,7 +409,7 @@ export const jobsCloud = {
);
return Response.json({ files: out });
} catch (e) {
- return caught(e, "Could not presign the overlays.");
+ return caught(e, new UserError("render_overlays_presign_failed", "Could not presign the overlays."));
}
},
@@ -418,7 +444,7 @@ export const jobsCloud = {
return err("Invalid render revision.", 400);
const borrowed = body.mediaFrom === "overlays";
const project = await getProject(userId, projectId);
- if (!project && !borrowed) return err("Project not found.", 400);
+ if (!project && !borrowed) return err(new UserError("project_not_found", "Project not found."), 400);
// Overlay keys come from the client; only this user's own overlay
// uploads are acceptable render inputs — anything else would let a
// crafted key pull another account's R2 objects into the render.
@@ -527,7 +553,7 @@ export const jobsCloud = {
wakeRenderWorker();
return Response.json({ id: row.id });
} catch (e) {
- return caught(e, "Export failed to start.");
+ return caught(e, new UserError("export_start_failed", "Export failed to start."));
}
},
@@ -546,15 +572,15 @@ export const jobsCloud = {
if (queued instanceof Response) return queued;
return Response.json(queued);
} catch (e) {
- return caught(e, "Export failed to start.");
+ return caught(e, new UserError("export_start_failed", "Export failed to start."));
}
},
async exportStatus(userId: string, jobId: string) {
const row = await findJob(userId, jobId);
- if (!row) return err("Unknown export.", 404);
+ if (!row) return err(new UserError("export_unknown", "Unknown export."), 404);
if (needsWorker(row)) wakeRenderWorker();
- const { status, error } = engineStatus(row);
+ const { status, error, ...failure } = engineStatus(row, (await rowFailures([row])).get(row.id));
const finished = row.state === "done" && row.outputKey;
// The artifact names the revision the render was cut from, which only the
// spec knows. One read, on the poll that ends the wait.
@@ -567,6 +593,7 @@ export const jobsCloud = {
status,
progress: row.progress,
error,
+ ...failure,
outName: row.outName || undefined,
artifact: finished ? {
id: row.id, projectId: row.projectId, kind: row.kind,
@@ -611,7 +638,7 @@ export const jobsCloud = {
const claim: ExportFiles = body.stems === true ? "fileAndStems" : "file";
const projectId = body.projectId;
if (!projectId) return err("projectId is required.", 400);
- if (!(await getProject(userId, projectId))) return err("Project not found.", 400);
+ if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 400);
const capped = await renderJobCheck(userId);
if (capped) return capped;
// The size the render is heading for, from the same model the export
@@ -659,7 +686,7 @@ export const jobsCloud = {
...(stemsUrl ? { stemsUrl } : {}),
});
} catch (e) {
- return caught(e, "Could not start the export.");
+ return caught(e, new UserError("export_could_not_start", "Could not start the export."));
}
},
@@ -685,13 +712,13 @@ export const jobsCloud = {
select: { ...jobRowSelect, spec: true },
});
if (!row || row.kind !== "export" || !row.projectId || !row.outName) {
- return err("Export not found.", 400);
+ return err(new UserError("export_not_found", "Export not found."), 400);
}
- if (row.state === "canceled") return err("Export canceled.", 400);
+ if (row.state === "canceled") return err(new UserError("export_canceled", "Export canceled."), 400);
const { projectId, outName } = row;
const key = projectExportKey(userId, projectId, outName);
const object = await head(key);
- if (!object) return err("The export was not uploaded.", 400);
+ if (!object) return err(new UserError("export_not_uploaded", "The export was not uploaded."), 400);
// A render that asked for stems uploaded them before the file. Each file
// is its own row at its own size, so deleting one frees what it held.
@@ -700,7 +727,7 @@ export const jobsCloud = {
const stemsName = stemsArchiveName(outName);
const stemsKey = projectExportKey(userId, projectId, stemsName);
const stemsObject = await head(stemsKey);
- if (!stemsObject) return err("The stems were not uploaded.", 400);
+ if (!stemsObject) return err(new UserError("export_stems_not_uploaded", "The stems were not uploaded."), 400);
files.push({ r2Key: stemsKey, fileName: stemsName, mime: STEMS_MIME, bytes: stemsObject.bytes });
}
const bytes = files.reduce((sum, f) => sum + f.bytes, 0);
@@ -737,7 +764,7 @@ export const jobsCloud = {
});
return Response.json({ id: row.id, outName });
} catch (e) {
- return caught(e, "Could not save the export.");
+ return caught(e, new UserError("export_save_failed", "Could not save the export."));
}
},
@@ -758,7 +785,7 @@ export const jobsCloud = {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not record the export's progress.");
+ return caught(e, new UserError("export_progress_failed", "Could not record the export's progress."));
}
},
@@ -786,7 +813,7 @@ export const jobsCloud = {
}
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not release the export.");
+ return caught(e, new UserError("export_release_failed", "Could not release the export."));
}
},
@@ -798,7 +825,7 @@ export const jobsCloud = {
}
if (row.kind === "preview" && !row.outputKey.startsWith(overlayPrefix(userId))) {
const artifact = await prisma.cutMediaObject.findUnique({ where: { r2Key: row.outputKey }, select: { id: true } });
- if (!artifact) return err("Preview expired. Render it again.", 410);
+ if (!artifact) return err(new UserError("preview_expired", "Preview expired. Render it again."), 410);
}
// A finished job's output never changes, so the redirect is cacheable.
return redirect(
@@ -806,7 +833,7 @@ export const jobsCloud = {
MEDIA_REDIRECT_HEADERS
);
} catch (e) {
- return caught(e, "Export not ready.");
+ return caught(e, new UserError("export_not_ready", "Export not ready."));
}
},
@@ -871,9 +898,10 @@ export const jobsCloud = {
})
: [];
const names = new Map(projects.map((p) => [p.id, p.name]));
+ const failures = await rowFailures(live);
return Response.json(
live.map((r) => {
- const { status, error } = engineStatus(r);
+ const { status, error, ...failure } = engineStatus(r, failures.get(r.id));
return {
id: r.id,
projectId: r.projectId ?? "",
@@ -882,6 +910,7 @@ export const jobsCloud = {
progress: r.progress,
outName: r.outName || undefined,
error,
+ ...failure,
createdAt: r.createdAt.getTime(),
startedAt: r.claimedAt?.getTime(),
};
@@ -904,7 +933,7 @@ export const jobsCloud = {
if (queued instanceof Response) return queued;
return Response.json({ jobId: queued.id });
} catch (e) {
- return caught(e, "Could not import that URL.");
+ return caught(e, new UserError("url_import_failed", "Could not import that URL."));
}
},
@@ -947,7 +976,7 @@ export const jobsCloud = {
wakeRenderWorker();
return Response.json({ jobId: row.id });
} catch (e) {
- return caught(e, "Could not import that URL.");
+ return caught(e, new UserError("url_import_failed", "Could not import that URL."));
}
},
@@ -959,14 +988,14 @@ export const jobsCloud = {
if (!file) return err("file is required.", 400);
const mode = convertModeIn(askedMode);
if (!mode) return err("mode is fit or reencode.", 400);
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 404);
const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
if (over) return over;
const source = await prisma.cutMediaObject.findFirst({
where: { userId, projectId, fileName: file, kind: "media" },
select: { id: true },
});
- if (!source) return err("Media file missing from project.", 404);
+ if (!source) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
const capped = await renderJobCheck(userId);
if (capped) return capped;
const row = await prisma.cutRenderJob.create({
@@ -980,7 +1009,7 @@ export const jobsCloud = {
wakeRenderWorker();
return Response.json({ jobId: row.id });
} catch (e) {
- return caught(e, "Could not convert that file.");
+ return caught(e, new UserError("convert_failed", "Could not convert that file."));
}
},
@@ -997,12 +1026,12 @@ export const jobsCloud = {
const compat = compatCoverIn(askedCompat);
if (askedCompat !== undefined && !compat) return err("compat is audio or video.", 400);
const maxHeight = typeof asked === "number" && Number.isFinite(asked) ? Math.round(Math.min(4320, Math.max(360, asked))) : undefined;
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 404);
const source = await prisma.cutMediaObject.findFirst({
where: { userId, projectId, fileName: file, kind: "media", uploadState: "complete" },
select: { id: true },
});
- if (!source) return err("Media file missing from project.", 404);
+ if (!source) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
// A heavy video's request (it names a height) wants the light proxy
// (lib/proxyNames.ts); a full-quality one built earlier doesn't answer it.
const light = maxHeight !== undefined;
@@ -1033,7 +1062,7 @@ export const jobsCloud = {
select: { spec: true },
});
if (failedRows.some((r) => sameProxyAsk(r.spec, light, compat))) {
- return err("The preview proxy could not be made from this file lately; the original plays instead.", 409);
+ return err(new UserError("proxy_recently_failed", "The preview proxy could not be made from this file lately; the original plays instead."), 409);
}
const capped = await renderJobCheck(userId);
if (capped) return capped;
@@ -1043,20 +1072,21 @@ export const jobsCloud = {
wakeRenderWorker();
return Response.json({ jobId: row.id });
} catch (e) {
- return caught(e, "Could not make the preview proxy.");
+ return caught(e, new UserError("proxy_failed", "Could not make the preview proxy."));
}
},
/** Generic job poll for non-export kinds (import_url, convert, proxy). */
async status(userId: string, jobId: string) {
const row = await findJob(userId, jobId);
- if (!row) return err("Unknown job.", 404);
+ if (!row) return err(new UserError("job_unknown", "Unknown job."), 404);
if (needsWorker(row)) wakeRenderWorker();
- const result =
- row.state === "done"
+ const settled =
+ row.state === "done" || row.state === "error"
? (await prisma.cutRenderJob.findUnique({ where: { id: row.id }, select: { result: true } }))
?.result
: null;
+ const result = row.state === "done" ? settled : null;
return Response.json({
id: row.id,
kind: row.kind,
@@ -1064,6 +1094,7 @@ export const jobsCloud = {
progress: row.progress,
result: result ?? undefined,
error: row.error ?? undefined,
+ ...(row.state === "error" && row.error ? rowFailure(settled) : {}),
});
},
};
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 0f644892..7160bb78 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -28,6 +28,7 @@ import { itemName } from "@/cut/lib/itemName";
import { compatCoverIn, compatCovers } from "@/cut/lib/proxyNames";
import type { AssetType } from "@/cut/lib/types";
import { caught, decodeFileParam, dedupeName, err, HttpResponseError, inspirationFolderId, redirect, safeFileName, storableFileName } from "./util";
+import { UserError } from "@/cut/lib/userError";
/** Cap on one signed-URL batch, matching the project media batch. */
const PRESIGN_GET_BATCH_MAX = 500;
@@ -286,7 +287,7 @@ async function copyIntoProject(
taken: Set<string>,
): Promise<string> {
const src = await libraryMediaObject(userId, libFileName);
- if (!src) throw new Error("Library asset not found.");
+ if (!src) throw new UserError("library_asset_not_found", "Library asset not found.");
const over = await quotaCheck(userId, Number(src.bytes));
if (over) throw new HttpResponseError(over);
const dest = dedupeName(safeFileName(libFileName), taken);
@@ -398,7 +399,7 @@ export const libraryCloud = {
if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {
return err("fileName and bytes are required.", 400);
}
- if (!libraryTypeOf(body.fileName)) return err("Unsupported file type.", 400);
+ if (!libraryTypeOf(body.fileName)) return err(new UserError("file_type_unsupported", "Unsupported file type."), 400);
// A resumed upload already holds its claim: the client kept the bytes
// (the iOS app's journal) and asks for a fresh URL under the same name.
// A claim that completed in the meantime reports done and uploads
@@ -439,7 +440,7 @@ export const libraryCloud = {
});
return Response.json({ fileName, key, url });
} catch (e) {
- return caught(e, "Could not presign the upload.");
+ return caught(e, new UserError("upload_presign_failed", "Could not presign the upload."));
}
},
@@ -462,13 +463,13 @@ export const libraryCloud = {
const folder = await prisma.cutFolder.findFirst({
where: { id: folderId, userId, scope: "library" },
});
- if (!folder) return err("Folder not found.", 404);
+ if (!folder) return err(new UserError("folder_not_found", "Folder not found."), 404);
destFolder = folderId;
}
const obj = await prisma.cutMediaObject.findFirst({
where: { userId, r2Key: key },
});
- if (!obj) return err("Unknown upload.", 404);
+ if (!obj) return err(new UserError("upload_unknown", "Unknown upload."), 404);
// A retried complete (the iOS app reconciling after an interrupted
// sync) lands on the asset it already made instead of minting a twin.
const already = await prisma.cutLibraryAsset.findFirst({
@@ -477,7 +478,7 @@ export const libraryCloud = {
if (already) return Response.json(assetView(already, obj));
const info = obj.uploadState === "complete" ? null : await head(key);
if (obj.uploadState !== "complete" && !info)
- return err("The upload never arrived.", 400);
+ return err(new UserError("upload_never_arrived", "The upload never arrived."), 400);
// A cover that came up alongside the file: its own object, finished the
// same way, named on the asset so the delete cascade takes it too.
const posterObj = posterKey
@@ -543,7 +544,7 @@ export const libraryCloud = {
});
return Response.json(assetView(row, obj));
} catch (e) {
- return caught(e, "Could not complete the upload.");
+ return caught(e, new UserError("upload_complete_failed", "Could not complete the upload."));
}
},
@@ -557,13 +558,13 @@ export const libraryCloud = {
const asset = await prisma.cutLibraryAsset.findFirst({
where: { id: assetId, userId, deletedAt: null },
});
- if (!asset) throw new Error("Library asset not found.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
const obj = await prisma.cutMediaObject.findUnique({
where: { id: asset.mediaObjectId },
});
- if (!obj) throw new Error("Library asset not found.");
+ if (!obj) throw new UserError("library_asset_not_found", "Library asset not found.");
if (!(await getProject(userId, projectId)))
- throw new Error("Project not found.");
+ throw new UserError("project_not_found", "Project not found.");
const fileName = await copyIntoProject(
userId,
projectId,
@@ -572,7 +573,7 @@ export const libraryCloud = {
);
return Response.json({ fileName });
} catch (e) {
- return caught(e, "Could not add from library.");
+ return caught(e, new UserError("library_add_failed", "Could not add from library."));
}
},
@@ -585,7 +586,7 @@ export const libraryCloud = {
name?: string;
};
const src = await projectMediaObject(userId, projectId, fileName);
- if (!src) throw new Error("Media file not found in project.");
+ if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
const project = await getProject(userId, projectId);
const docAsset = (
project?.doc as { assets?: StoredAsset[] } | undefined
@@ -596,7 +597,7 @@ export const libraryCloud = {
await takenLibraryNames(userId),
);
const obj = await libraryMediaObject(userId, dest);
- if (!obj) throw new Error("Could not save to library.");
+ if (!obj) throw new UserError("library_save_failed", "Could not save to library.");
const row = await prisma.cutLibraryAsset.create({
data: {
userId,
@@ -613,7 +614,7 @@ export const libraryCloud = {
});
return Response.json(assetView(row, obj));
} catch (e) {
- return caught(e, "Could not save to library.");
+ return caught(e, new UserError("library_save_failed", "Could not save to library."));
}
},
@@ -631,11 +632,11 @@ export const libraryCloud = {
const asset = await prisma.cutLibraryAsset.findFirst({
where: { id, userId, deletedAt: null },
});
- if (!asset) throw new Error("Library asset not found.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
const obj = await prisma.cutMediaObject.findUnique({
where: { id: asset.mediaObjectId },
});
- if (!obj) throw new Error("Library asset not found.");
+ if (!obj) throw new UserError("library_asset_not_found", "Library asset not found.");
const positive = (v: unknown) =>
typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
const meta = { ...((asset.meta ?? {}) as AssetMeta) };
@@ -660,7 +661,7 @@ export const libraryCloud = {
});
return Response.json(assetView({ ...asset, meta }, obj));
} catch (e) {
- return caught(e, "Could not update the library asset.");
+ return caught(e, new UserError("library_asset_update_failed", "Could not update the library asset."));
}
},
@@ -675,7 +676,7 @@ export const libraryCloud = {
const folder = await prisma.cutFolder.findFirst({
where: { id: folderId, userId, scope: "library" },
});
- if (!folder) throw new Error("Folder not found.");
+ if (!folder) throw new UserError("folder_not_found", "Folder not found.");
}
const asset = await prisma.cutLibraryAsset.findFirst({
where: { id, userId, deletedAt: null },
@@ -688,7 +689,7 @@ export const libraryCloud = {
return Response.json({ ok: true });
}
const template = await findTemplate(userId, id);
- if (!template) throw new Error("Library item not found.");
+ if (!template) throw new UserError("library_item_not_found", "Library item not found.");
const doc = template.doc as unknown as TemplateDoc;
await prisma.cutTemplate.update({
where: { id },
@@ -696,7 +697,7 @@ export const libraryCloud = {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not move item.");
+ return caught(e, new UserError("library_item_move_failed", "Could not move item."));
}
},
@@ -710,12 +711,12 @@ export const libraryCloud = {
const compat = compatCoverIn(asked);
if (asked !== undefined && !compat) return err("compat is audio or video.", 400);
const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId, deletedAt: null } });
- if (!asset) return err("Library asset not found.", 404);
+ if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
const obj = await prisma.cutMediaObject.findFirst({ where: { id: asset.mediaObjectId, userId } });
- if (!obj) return err("Library asset not found.", 404);
+ if (!obj) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
const view = assetView(asset, obj);
const takes = view.type === "video" || (compat === "audio" && view.type === "audio");
- if (!takes) return err("Only a video takes a playable copy.", 400);
+ if (!takes) return err(new UserError("playable_copy_video_only", "Only a video takes a playable copy."), 400);
if (view.proxyFile && (!compat || compatCovers(view.proxyFile, compat))) return Response.json(view);
const jobId = libraryProxyJobId(id);
const existing = await prisma.cutRenderJob.findFirst({ where: { id: jobId, userId } });
@@ -738,7 +739,7 @@ export const libraryCloud = {
wakeRenderWorker();
return Response.json({ jobId });
} catch (e) {
- return caught(e, "Could not make the playable copy.");
+ return caught(e, new UserError("playable_copy_make_failed", "Could not make the playable copy."));
}
},
@@ -749,7 +750,7 @@ export const libraryCloud = {
await deleteLibraryAssetCascade(userId, id, { tombstone: true });
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete.");
+ return caught(e, new UserError("library_delete_failed", "Could not delete."));
}
},
@@ -791,7 +792,7 @@ export const libraryCloud = {
expiresIn: mediaUrlLifetime(),
});
} catch (e) {
- return caught(e, "Could not sign the library URLs.");
+ return caught(e, new UserError("library_urls_sign_failed", "Could not sign the library URLs."));
}
},
@@ -822,7 +823,7 @@ export const libraryCloud = {
parentId?: string | null;
};
const trimmed = (name ?? "").trim();
- if (!trimmed) throw new Error("Folder name required.");
+ if (!trimmed) throw new UserError("folder_name_required", "Folder name required.");
const folders = await prisma.cutFolder.findMany({
where: { userId, scope: "library" },
select: { id: true, parentId: true },
@@ -837,7 +838,7 @@ export const libraryCloud = {
});
return Response.json(libraryFolderView(row));
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
},
@@ -850,12 +851,12 @@ export const libraryCloud = {
parentId?: string | null;
};
const trimmed = name?.trim();
- if (name !== undefined && !trimmed) throw new Error("Folder name required.");
+ if (name !== undefined && !trimmed) throw new UserError("folder_name_required", "Folder name required.");
const folders = await prisma.cutFolder.findMany({
where: { userId, scope: "library" },
select: { id: true, parentId: true },
});
- if (!folders.some((f) => f.id === id)) throw new Error("Folder not found.");
+ if (!folders.some((f) => f.id === id)) throw new UserError("folder_not_found", "Folder not found.");
const updated = await prisma.cutFolder.update({
where: { id },
data: {
@@ -867,7 +868,7 @@ export const libraryCloud = {
});
return Response.json(libraryFolderView(updated));
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
},
@@ -908,7 +909,7 @@ export const libraryCloud = {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
},
@@ -922,8 +923,8 @@ export const libraryCloud = {
projectId: string;
} & TemplateInput;
if (!(await getProject(userId, projectId)))
- throw new Error("Project not found.");
- if (templateEmpty(input)) throw new Error("Nothing to save.");
+ throw new UserError("project_not_found", "Project not found.");
+ if (templateEmpty(input)) throw new UserError("template_nothing_to_save", "Nothing to save.");
// Every source is resolved and the whole batch checked against the quota
// before the first copy, so the wall is met with nothing written; a
// copy that still fails takes the ones before it back with it, since a
@@ -931,7 +932,7 @@ export const libraryCloud = {
const sources = await Promise.all(
input.media.map(async (m) => {
const src = await projectMediaObject(userId, projectId, m.fileName);
- if (!src) throw new Error("Media file not found in project.");
+ if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
return { m, src };
}),
);
@@ -979,7 +980,7 @@ export const libraryCloud = {
});
return Response.json(templateView(row));
} catch (e) {
- return caught(e, "Could not save the template.");
+ return caught(e, new UserError("template_save_failed", "Could not save the template."));
}
},
@@ -991,7 +992,7 @@ export const libraryCloud = {
keys?: string[];
folderId?: string | null;
};
- if (templateEmpty(input)) throw new Error("Nothing to add.");
+ if (templateEmpty(input)) throw new UserError("template_nothing_to_add", "Nothing to add.");
const media: TemplateMedia[] = [];
for (const [i, m] of (input.media ?? []).entries()) {
const key = keys?.[i];
@@ -1000,10 +1001,10 @@ export const libraryCloud = {
where: { userId, r2Key: key },
})
: null;
- if (!obj) throw new Error("Template media missing.");
+ if (!obj) throw new UserError("template_media_missing", "Template media missing.");
if (obj.uploadState !== "complete") {
const info = await head(key!);
- if (!info) throw new Error("The upload never arrived.");
+ if (!info) throw new UserError("upload_never_arrived", "The upload never arrived.");
await prisma.$transaction(async (tx) => {
await tx.cutMediaObject.update({
where: { id: obj.id },
@@ -1038,7 +1039,7 @@ export const libraryCloud = {
});
return Response.json(templateView(row));
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
},
@@ -1048,9 +1049,9 @@ export const libraryCloud = {
try {
const { projectId } = (await req.json()) as { projectId: string };
if (!(await getProject(userId, projectId)))
- throw new Error("Project not found.");
+ throw new UserError("project_not_found", "Project not found.");
const row = await findTemplate(userId, id);
- if (!row) throw new Error("Template not found.");
+ if (!row) throw new UserError("template_not_found", "Template not found.");
const template = templateView(row);
// The whole batch against the quota before the first copy; a project
// copy that still fails is unreferenced project media, which the sweep
@@ -1058,7 +1059,7 @@ export const libraryCloud = {
let incoming = 0;
for (const m of template.media) {
const src = await libraryMediaObject(userId, m.fileName);
- if (!src) throw new Error("Library asset not found.");
+ if (!src) throw new UserError("library_asset_not_found", "Library asset not found.");
incoming += Number(src.bytes);
}
const over = await quotaCheck(userId, incoming);
@@ -1076,7 +1077,7 @@ export const libraryCloud = {
}
return Response.json({ template, media });
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
},
@@ -1091,13 +1092,13 @@ export const libraryCloud = {
extend: number;
};
const row = await findTemplate(userId, id);
- if (!row) throw new Error("Template not found.");
+ if (!row) throw new UserError("template_not_found", "Template not found.");
const src = await projectMediaObject(
userId,
projectId,
input.media.fileName,
);
- if (!src) throw new Error("Media file not found in project.");
+ if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
const dest = await copyIntoLibrary(
userId,
src,
@@ -1129,7 +1130,7 @@ export const libraryCloud = {
});
return Response.json(templateView(updated));
} catch (e) {
- return caught(e, "Could not add to the template.");
+ return caught(e, new UserError("template_append_failed", "Could not add to the template."));
}
},
@@ -1138,14 +1139,14 @@ export const libraryCloud = {
const { name } = (await req.json()) as { name?: string };
const next = itemName(name);
const row = await findTemplate(userId, id);
- if (!row) throw new Error("Template not found.");
+ if (!row) throw new UserError("template_not_found", "Template not found.");
const updated = await prisma.cutTemplate.update({
where: { id },
data: { name: next },
});
return Response.json(templateView(updated));
} catch (e) {
- return caught(e, "Could not rename the template.");
+ return caught(e, new UserError("template_rename_failed", "Could not rename the template."));
}
},
@@ -1155,7 +1156,7 @@ export const libraryCloud = {
if (row) await deleteTemplateCascade(userId, row);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the template.");
+ return caught(e, new UserError("template_delete_failed", "Could not delete the template."));
}
},
};
diff --git a/site/src/cut/server/cloud/librarySharing.ts b/site/src/cut/server/cloud/librarySharing.ts
index 7ba78f9c..ea19dc16 100644
--- a/site/src/cut/server/cloud/librarySharing.ts
+++ b/site/src/cut/server/cloud/librarySharing.ts
@@ -10,9 +10,10 @@ import {
import { libraryShareAccess, sharedFolderTrail } from "@/cut/server/cloud/libraryShareAccess";
import { assetView, templateView } from "@/cut/server/cloud/library";
import { mediaObjectUrl } from "@/cut/server/cloud/mediaCdn";
+import { UserError, errorBody } from "@/cut/lib/userError";
const privateHeaders = { "Cache-Control": "private, no-store", Vary: "Cookie" };
-const err = (error: string, status: number) => Response.json({ error }, { status, headers: privateHeaders });
+const err = (failure: string | UserError, status: number) => Response.json(errorBody(failure, ""), { status, headers: privateHeaders });
const json = (body: unknown) => Response.json(body, { headers: privateHeaders });
const tokenSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/);
const querySchema = z.object({
@@ -193,7 +194,7 @@ export function createLibrarySharing(
if (!settings.success || !target.success) return err("Not found.", 404);
const session = share.access === "public" ? null : await getSession(req.headers);
const status = libraryShareAccess({ ...settings.data, userId: share.userId }, session?.user ?? null);
- if (status !== 200) return err(status === 401 ? "Sign in to view this share." : "You don't have access to this share.", status);
+ if (status !== 200) return err(status === 401 ? new UserError("share_sign_in", "Sign in to view this share.") : new UserError("share_no_access", "You don't have access to this share."), status);
if (!(await ownedTarget(share.userId, target.data))) return err("Not found.", 404);
return { share, target: target.data };
}
diff --git a/site/src/cut/server/cloud/libraryUpload.ts b/site/src/cut/server/cloud/libraryUpload.ts
index e6f1340c..4175a081 100644
--- a/site/src/cut/server/cloud/libraryUpload.ts
+++ b/site/src/cut/server/cloud/libraryUpload.ts
@@ -4,6 +4,7 @@ import { assetView } from "@/cut/server/cloud/library";
import { renderJobCheck } from "@/cut/server/cloud/limits";
import { head } from "@/cut/server/cloud/r2";
import { err } from "@/cut/server/cloud/util";
+import { UserError } from "@/cut/lib/userError";
import { wakeRenderWorker } from "@/cut/server/cloud/wake";
import { prisma } from "@/lib/prisma";
@@ -23,12 +24,12 @@ export function createLibraryUploadPreparation({
const object = await db.cutMediaObject.findFirst({
where: { userId, r2Key: input.key, kind: "library", projectId: null },
});
- if (!object) return err("Unknown upload.", 404);
+ if (!object) return err(new UserError("upload_unknown", "Unknown upload."), 404);
const type = libraryTypeOf(object.fileName);
- if (type !== "video" && type !== "audio") return err("This upload has no video or audio.", 400);
+ if (type !== "video" && type !== "audio") return err(new UserError("upload_no_video_audio", "This upload has no video or audio."), 400);
if (input.folderId && !(await db.cutFolder.findFirst({
where: { id: input.folderId, userId, scope: "library" }, select: { id: true },
- }))) return err("Folder not found.", 404);
+ }))) return err(new UserError("folder_not_found", "Folder not found."), 404);
const id = libraryUploadId(object.id);
const asset = await db.cutLibraryAsset.findFirst({ where: { id, userId, deletedAt: null } });
@@ -36,14 +37,14 @@ export function createLibraryUploadPreparation({
const media = await db.cutMediaObject.findFirst({ where: { id: asset.mediaObjectId, userId } });
if (media) return Response.json(assetView(asset, media));
}
- if (object.uploadState !== "pending") return err("This file is already in the Library.", 409);
+ if (object.uploadState !== "pending") return err(new UserError("library_file_exists", "This file is already in the Library."), 409);
const existing = await db.cutRenderJob.findFirst({ where: { id, userId } });
if (existing && (existing.state === "queued" || existing.state === "running")) {
wake();
return Response.json({ jobId: id });
}
const info = await inspect(input.key);
- if (!info || info.bytes !== Number(object.bytes)) return err("The upload is incomplete. Select the file again.", 400);
+ if (!info || info.bytes !== Number(object.bytes)) return err(new UserError("upload_incomplete", "The upload is incomplete. Select the file again."), 400);
const capped = await checkLimit(userId);
if (capped) return capped;
const spec = { ...input, target: "library", objectId: object.id };
diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.ts
index e6e9617e..a7ab1f4a 100644
--- a/site/src/cut/server/cloud/media.ts
+++ b/site/src/cut/server/cloud/media.ts
@@ -8,6 +8,9 @@ import { getProject, takenMediaNames } from "./projects";
import { head, presignPut, projectMediaKey, putObject } from "./r2";
import { addUsage, quotaCheck } from "./usage";
import { caught, dedupeName, err, safeFileName, storableFileName } from "./util";
+import { UserError } from "@/cut/lib/userError";
+
+const projectNotFound = () => new UserError("project_not_found", "Project not found.");
/** Direct-upload cap: anything larger goes through presign. */
const INLINE_UPLOAD_BYTES = 3.5 * 1024 * 1024;
@@ -66,7 +69,7 @@ export const mediaCloud = {
if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {
return err("fileName and bytes are required.", 400);
}
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(projectNotFound(), 404);
// A resumed upload already holds its name: the browser kept the bytes
// across a reload and asks for a fresh URL for the same claim. Re-mint
// against the claimed key so the name never shifts; a claim that
@@ -117,7 +120,7 @@ export const mediaCloud = {
});
return Response.json({ fileName, key, url });
} catch (e) {
- return caught(e, "Could not presign the upload.");
+ return caught(e, new UserError("upload_presign_failed", "Could not presign the upload."));
}
},
@@ -128,10 +131,10 @@ export const mediaCloud = {
const { key } = (await req.json()) as { key?: string };
if (!key) return err("key is required.", 400);
const row = await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: key } });
- if (!row) return err("Unknown upload.", 404);
+ if (!row) return err(new UserError("upload_unknown", "Unknown upload."), 404);
if (row.uploadState === "complete") return Response.json({ fileName: row.fileName });
const info = await head(key);
- if (!info) return err("The upload never arrived.", 400);
+ if (!info) return err(new UserError("upload_never_arrived", "The upload never arrived."), 400);
await prisma.$transaction(async (tx) => {
await tx.cutMediaObject.update({
where: { id: row.id },
@@ -145,7 +148,7 @@ export const mediaCloud = {
});
return Response.json({ fileName: row.fileName });
} catch (e) {
- return caught(e, "Could not complete the upload.");
+ return caught(e, new UserError("upload_complete_failed", "Could not complete the upload."));
}
},
@@ -190,7 +193,7 @@ export const mediaCloud = {
});
return Response.json({ urls, expiresIn: mediaUrlLifetime() });
} catch (e) {
- return caught(e, "Could not sign the media URLs.");
+ return caught(e, new UserError("media_sign_failed", "Could not sign the media URLs."));
}
},
@@ -198,7 +201,7 @@ export const mediaCloud = {
* return the MediaAsset shape. Larger callers use presign. */
async importImage(userId: string, projectId: string, req: Request) {
try {
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(projectNotFound(), 404);
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No image in upload.", 400);
@@ -243,7 +246,7 @@ export const mediaCloud = {
...(origin ? { origin } : {}),
});
} catch (e) {
- return caught(e, "Could not import the image.");
+ return caught(e, new UserError("image_import_failed", "Could not import the image."));
}
},
};
diff --git a/site/src/cut/server/cloud/notes.ts b/site/src/cut/server/cloud/notes.ts
index d15ec3f0..530b04a7 100644
--- a/site/src/cut/server/cloud/notes.ts
+++ b/site/src/cut/server/cloud/notes.ts
@@ -13,6 +13,7 @@ import { Prisma } from "@/generated/prisma/client";
import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";
import { NOTE_LABELS_MAX } from "@/cut/lib/types";
import { prisma } from "@/lib/prisma";
+import { UserError } from "@/cut/lib/userError";
import { caught, err } from "./util";
export interface NoteView {
@@ -161,7 +162,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
},
async get(userId: string, id: string) {
const row = await db.cutNote.findFirst({ where: { id, userId, deletedAt: null } });
- return row ? Response.json(view(row)) : err("Note not found.", 404);
+ return row ? Response.json(view(row)) : err(new UserError("note_not_found", "Note not found."), 404);
},
/** Every note including tombstones, newest first, and the folders they file
* into. Notes are small and the set is one person's, so the merge reads the
@@ -206,13 +207,18 @@ export function createNotesCloud(db: typeof prisma = prisma) {
const location = body.libraryLocation === undefined ? undefined
: parsedLocation?.success ? parsedLocation.data : null;
if (location?.residency === "cloud" && location.folderId !== null && !await db.cutFolder.findFirst({ where: { id: location.folderId, userId, scope: "library" }, select: { id: true } })) {
- return err("Library folder not found.", 404);
+ return err(new UserError("library_folder_not_found", "Library folder not found."), 404);
}
// Over the cap the write is refused outright: truncating here would
// answer 200 with a note wearing fewer labels than the person gave it,
// and the merge would carry that loss back to their other device.
if (Array.isArray(body.labelIds) && new Set(body.labelIds).size > NOTE_LABELS_MAX) {
- return err(`A note can carry at most ${NOTE_LABELS_MAX} labels.`, 400);
+ return err(
+ new UserError("note_labels_too_many", `A note can carry at most ${NOTE_LABELS_MAX} labels.`, {
+ max: NOTE_LABELS_MAX,
+ }),
+ 400
+ );
}
const labelIds = await resolveLabels(db, userId, body.labelIds);
const data = {
@@ -241,7 +247,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
});
return Response.json(view(row));
} catch (e) {
- return caught(e, "Could not save the note.");
+ return caught(e, new UserError("note_save_failed", "Could not save the note."));
}
},
@@ -257,7 +263,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the note.");
+ return caught(e, new UserError("note_delete_failed", "Could not delete the note."));
}
},
@@ -273,7 +279,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
if (!NOTE_ID.test(id)) return err("Invalid folder id.", 400);
const body = (await req.json()) as { name?: string; parentId?: string | null };
const name = String(body.name ?? "").trim().slice(0, 120);
- if (!name) return err("Folder name required.", 400);
+ if (!name) return err(new UserError("folder_name_required", "Folder name required."), 400);
const existing = await db.cutFolder.findFirst({
where: { id, userId, scope: "note" },
select: { id: true, parentId: true },
@@ -291,7 +297,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
const row = await db.cutFolder.update({ where: { id }, data: { name, parentId } });
return Response.json(folderView(row));
} catch (e) {
- return caught(e, "Could not save the folder.");
+ return caught(e, new UserError("note_folder_save_failed", "Could not save the folder."));
}
},
@@ -316,7 +322,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the folder.");
+ return caught(e, new UserError("note_folder_delete_failed", "Could not delete the folder."));
}
},
@@ -330,7 +336,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
if (!NOTE_ID.test(id)) return err("Invalid label id.", 400);
const body = (await req.json()) as { name?: string };
const name = String(body.name ?? "").trim().slice(0, 60);
- if (!name) return err("Label name required.", 400);
+ if (!name) return err(new UserError("label_name_required", "Label name required."), 400);
const existing = await db.cutNoteLabel.findFirst({
where: { id, userId },
select: { id: true },
@@ -342,7 +348,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
const row = await db.cutNoteLabel.update({ where: { id }, data: { name } });
return Response.json(labelView(row));
} catch (e) {
- return caught(e, "Could not save the label.");
+ return caught(e, new UserError("label_save_failed", "Could not save the label."));
}
},
@@ -367,7 +373,7 @@ export function createNotesCloud(db: typeof prisma = prisma) {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the label.");
+ return caught(e, new UserError("label_delete_failed", "Could not delete the label."));
}
},
};
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index c25f45c4..95c492c1 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -8,10 +8,13 @@ import { OUTPUT_SPACES } from "@donkeycut/effects-kit";
import { isTimelineId, normalizeAspect, sanitizeTimelines, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import { defaultNames } from "@/cut/lib/defaultNames";
+import { creatorLocaleOf } from "./creatorLocale";
import { deleteLadder } from "./ladderStore";
import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl } from "./mediaCdn";
import { del, deletePrefix, projectPrefix, projectMediaKey } from "./r2";
import { addUsage } from "./usage";
+import { UserError } from "@/cut/lib/userError";
import { caught, decodeFileParam, err, redirect } from "./util";
const projectFolderView = (row: {
@@ -29,6 +32,11 @@ const projectFolderView = (row: {
const HTTP_BAD_REQUEST = 400;
const HTTP_NOT_FOUND = 404;
+// Refusals the projects home reads, coded so the page words them.
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
+const FOLDER_NOT_FOUND = new UserError("folder_not_found", "Folder not found.");
+const FOLDER_NAME_REQUIRED = new UserError("folder_name_required", "Folder name required.");
+
// Writer ids are the transport's crypto.randomUUID().
const WRITER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const WRITER_SEQ = /^[1-9][0-9]{0,8}$/;
@@ -234,11 +242,13 @@ export const projectsCloud = {
async create(userId: string, req: Request) {
try {
- const { name, folderId, aspect } = (await req.json()) as {
+ const { name, folderId, aspect, locale } = (await req.json()) as {
name?: string;
folderId?: string | null;
aspect?: string;
+ locale?: string;
};
+ const untitled = name?.trim() ? "" : (await defaultNames(await creatorLocaleOf(userId, locale))).untitled;
const folder = folderId
? await prisma.cutFolder.findFirst({ where: { id: folderId, userId, scope: "project" } })
: null;
@@ -246,7 +256,7 @@ export const projectsCloud = {
const now = Date.now();
const doc: ProjectDoc = {
version: 1,
- name: (name ?? "Untitled").trim() || "Untitled",
+ name: name?.trim() || untitled,
createdAt: now,
updatedAt: now,
assets: [],
@@ -260,18 +270,18 @@ export const projectsCloud = {
});
return Response.json(summarize(row, 0));
} catch (e) {
- return caught(e, "Could not create project.");
+ return caught(e, new UserError("project_create_failed", "Could not create project."));
}
},
async get(userId: string, id: string, req: Request) {
if (req.method === "HEAD") {
const row = await prisma.cutProject.findFirst({ where: { id, userId }, select: { version: true } });
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
return new Response(null, { headers: { "x-cut-doc-version": String(row.version) } });
}
const row = await getProject(userId, id);
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
return Response.json(docOf(row), {
headers: { "x-cut-doc-version": String(row.version) },
});
@@ -283,7 +293,7 @@ export const projectsCloud = {
async put(userId: string, id: string, req: Request) {
try {
const row = await getProject(userId, id);
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
const vParam = new URL(req.url).searchParams.get("v");
const writer = writerOf(req);
if (writer === "invalid") {
@@ -331,25 +341,25 @@ export const projectsCloud = {
// write raced the guarded update.
const current = base ? await getProject(userId, id) : row;
if (!current) {
- return err("Project not found.", HTTP_NOT_FOUND);
+ return err(PROJECT_NOT_FOUND, HTTP_NOT_FOUND);
}
return Response.json(
{ error: "conflict", doc: docOf(current), version: current.version },
{ status: HTTP_CONFLICT }
);
} catch (e) {
- return caught(e, "Could not save project.");
+ return caught(e, new UserError("project_save_failed", "Could not save project."));
}
},
async remove(userId: string, id: string) {
try {
const row = await getProject(userId, id);
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
await deleteProjectCascade(userId, id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete project.");
+ return caught(e, new UserError("project_delete_failed", "Could not delete project."));
}
},
@@ -357,17 +367,17 @@ export const projectsCloud = {
try {
const { folderId } = (await req.json()) as { folderId: string | null };
const row = await getProject(userId, id);
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
if (folderId) {
const folder = await prisma.cutFolder.findFirst({
where: { id: folderId, userId, scope: "project" },
});
- if (!folder) return err("Folder not found.", 500);
+ if (!folder) return err(FOLDER_NOT_FOUND, 500);
}
await prisma.cutProject.update({ where: { id }, data: { folderId: folderId ?? null } });
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not move project.");
+ return caught(e, new UserError("project_move_failed", "Could not move project."));
}
},
@@ -383,7 +393,7 @@ export const projectsCloud = {
try {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
+ if (!trimmed) return err(FOLDER_NAME_REQUIRED, 500);
const folders = await prisma.cutFolder.findMany({
where: { userId, scope: "project" },
select: { id: true, parentId: true },
@@ -398,7 +408,7 @@ export const projectsCloud = {
});
return Response.json(projectFolderView(row));
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
},
@@ -408,12 +418,12 @@ export const projectsCloud = {
try {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = name?.trim();
- if (name !== undefined && !trimmed) return err("Folder name required.", 500);
+ if (name !== undefined && !trimmed) return err(FOLDER_NAME_REQUIRED, 500);
const folders = await prisma.cutFolder.findMany({
where: { userId, scope: "project" },
select: { id: true, parentId: true },
});
- if (!folders.some((f) => f.id === id)) return err("Folder not found.", 500);
+ if (!folders.some((f) => f.id === id)) return err(FOLDER_NOT_FOUND, 500);
const updated = await prisma.cutFolder.update({
where: { id },
data: {
@@ -423,7 +433,7 @@ export const projectsCloud = {
});
return Response.json(projectFolderView(updated));
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
},
@@ -449,7 +459,7 @@ export const projectsCloud = {
});
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
},
@@ -491,7 +501,7 @@ export const projectsCloud = {
}
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the media file.");
+ return caught(e, new UserError("media_delete_failed", "Could not delete the media file."));
}
},
@@ -545,7 +555,7 @@ export const projectsCloud = {
}
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the export.");
+ return caught(e, new UserError("export_delete_failed", "Could not delete the export."));
}
},
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 4ec65cc4..7a82c747 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -9,6 +9,7 @@ import { librarySharing } from "@/cut/server/cloud/librarySharing";
import { type DonkeyAuthenticatedRequest } from "@/lib/donkey-api-auth";
import { isDonkeySuperUser } from "@/lib/super-user";
import { matchRouteTable, type RouteEntry } from "../http/match";
+import { accountCloud } from "./account";
import { captionsCloud } from "./captions";
import { chatsCloud } from "./chats";
import { commandsCloud } from "./commands";
@@ -134,6 +135,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "PUT", path: "/api/cut-cloud/notes/:id", handler: (r, u, p) => notesCloud.put(u, p.id, r) },
{ method: "DELETE", path: "/api/cut-cloud/notes/:id", handler: (_r, u, p) => notesCloud.remove(u, p.id) },
{ method: "GET", path: "/api/cut-cloud/phone", handler: (_r, u) => phoneApi.get(u) },
+ { method: "PUT", path: "/api/cut-cloud/account/locale", handler: (r, u) => accountCloud.setLocale(u, r) },
{ method: "POST", path: "/api/cut-cloud/transcribe", handler: (r, u) => transcribeCloud.transcribe(u, r) },
{ method: "POST", path: "/api/cut-cloud/ai/captions", handler: (r, u) => captionsCloud.captions(u, r) },
diff --git a/site/src/cut/server/cloud/share.ts b/site/src/cut/server/cloud/share.ts
index b2fac9be..858c93f1 100644
--- a/site/src/cut/server/cloud/share.ts
+++ b/site/src/cut/server/cloud/share.ts
@@ -5,6 +5,7 @@ import { randomBytes } from "node:crypto";
import { isTimelineId, type ShareFeatures } from "@/cut/lib/types";
import { prisma } from "@/lib/prisma";
import { getProject } from "./projects";
+import { UserError } from "@/cut/lib/userError";
import { caught, err } from "./util";
export type ShareAccess = "restricted" | "public";
@@ -57,16 +58,19 @@ const shareJson = (row: ShareRow) => ({
features: normalizeFeatures(row.features),
});
+// The share dialog reads this refusal, coded so the page words it.
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
+
export const shareCloud = {
async get(userId: string, projectId: string) {
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(PROJECT_NOT_FOUND, 404);
const row = await prisma.cutProjectShare.findUnique({ where: { projectId } });
return Response.json({ share: row && row.userId === userId ? shareJson(row) : null });
},
async put(userId: string, projectId: string, req: Request) {
try {
- if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ if (!(await getProject(userId, projectId))) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as {
access?: unknown;
emails?: unknown;
@@ -84,7 +88,7 @@ export const shareCloud = {
});
return Response.json({ share: shareJson(row) });
} catch (e) {
- return caught(e, "Could not save the share.");
+ return caught(e, new UserError("share_save_failed", "Could not save the share."));
}
},
@@ -93,7 +97,7 @@ export const shareCloud = {
await prisma.cutProjectShare.deleteMany({ where: { projectId, userId } });
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not remove the share.");
+ return caught(e, new UserError("share_remove_failed", "Could not remove the share."));
}
},
};
diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.ts
index f8823f39..07546249 100644
--- a/site/src/cut/server/cloud/sharedView.ts
+++ b/site/src/cut/server/cloud/sharedView.ts
@@ -13,9 +13,14 @@ import { mediaObjectUrl, mediaTreeUrl, mediaUrlLifetime } from "./mediaCdn";
import { projectHlsPrefix, projectMediaKey } from "./r2";
import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";
import { shareCacheHeaders, shareRedirectHeaders } from "./shareCache";
+import { UserError } from "@/cut/lib/userError";
import { caught, decodeFileParam, err, redirect } from "./util";
const PRESIGN_GET_BATCH_MAX = 500;
+
+// Refusals the share viewer reads, coded so the page words them.
+const SHARE_NOT_FOUND = new UserError("share_not_found", "Share not found.");
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
/** How long a media redirect may be reused. Tokens are minted on window
* boundaries, so the redirect is reusable until the window turns over; this
* keeps it well inside that. */
@@ -34,17 +39,17 @@ interface ShareView {
* additionally needs a signed-in viewer who is the owner or an invitee.
* Returns the error Response to send when access fails. */
export async function resolveShare(token: string, req: Request): Promise<ShareView | Response> {
- if (!token || token.length > 64) return err("Share not found.", 404);
+ if (!token || token.length > 64) return err(SHARE_NOT_FOUND, 404);
const share = await prisma.cutProjectShare.findUnique({ where: { id: token } });
- if (!share) return err("Share not found.", 404);
+ if (!share) return err(SHARE_NOT_FOUND, 404);
const features = normalizeFeatures(share.features);
if (share.access === "public") return { share, features };
const session = await auth.api.getSession({ headers: req.headers });
- if (!session?.user) return err("Sign in to view this project.", 401);
+ if (!session?.user) return err(new UserError("share_sign_in_required", "Sign in to view this project."), 401);
const email = session.user.email?.toLowerCase() ?? "";
const invited = (normalizeEmails(share.emails) ?? []).includes(email);
if (session.user.id !== share.userId && !invited) {
- return err("You don't have access to this project.", 403);
+ return err(new UserError("share_access_denied", "You don't have access to this project."), 403);
}
return { share, features };
}
@@ -169,7 +174,7 @@ export const sharedView = {
const view = await resolveShare(token, req);
if (view instanceof Response) return view;
const row = await ownerProject(view.share);
- if (!row) return err("Share not found.", 404);
+ if (!row) return err(SHARE_NOT_FOUND, 404);
return Response.json(
{
projectId: view.share.projectId,
@@ -184,7 +189,7 @@ export const sharedView = {
async doc(token: string, id: string, req: Request) {
const view = await resolveShare(token, req);
if (view instanceof Response) return view;
- if (id !== view.share.projectId) return err("Project not found.", 404);
+ if (id !== view.share.projectId) return err(PROJECT_NOT_FOUND, 404);
// The viewer's 10s change-poll is a HEAD that only reads the version
// header. Serve it from a version-only select instead of reading and
// filtering the whole doc every tick.
@@ -193,7 +198,7 @@ export const sharedView = {
where: { id: view.share.projectId, userId: view.share.userId },
select: { version: true, updatedAt: true },
});
- if (!meta) return err("Project not found.", 404);
+ if (!meta) return err(PROJECT_NOT_FOUND, 404);
return new Response(null, {
headers: {
"x-cut-doc-version": String(meta.version),
@@ -202,7 +207,7 @@ export const sharedView = {
});
}
const row = await ownerProject(view.share);
- if (!row) return err("Project not found.", 404);
+ if (!row) return err(PROJECT_NOT_FOUND, 404);
return Response.json(filterDocForShare(row.doc as unknown as ProjectDoc, view.features), {
headers: {
"x-cut-doc-version": String(row.version),
diff --git a/site/src/cut/server/cloud/transcribe.ts b/site/src/cut/server/cloud/transcribe.ts
index 13f82ffc..2cbb3da9 100644
--- a/site/src/cut/server/cloud/transcribe.ts
+++ b/site/src/cut/server/cloud/transcribe.ts
@@ -25,6 +25,7 @@ import {
import { geminiModelRoles } from "@/lib/inference/gemini-models";
import { isJsonObject, toJsonValue } from "@/lib/inference/json";
import type { JsonValue } from "@/lib/inference/providers";
+import { UserError } from "@/cut/lib/userError";
import { err } from "./util";
// The client sends 16 kHz 16-bit mono PCM in chunks of at most 20 seconds; the
@@ -241,7 +242,7 @@ export const transcribeCloud = {
const clientConfig = geminiClientConfig(process.env);
if (!clientConfig.configured) {
- return err("Transcription is not configured on this deployment.", 500);
+ return err(new UserError("transcription_unconfigured", "Transcription is not configured on this deployment."), 500);
}
// Inside the allowance the chunk is on the house — no balance check, so a
@@ -306,7 +307,7 @@ export const transcribeCloud = {
const credit = creditErrorResponse(error);
if (credit) return credit;
const mapped = geminiApiError("Transcription failed.", error);
- return err(mapped.message, mapped.statusCode ?? 502);
+ return err(new UserError("transcription_failed", mapped.message), mapped.statusCode ?? 502);
}
// The call succeeded and spent tokens; record and charge before judging
@@ -332,7 +333,7 @@ export const transcribeCloud = {
const words = readWords(raw as JsonValue, audioSeconds);
if (words === null) {
- return err("The transcription model returned no word timings — try again.", 502);
+ return err(new UserError("transcription_no_timings", "The transcription model returned no word timings — try again."), 502);
}
return Response.json({ cues: groupWordsIntoCues(words) });
},
diff --git a/site/src/cut/server/cloud/turns.ts b/site/src/cut/server/cloud/turns.ts
index 690592f1..7f85169c 100644
--- a/site/src/cut/server/cloud/turns.ts
+++ b/site/src/cut/server/cloud/turns.ts
@@ -4,6 +4,7 @@
// queued/running row holds the project's agent write lease (lease.ts), and
// the generic /jobs/:jobId route serves the poll.
import type { Prisma } from "@/generated/prisma/client";
+import { DEFAULT_LOCALE, isLocale, type Locale } from "@/i18n/locales";
import { prisma } from "@/lib/prisma";
import { cutLimitsFor, liveJobCheck } from "./limits";
import { queueLeasedJob } from "./lease";
@@ -17,6 +18,17 @@ export interface AgentTurnSpec {
threadId: string;
messages: unknown[];
model?: string;
+ /** The interface language the reply is written in. */
+ locale?: Locale;
+}
+
+/** The language a turn replies in: the caller's, else the account's. */
+async function turnLocale(userId: string, asked: unknown): Promise<Locale> {
+ if (isLocale(asked)) {
+ return asked;
+ }
+ const user = await prisma.user.findUnique({ where: { id: userId }, select: { locale: true } });
+ return isLocale(user?.locale) ? user.locale : DEFAULT_LOCALE;
}
export const turnsCloud = {
@@ -57,6 +69,7 @@ export const turnsCloud = {
threadId,
messages: body.messages,
...(typeof body.model === "string" && body.model ? { model: body.model } : {}),
+ locale: await turnLocale(userId, body.locale),
};
const row = await queueLeasedJob(userId, projectId, "agent_turn", spec as unknown as Prisma.InputJsonValue);
if (row instanceof Response) return row;
diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.ts
index 61379f15..871acd82 100644
--- a/site/src/cut/server/cloud/util.ts
+++ b/site/src/cut/server/cloud/util.ts
@@ -2,9 +2,10 @@ import path from "node:path";
import { LadderStoreNotConfiguredError } from "./ladderStore";
import { MediaNotConfiguredError } from "./mediaCdn";
import { R2NotConfiguredError } from "./r2";
+import { errorBody, UserError } from "@/cut/lib/userError";
-export const err = (message: string, status: number) =>
- Response.json({ error: message }, { status });
+export const err = (failure: string | UserError, status: number) =>
+ Response.json(errorBody(failure, ""), { status });
/** A refusal raised deep inside a helper — a quota wall met halfway through a
* copy — carrying the exact response the route should answer with, so the
@@ -15,7 +16,7 @@ export class HttpResponseError extends Error {
}
}
-export const caught = (e: unknown, fallback: string, status = 500) => {
+export const caught = (e: unknown, fallback: string | UserError, status = 500) => {
if (e instanceof HttpResponseError) return e.response;
if (e instanceof R2NotConfiguredError) return err(e.message, 500);
// The real reason belongs in the server's logs, not in a response an
@@ -23,13 +24,13 @@ export const caught = (e: unknown, fallback: string, status = 500) => {
// 5xx also keeps the client's retry — a 4xx reads as "stop asking".
if (e instanceof MediaNotConfiguredError) {
console.error(e.message);
- return err("Cloud media is unavailable.", 500);
+ return err(new UserError("cloud_media_unavailable", "Cloud media is unavailable."), 500);
}
if (e instanceof LadderStoreNotConfiguredError) {
console.error(e.message);
- return err("Streaming is unavailable.", 500);
+ return err(new UserError("streaming_unavailable", "Streaming is unavailable."), 500);
}
- return err(e instanceof Error ? e.message : fallback, status);
+ return Response.json(errorBody(e, fallback), { status });
};
export const redirect = (url: string, headers: Record<string, string> = {}) =>
diff --git a/site/src/cut/server/convert.ts b/site/src/cut/server/convert.ts
index ed32447b..5e15e9d8 100644
--- a/site/src/cut/server/convert.ts
+++ b/site/src/cut/server/convert.ts
@@ -3,6 +3,7 @@ import { h264Encoder, runFfmpeg, vtQuality, type RenderHandle } from "./exportPi
import { assertGraphSafe } from "./filterGraph";
import type { ConvertMode } from "../lib/convertMode";
import { videoDimensions } from "./util";
+import { UserError } from "../lib/userError";
/**
* Re-wrapping one media file as an MP4 every player and every browser opens.
@@ -75,8 +76,8 @@ export function selectConversionStreams(streams: MediaStream[], formatName = "")
const audioTracks = streams.filter((s) => s.codec_type === "audio");
const knownAudio = audioTracks.filter((s) => s.codec_name && s.codec_name !== "unknown" && s.codec_tag_string !== "apac");
const audio = knownAudio.find((s) => s.disposition?.default) ?? knownAudio[0];
- if (audioTracks.length && !audio) throw new Error("This file has no supported audio track for conversion.");
- if (video && (!video.codec_name || video.codec_name === "unknown")) throw new Error("This file has no supported video track for conversion.");
+ if (audioTracks.length && !audio) throw new UserError("convert_no_audio_track", "This file has no supported audio track for conversion.");
+ if (video && (!video.codec_name || video.codec_name === "unknown")) throw new UserError("convert_no_video_track", "This file has no supported video track for conversion.");
return {
video: video?.codec_name,
audio: audio?.codec_name,
@@ -101,13 +102,13 @@ export function streamCodecs(file: string): Promise<ReturnType<typeof selectConv
let out = "";
const timer = setTimeout(() => {
p.kill("SIGKILL");
- reject(new Error("Media inspection timed out."));
+ reject(new UserError("media_inspect_timed_out", "Media inspection timed out."));
}, 30_000);
timer.unref();
p.stdout.on("data", (d) => (out += d));
p.on("close", (code) => {
clearTimeout(timer);
- if (code !== 0) return reject(new Error("Could not inspect this media file."));
+ if (code !== 0) return reject(new UserError("media_inspect_failed", "Could not inspect this media file."));
try {
const probe = JSON.parse(out) as { streams?: MediaStream[]; format?: { format_name?: string } };
resolve(selectConversionStreams(probe.streams ?? [], probe.format?.format_name));
@@ -129,7 +130,7 @@ export async function convertToMp4(
opts: { maxHeight?: number; mode?: ConvertMode; onProgress?: (seconds: number) => void } = {}
): Promise<ConvertOutcome> {
const [codecs, dims] = await Promise.all([streamCodecs(src), videoDimensions(src)]);
- if (!codecs.video && !codecs.audio) throw new Error("That file carries no video or audio.");
+ if (!codecs.video && !codecs.audio) throw new UserError("media_no_streams", "That file carries no video or audio.");
const cap = opts.maxHeight && opts.maxHeight > 0 ? Math.round(opts.maxHeight) : 0;
const shrink = !!(cap && dims && dims.height > cap);
diff --git a/site/src/cut/server/defaultNames.test.ts b/site/src/cut/server/defaultNames.test.ts
new file mode 100644
index 00000000..df76bb58
--- /dev/null
+++ b/site/src/cut/server/defaultNames.test.ts
@@ -0,0 +1,50 @@
+import { afterAll, expect, test } from "bun:test";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { translatorFor } from "@/i18n/translator";
+
+// A project the engine creates without a name is named in its creator's
+// language: the create request's locale picks the catalog. The temp data
+// root keeps the test off the user's own Movies folder.
+const root = await mkdtemp(path.join(os.tmpdir(), "cut-default-names-test-"));
+process.env.DONKEY_CUT_DATA_DIR = root;
+const { projectsApi } = await import("./http/projects");
+const projects = await import("./projects");
+afterAll(async () => { await rm(root, { recursive: true, force: true }); });
+
+const create = async (body: Record<string, unknown>) => {
+ const req = new Request("http://engine/api/cut/projects", { method: "POST", body: JSON.stringify(body) });
+ return (await (await projectsApi.create(req)).json()) as { id: string; name: string };
+};
+
+test("a headless project created in ja is named from the ja catalog", async () => {
+ const t = await translatorFor("ja", "errors");
+ const first = await create({ locale: "ja" });
+ const second = await create({ locale: "ja" });
+
+ expect(first.name).toBe(t("defaults.untitled"));
+ expect(second.name).toBe(t("defaults.untitled"));
+
+ // Two untitled projects take "<base>" and "<base> 2" folders in that language.
+ const dirs = await readdir(path.join(root, "projects"));
+ expect(dirs).toContain(t("defaults.untitled"));
+ expect(dirs).toContain(`${t("defaults.untitled")} 2`);
+});
+
+test("a create without a locale is named in the default language", async () => {
+ const t = await translatorFor("en", "errors");
+ expect((await create({})).name).toBe(t("defaults.untitled"));
+});
+
+test("a duplicate is named in its creator's language", async () => {
+ const t = await translatorFor("ja", "errors");
+ const { id } = await create({ name: "Trip" });
+ const req = new Request(`http://engine/api/cut/projects/${id}/duplicate`, {
+ method: "POST",
+ body: JSON.stringify({ locale: "ja" }),
+ });
+ const copy = (await (await projectsApi.duplicate(req, { id })).json()) as { id: string };
+ expect((await projects.readProject(copy.id))?.name).toBe(t("defaults.copy", { name: "Trip" }));
+});
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index 4e588b45..67bd9ab6 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -1,4 +1,5 @@
import { spawn, type ChildProcess } from "node:child_process";
+import { UserError, errorFromBody, type UserErrorParams } from "../lib/userError";
import { exportSourceFiles } from "./sourceExport";
import type { SourceSegment } from "../lib/sourceExportPlan";
import { deliveryCodec, deliveryContainer, deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor, type ExportCodec, type ExportRange, type SpecClipColor } from "../lib/exportDelivery";
@@ -440,10 +441,15 @@ export interface RenderHandle {
stemsPath?: string;
progress: number;
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
proc?: ChildProcess;
log: string[];
}
+/** H.264 carries 8 bits a channel, too few for an HDR master. */
+const h264Hdr = () => new UserError("export_h264_hdr", "H.264 is 8-bit. Export HDR as HEVC or ProRes.");
+
/** The H.264 encoder to use, probed once against the same `ffmpeg` the exports
* spawn. Prefer libx264 (CRF + presets) when the build carries it — the dev
* Homebrew ffmpeg does. The bundled engine ffmpeg is LGPL (`--disable-gpl`), so
@@ -541,10 +547,14 @@ export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {
: [];
switch (enc) {
case "libx264":
- if (hdr) throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");
+ if (hdr) {
+ throw h264Hdr();
+ }
return ["-c:v", "libx264", "-preset", spec.preset, ...(spec.bitrate ? rate : ["-crf", String(spec.crf)]), ...gop, "-profile:v", "high", "-pix_fmt", "yuv420p"];
case "h264_videotoolbox":
- if (hdr) throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");
+ if (hdr) {
+ throw h264Hdr();
+ }
return ["-c:v", "h264_videotoolbox", ...rate, ...gop, "-profile:v", "high", "-pix_fmt", "yuv420p", "-allow_sw", "1"];
case "libx265": {
// x265's CRF scale sits about four points above x264's for the same picture.
@@ -583,7 +593,7 @@ export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {
"-pix_fmt", full ? "yuv444p10le" : "yuv422p10le"];
}
default:
- throw new Error(`No encoder for ${codec}.`);
+ throw new UserError("export_no_encoder", `No encoder for ${codec}.`, { codec });
}
}
@@ -624,7 +634,9 @@ async function resolveMedia(
) {
const p = mediaPathFor(file);
const info = await statFn(p).catch(() => null);
- if (!info?.isFile()) throw new Error(`Media file missing from project: ${file}`);
+ if (!info?.isFile()) {
+ throw new UserError("export_media_missing", `Media file missing from project: ${file}`, { file });
+ }
return p;
}
@@ -979,7 +991,7 @@ export function runFfmpeg(
clearTimeout(watchdog);
watchdog = setTimeout(() => {
proc.kill("SIGKILL");
- reject(new Error("Export stalled — no ffmpeg progress for 120s."));
+ reject(new UserError("export_stalled", "Export stalled — no ffmpeg progress for 120s."));
}, STALL_MS);
watchdog.unref();
};
@@ -1005,22 +1017,27 @@ export function runFfmpeg(
clearTimeout(watchdog);
reject(
err.message.includes("ENOENT")
- ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")
+ ? new UserError("ffmpeg_not_found", "ffmpeg was not found. Install it with: brew install ffmpeg")
: err
);
});
proc.on("close", (code) => {
clearTimeout(watchdog);
if (code === 0) resolve();
- else if (job.error) reject(new Error(job.error));
- else reject(new Error(`ffmpeg exited with code ${code}.\n${job.log.slice(-8).join("")}`));
+ else if (job.error) reject(errorFromBody(job, job.error));
+ else {
+ const log = job.log.slice(-8).join("");
+ reject(new UserError("export_ffmpeg_exited", `ffmpeg exited with code ${code}.\n${log}`, { code: String(code), log }));
+ }
});
});
}
/** End a render whose job was canceled or timed out between passes. */
function stopIfCanceled(job: RenderHandle) {
- if (job.error) throw new Error(job.error);
+ if (job.error) {
+ throw errorFromBody(job, job.error);
+ }
}
/** The pipeline's edges into the world: staged-media checks, list-file
@@ -1073,7 +1090,9 @@ export async function runExport(
mediaPathFor: (file: string) => string,
io: ExportPipelineIO = realIO
) {
- if (given.clips.length === 0) throw new Error("Nothing to export.");
+ if (given.clips.length === 0) {
+ throw new UserError("export_empty", "Nothing to export.");
+ }
const codec = given.codec ?? "h264";
// Stems are cut from the graph's own sound, so a spec that asks for them
// renders.
@@ -1084,7 +1103,9 @@ export async function runExport(
const clips = given.clips.filter((clip) => clip.file === segment.file).sort((a, b) => a.in - b.in);
let covered = segment.from;
for (const clip of clips) if (clip.in <= covered && clip.out > covered) covered = clip.out;
- if (covered < segment.to) throw new Error("Source export does not match the timeline media.");
+ if (covered < segment.to) {
+ throw new UserError("export_source_mismatch", "Source export does not match the timeline media.");
+ }
}
}
if (await io.exportSourceFiles(job, mediaPathFor, given.sourceSegments, codec, given.audioBitrate)) return;
@@ -1179,7 +1200,9 @@ async function renderPass(
const output: OutputSpace = spec.colorSpace ?? "sdr";
const hdr = output !== "sdr";
const compositeSpace = compositeSpaceFor(output);
- if (hdr && codec === "h264") throw new Error("H.264 is 8-bit. Export HDR as HEVC or ProRes.");
+ if (hdr && codec === "h264") {
+ throw h264Hdr();
+ }
// The chroma the composite is built at. A full-chroma delivery composites
// at 4:4:4, so the titles, captions, stickers and masks the graph draws in
@@ -1744,7 +1767,8 @@ async function renderPass(
const text = Buffer.from(await io.readFile(path.join(job.tmpDir, path.basename(file)))).toString("utf8");
parsed = parseLutFile(file, text);
} catch (e) {
- throw new Error(`The LUT ${file} could not be read: ${e instanceof Error ? e.message : String(e)}`);
+ const reason = e instanceof Error ? e.message : String(e);
+ throw new UserError("lut_file_unreadable", `The LUT ${file} could not be read: ${reason}`, { file, reason });
}
userLuts.set(file, parsed);
return parsed;
diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.ts
index ef09654c..686517df 100644
--- a/site/src/cut/server/frames.ts
+++ b/site/src/cut/server/frames.ts
@@ -6,6 +6,7 @@ import { h264Encoder, vtQuality } from "./exportPipeline";
import { mediaPath } from "./projects";
import { assertGraphSafe, fexpr } from "./filterGraph";
import { num, round } from "./util";
+import { UserError } from "../lib/userError";
function run(cmd: string, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
@@ -21,7 +22,7 @@ function run(cmd: string, args: string[]): Promise<void> {
clearTimeout(timer);
reject(
e.message.includes("ENOENT")
- ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")
+ ? new UserError("ffmpeg_not_found", "ffmpeg was not found. Install it with: brew install ffmpeg")
: e
);
});
@@ -200,7 +201,7 @@ function runCapture(args: string[], timeoutMs: number): Promise<CaptureRun> {
clearTimeout(timer);
reject(
e.message.includes("ENOENT")
- ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")
+ ? new UserError("ffmpeg_not_found", "ffmpeg was not found. Install it with: brew install ffmpeg")
: e
);
});
@@ -241,7 +242,7 @@ export async function detectSilence(
);
if (!r.ok) {
if (/does not contain any stream|matches no streams|Cannot find a matching stream/i.test(r.stderr))
- throw new Error("This file has no audio track.");
+ throw new UserError("media_no_audio_track", "This file has no audio track.");
throw new Error(
r.timedOut ? "Silence detection timed out — try a shorter range." : errTail(r.stderr)
);
@@ -299,7 +300,7 @@ export function extractAudio(
p.on("error", (e) =>
reject(
e.message.includes("ENOENT")
- ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")
+ ? new UserError("ffmpeg_not_found", "ffmpeg was not found. Install it with: brew install ffmpeg")
: e,
),
);
@@ -307,7 +308,7 @@ export function extractAudio(
clearTimeout(timer);
if (code === 0 && chunks.length > 0) return resolve(Buffer.concat(chunks));
if (/does not contain any stream|matches no streams|Cannot find a matching stream/i.test(err))
- return reject(new Error("This file has no audio track."));
+ return reject(new UserError("media_no_audio_track", "This file has no audio track."));
reject(new Error(errTail(err) || "Could not read the audio."));
});
});
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index db3355bc..08374ecb 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -42,7 +42,9 @@ import { STEP_BUDGET, stopText, turnClose, type TurnEnd } from "../../lib/turnBu
import { pendingAsk } from "../../lib/chatResume";
import { codexCommand } from "../tool-path";
import { codexAccountModels, createCodexCatalog } from "../ai/codexModels";
-import { errorMessage } from "../util";
+import { errorMessage, errorReply } from "../util";
+import { UserError } from "../../lib/userError";
+import { DEFAULT_LOCALE, isLocale, type Locale } from "../../../i18n/locales";
/** The one place a Claude chat's WebFetch may go: Pexels' pages, where stock
* footage is searched by its own search URLs. Every other host is refused. */
@@ -59,6 +61,16 @@ interface ChatBody {
route?: EngineRoute;
/** Asks the editor carried out on its own since the provider's last turn. */
handled?: HandledAsk[];
+ /** The page's interface language; the handler settles it to a supported one. */
+ locale: Locale;
+}
+
+/** A failure the person reads: its code and values first, as a transient
+ * part the panel words in the page's language, then the English error that
+ * ends the stream. */
+function emitFailure(emit: UIChunkWriter["write"], failure: UserError) {
+ emit({ type: "data-failure", data: { message: failure.message, code: failure.code, params: failure.params }, transient: true });
+ emit({ type: "error", errorText: failure.message });
}
// The steer a Codex turn resumes on once request_tools widened its catalog.
@@ -155,7 +167,7 @@ async function runClaude(
...(process.env.DONKEY_CUT_CLAUDE
? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }
: {}),
- systemPrompt: systemPrompt(),
+ systemPrompt: systemPrompt(body.locale),
// The editor MCP server is the whole surface, but for one built-in:
// WebFetch, held to Pexels, where a replication's stock footage is
// searched. Pexels answers a server's own fetch with a challenge, and
@@ -194,7 +206,7 @@ async function runClaude(
const m = msg as unknown as Record<string, unknown> & { type: string };
const failure = claudeFailure(m);
if (failure) {
- emit({ type: "error", errorText: failure });
+ emitFailure(emit, failure);
end = "failed";
break;
}
@@ -205,7 +217,7 @@ async function runClaude(
// instead of letting that reach the user.
const tools = Array.isArray(m.tools) ? (m.tools as unknown[]) : [];
if (!tools.some((t) => typeof t === "string" && t.startsWith("mcp__cut"))) {
- emit({ type: "error", errorText: "The editor tools didn't load. Reload the tab and try again." });
+ emitFailure(emit, new UserError("editor_tools_unbound", "The editor tools didn't load. Reload the tab and try again."));
await q.interrupt().catch(() => {});
end = "blocked";
break;
@@ -300,7 +312,7 @@ async function runCodex(
let session = body.providerSession;
let ask = prompt;
for (;;) {
- const run = await codexRun(emit, ask, body.model, session, base, sessionKey, signal);
+ const run = await codexRun(emit, ask, body.model, body.locale, session, base, sessionKey, signal);
session = run.thread ?? session;
if (signal.aborted || !session) return;
const folds = inbox.take();
@@ -328,6 +340,7 @@ async function codexRun(
emit: UIChunkWriter["write"],
prompt: string,
model: string,
+ locale: Locale,
session: string | undefined,
base: string,
sessionKey: string,
@@ -360,7 +373,7 @@ async function codexRun(
// 100s, and a listen's words can queue behind a caption run.
"-c",
`mcp_servers.cut.tool_timeout_sec=${CODEX_TOOL_TIMEOUT_S}`,
- session ? prompt : `${systemPrompt()}\n\n${prompt}`
+ session ? prompt : `${systemPrompt(locale)}\n\n${prompt}`
);
await new Promise<void>((resolve, reject) => {
@@ -570,7 +583,7 @@ export const aiApi = {
return Response.json({ texts });
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Could not write captions.") },
+ errorReply(e, new UserError("captions_write_failed", "Could not write captions.")),
{ status: 500 }
);
}
@@ -592,7 +605,7 @@ export const aiApi = {
return Response.json({ cues });
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Could not caption the visuals.") },
+ errorReply(e, new UserError("visual_captions_failed", "Could not caption the visuals.")),
{ status: 500 }
);
}
@@ -612,6 +625,8 @@ export const aiApi = {
if (!identity.success) return Response.json({ error: "A project and chat are required." }, { status: 400 });
const projectId = identity.data.context.project.id;
const { route, handled = [] } = identity.data;
+ // Replies follow the page's language; a page that sent none reads English.
+ body.locale = isLocale(body.locale) ? body.locale : DEFAULT_LOCALE;
const base = new URL(req.url).origin;
const sessionKey = crypto.randomUUID();
const { text: userText, attachments } = pendingAsk(body.messages);
diff --git a/site/src/cut/server/http/convert.ts b/site/src/cut/server/http/convert.ts
index f92dfb92..47a52792 100644
--- a/site/src/cut/server/http/convert.ts
+++ b/site/src/cut/server/http/convert.ts
@@ -3,7 +3,8 @@ import os from "node:os";
import path from "node:path";
import { convertModeIn } from "../../lib/convertMode";
import { convertToMp4, mp4NameFor } from "../convert";
-import { errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
/**
* Convert media the caller supplies, for a project this engine does not store.
@@ -40,7 +41,7 @@ export const convertApi = {
});
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Could not convert that file.") },
+ errorReply(e, new UserError("convert_failed", "Could not convert that file.")),
{ status: 500 }
);
} finally {
diff --git a/site/src/cut/server/http/export.ts b/site/src/cut/server/http/export.ts
index 12c36599..5b965ed9 100644
--- a/site/src/cut/server/http/export.ts
+++ b/site/src/cut/server/http/export.ts
@@ -11,7 +11,11 @@ import {
type ExportSpec,
} from "../jobs";
import { serveFileRange } from "../serveFile";
-import { errorMessage } from "../util";
+import { UserError, errorBody } from "../../lib/userError";
+import { errorReply } from "../util";
+
+const startFailed = () => new UserError("export_start_failed", "Export failed to start.");
+const notRunning = () => new UserError("export_not_running", "This export is no longer running.");
/** Export rendering: start a job, poll it, cancel it, download the result. */
export const exportApi = {
@@ -26,12 +30,12 @@ export const exportApi = {
const form = await req.formData();
const job = await createJob(form);
if (job.status === "error") {
- return Response.json({ error: job.error }, { status: 400 });
+ return Response.json(errorBody(job, startFailed()), { status: 400 });
}
return Response.json({ id: job.id });
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Export failed to start.") },
+ errorReply(e, startFailed()),
{ status: 500 }
);
}
@@ -49,11 +53,13 @@ export const exportApi = {
};
if (!body.projectId) return Response.json({ error: "Missing project." }, { status: 400 });
const job = await createClientJob(body.projectId, body.container, body.name?.trim() || undefined, body.stems === true ? "fileAndStems" : "file");
- if (job.status === "error") return Response.json({ error: job.error }, { status: 400 });
+ if (job.status === "error") {
+ return Response.json(errorBody(job, startFailed()), { status: 400 });
+ }
return Response.json({ id: job.id, outName: job.outName });
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Export failed to start.") },
+ errorReply(e, startFailed()),
{ status: 500 }
);
}
@@ -68,8 +74,12 @@ export const exportApi = {
/** The finished file, streamed straight into the project's exports folder. */
async clientComplete(req: Request, { jobId }: { jobId: string }) {
const job = await completeClientJob(jobId, req.body);
- if (!job) return Response.json({ error: "This export is no longer running." }, { status: 409 });
- if (job.status === "error") return Response.json({ error: job.error }, { status: 500 });
+ if (!job) {
+ return Response.json(errorBody(null, notRunning()), { status: 409 });
+ }
+ if (job.status === "error") {
+ return Response.json(errorBody(job, job.error ?? ""), { status: 500 });
+ }
return Response.json({ id: job.id, outName: job.outName });
},
@@ -77,10 +87,15 @@ export const exportApi = {
async clientStems(req: Request, { jobId }: { jobId: string }) {
try {
const job = await completeClientStems(jobId, req.body);
- if (!job) return Response.json({ error: "This export is no longer running." }, { status: 409 });
+ if (!job) {
+ return Response.json(errorBody(null, notRunning()), { status: 409 });
+ }
return Response.json({ ok: true });
} catch (e) {
- return Response.json({ error: errorMessage(e, "Could not save the stems.") }, { status: 500 });
+ return Response.json(
+ errorReply(e, new UserError("export_stems_save_failed", "Could not save the stems.")),
+ { status: 500 }
+ );
}
},
@@ -91,11 +106,15 @@ export const exportApi = {
async status(_req: Request, { jobId }: { jobId: string }) {
const job = getJob(jobId);
- if (!job) return Response.json({ error: "Unknown export." }, { status: 404 });
+ if (!job) {
+ return Response.json(errorBody(null, new UserError("export_unknown", "Unknown export.")), { status: 404 });
+ }
return Response.json({
status: job.status,
progress: job.progress,
error: job.error,
+ errorCode: job.errorCode,
+ errorParams: job.errorParams,
outName: job.outName,
});
},
diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.ts
index 503d865b..4ec73a2e 100644
--- a/site/src/cut/server/http/library.ts
+++ b/site/src/cut/server/http/library.ts
@@ -26,12 +26,13 @@ import {
} from "../library";
import { serveFileRange, wantsDownload } from "../serveFile";
import { importFromUrl } from "../urlImport";
-import { errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
-const err = (message: string, status: number) =>
- Response.json({ error: message }, { status });
-const caught = (e: unknown, fallback: string) =>
- err(errorMessage(e, fallback), 500);
+const err = (failure: string | UserError, status: number) =>
+ Response.json(errorReply(failure, ""), { status });
+const caught = (e: unknown, fallback: string | UserError) =>
+ Response.json(errorReply(e, fallback), { status: 500 });
/** Link imports by the key the page sent with them. A page that reloads
* mid-import asks again under the same key and waits on the download already
@@ -78,7 +79,7 @@ export const libraryApi = {
} & TemplateInput;
return Response.json(await saveTemplate(projectId, input));
} catch (e) {
- return caught(e, "Could not save the template.");
+ return caught(e, new UserError("template_save_failed", "Could not save the template."));
}
},
@@ -97,7 +98,7 @@ export const libraryApi = {
.filter((f): f is File => f instanceof File);
return Response.json(await importTemplate(doc, files));
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
},
@@ -107,7 +108,7 @@ export const libraryApi = {
const { projectId } = (await req.json()) as { projectId: string };
return Response.json(await copyTemplateToProject(id, projectId));
} catch (e) {
- return caught(e, "Could not add the template.");
+ return caught(e, new UserError("template_add_failed", "Could not add the template."));
}
},
@@ -119,7 +120,7 @@ export const libraryApi = {
} & Parameters<typeof addMediaToTemplate>[2];
return Response.json(await addMediaToTemplate(id, projectId, input));
} catch (e) {
- return caught(e, "Could not add to the template.");
+ return caught(e, new UserError("template_append_failed", "Could not add to the template."));
}
},
@@ -128,7 +129,7 @@ export const libraryApi = {
const { name } = (await req.json()) as { name?: string };
return Response.json(await renameTemplate(id, name ?? ""));
} catch (e) {
- return caught(e, "Could not rename the template.");
+ return caught(e, new UserError("template_rename_failed", "Could not rename the template."));
}
},
@@ -141,7 +142,7 @@ export const libraryApi = {
}
return Response.json(await makeLibraryProxy(id, { maxHeight: body.maxHeight!, crf: body.crf! }));
} catch (e) {
- return caught(e, "Could not make the playable copy.");
+ return caught(e, new UserError("playable_copy_make_failed", "Could not make the playable copy."));
}
},
@@ -150,7 +151,7 @@ export const libraryApi = {
const { name } = (await req.json()) as { name?: string };
return Response.json(await renameAsset(id, name ?? ""));
} catch (e) {
- return caught(e, "Could not rename the file.");
+ return caught(e, new UserError("file_rename_failed", "Could not rename the file."));
}
},
@@ -159,7 +160,7 @@ export const libraryApi = {
await deleteTemplate(id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the template.");
+ return caught(e, new UserError("template_delete_failed", "Could not delete the template."));
}
},
@@ -170,7 +171,7 @@ export const libraryApi = {
if (!url) return err("No URL provided.", 400);
return Response.json(await importOnce(key, () => importFromUrl(url, { audio: audio === true })));
} catch (e) {
- return caught(e, "Could not import that URL.");
+ return caught(e, new UserError("url_import_failed", "Could not import that URL."));
}
},
@@ -179,7 +180,7 @@ export const libraryApi = {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
return Response.json(await createFolder(name ?? "", parentId ?? null));
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
},
@@ -189,7 +190,7 @@ export const libraryApi = {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
return Response.json(await updateFolder(id, { name, parentId }));
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
},
@@ -198,7 +199,7 @@ export const libraryApi = {
await deleteFolder(id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
},
@@ -212,7 +213,7 @@ export const libraryApi = {
await moveItem(id, folderId ?? null);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not move item.");
+ return caught(e, new UserError("library_item_move_failed", "Could not move item."));
}
},
@@ -259,7 +260,7 @@ export const libraryApi = {
),
);
} catch (e) {
- return caught(e, "Upload failed.");
+ return caught(e, new UserError("upload_failed", "Upload failed."));
}
},
@@ -268,7 +269,7 @@ export const libraryApi = {
await removeAsset(id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete.");
+ return caught(e, new UserError("library_delete_failed", "Could not delete."));
}
},
@@ -282,7 +283,7 @@ export const libraryApi = {
const fileName = await copyLibraryAssetToProject(assetId, projectId);
return Response.json({ fileName });
} catch (e) {
- return caught(e, "Could not add from library.");
+ return caught(e, new UserError("library_add_failed", "Could not add from library."));
}
},
@@ -298,7 +299,7 @@ export const libraryApi = {
await addFromProject(projectId, fileName, name ?? fileName),
);
} catch (e) {
- return caught(e, "Could not save to library.");
+ return caught(e, new UserError("library_save_failed", "Could not save to library."));
}
},
diff --git a/site/src/cut/server/http/mic.ts b/site/src/cut/server/http/mic.ts
index 8d8563ea..fbc0ecc7 100644
--- a/site/src/cut/server/http/mic.ts
+++ b/site/src/cut/server/http/mic.ts
@@ -1,7 +1,10 @@
import { cancelMic, feedMic, getMicJob, startMicJob, stopMic } from "../mic";
-import { errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
-const err = (message: string, status: number) => Response.json({ error: message }, { status });
+const err = (failure: string | UserError, status: number) => Response.json(errorReply(failure, ""), { status });
+
+const dictationUnknown = () => new UserError("dictation_unknown", "Unknown dictation.");
/** Live mic dictation: start a job, stream PCM to it, poll the transcript. */
export const micApi = {
@@ -11,28 +14,28 @@ export const micApi = {
const job = await startMicJob(typeof body.locale === "string" ? body.locale : "en-US");
return Response.json({ id: job.id });
} catch (e) {
- return err(errorMessage(e, "Could not start dictation."), 500);
+ return Response.json(errorReply(e, new UserError("dictation_start_failed", "Could not start dictation.")), { status: 500 });
}
},
async feed(req: Request, { id }: { id: string }) {
const pcm = Buffer.from(await req.arrayBuffer());
- return feedMic(id, pcm) ? new Response(null, { status: 204 }) : err("Dictation is not running.", 409);
+ return feedMic(id, pcm) ? new Response(null, { status: 204 }) : err(new UserError("dictation_not_running", "Dictation is not running."), 409);
},
poll(_req: Request, { id }: { id: string }) {
const job = getMicJob(id);
- if (!job) return err("Unknown dictation.", 404);
- return Response.json({ status: job.status, text: job.text, error: job.error });
+ if (!job) return err(dictationUnknown(), 404);
+ return Response.json({ status: job.status, text: job.text, error: job.error, errorCode: job.errorCode, errorParams: job.errorParams });
},
async stop(_req: Request, { id }: { id: string }) {
const text = await stopMic(id);
- if (text === null) return err("Unknown dictation.", 404);
+ if (text === null) return err(dictationUnknown(), 404);
return Response.json({ text });
},
cancel(_req: Request, { id }: { id: string }) {
- return cancelMic(id) ? new Response(null, { status: 204 }) : err("Unknown dictation.", 404);
+ return cancelMic(id) ? new Response(null, { status: 204 }) : err(dictationUnknown(), 404);
},
};
diff --git a/site/src/cut/server/http/phoneLink.ts b/site/src/cut/server/http/phoneLink.ts
index cb2ee6b9..80e9e360 100644
--- a/site/src/cut/server/http/phoneLink.ts
+++ b/site/src/cut/server/http/phoneLink.ts
@@ -16,11 +16,12 @@ import {
removePhoneDevice,
} from "../phoneLink";
import { serveFileRange } from "../serveFile";
-import { errorMessage } from "../util";
+import type { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
-const err = (message: string, status: number) => Response.json({ error: message }, { status });
-const caught = (e: unknown, fallback: string) =>
- err(errorMessage(e, fallback), 500);
+const err = (failure: string | UserError, status: number) => Response.json(errorReply(failure, ""), { status });
+const caught = (e: unknown, fallback: string | UserError) =>
+ Response.json(errorReply(e, fallback), { status: 500 });
/** The header a paired phone's traffic carries. The app's listener copies it
* across from the peer connection; nothing else on this Mac sets it. */
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index b51619ff..171dd425 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -28,15 +28,19 @@ import {
} from "../projects";
import { convertToMp4, mp4NameFor } from "../convert";
import { convertModeIn } from "@/cut/lib/convertMode";
+import { requestedLocale } from "@/cut/lib/defaultNames";
import { makeCompatProxy, makeProxy, proxyNameFor } from "../proxy";
import { serveFileRange, wantsDownload } from "../serveFile";
import { importUrlToProject } from "../urlImport";
import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";
-import { exists, uniqueName, errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { exists, uniqueName, errorReply } from "../util";
-const err = (message: string, status: number) => Response.json({ error: message }, { status });
-const caught = (e: unknown, fallback: string, status = 500) =>
- err(errorMessage(e, fallback), status);
+const err = (failure: string | UserError, status: number) => Response.json(errorReply(failure, ""), { status });
+const caught = (e: unknown, fallback: string | UserError, status = 500) =>
+ Response.json(errorReply(e, fallback), { status });
+// The reply for an id with no project behind it, coded so the page words it.
+const PROJECT_NOT_FOUND = new UserError("project_not_found", "Project not found.");
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
/** Project CRUD, media, exports, transcription, freeze-frames. */
@@ -54,7 +58,7 @@ export const projectsApi = {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
return Response.json(await createProjectFolder(name ?? "", parentId ?? null));
} catch (e) {
- return caught(e, "Could not create folder.");
+ return caught(e, new UserError("folder_create_failed", "Could not create folder."));
}
},
@@ -64,7 +68,7 @@ export const projectsApi = {
const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
return Response.json(await updateProjectFolder(id, { name, parentId }));
} catch (e) {
- return caught(e, "Could not update folder.");
+ return caught(e, new UserError("folder_update_failed", "Could not update folder."));
}
},
@@ -73,7 +77,7 @@ export const projectsApi = {
await deleteProjectFolder(id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete folder.");
+ return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
}
},
@@ -84,32 +88,33 @@ export const projectsApi = {
await moveProjectToFolder(id, folderId ?? null);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not move project.");
+ return caught(e, new UserError("project_move_failed", "Could not move project."));
}
},
async create(req: Request) {
try {
- const { name, folderId, aspect } = (await req.json()) as {
+ const { name, folderId, aspect, locale } = (await req.json()) as {
name?: string;
folderId?: string | null;
aspect?: string;
+ locale?: string;
};
return Response.json(
- await createProject(name ?? "Untitled", folderId ?? null, normalizeAspect(aspect))
+ await createProject(name ?? "", folderId ?? null, normalizeAspect(aspect), requestedLocale(locale))
);
} catch (e) {
- return caught(e, "Could not create project.");
+ return caught(e, new UserError("project_create_failed", "Could not create project."));
}
},
async get(req: Request, { id }: { id: string }) {
const revision = await projectFileRevision(id);
- if (!revision) return err("Project not found.", 404);
+ if (!revision) return err(PROJECT_NOT_FOUND, 404);
const headers = { "x-cut-doc-version": revision };
if (req.method === "HEAD") return new Response(null, { headers });
const doc = await readProject(id).catch(() => null);
- if (!doc) return err("Project not found.", 404);
+ if (!doc) return err(PROJECT_NOT_FOUND, 404);
void sweepOrphanMedia(id, doc).catch(() => {});
return Response.json(doc, { headers });
},
@@ -117,7 +122,7 @@ export const projectsApi = {
async put(req: Request, { id }: { id: string }) {
try {
const existing = await readProject(id);
- if (!existing) return err("Project not found.", 404);
+ if (!existing) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as Partial<ProjectDoc>;
const doc: ProjectDoc = {
...existing,
@@ -171,7 +176,7 @@ export const projectsApi = {
const revision = await writeProject(id, doc);
return Response.json({ ok: true, updatedAt: doc.updatedAt, revision });
} catch (e) {
- return caught(e, "Could not save project.");
+ return caught(e, new UserError("project_save_failed", "Could not save project."));
}
},
@@ -180,16 +185,18 @@ export const projectsApi = {
await deleteProject(id);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete project.");
+ return caught(e, new UserError("project_delete_failed", "Could not delete project."));
}
},
/** Duplicate a project (doc + media) into a fresh one. */
- async duplicate(_req: Request, { id }: { id: string }) {
+ async duplicate(req: Request, { id }: { id: string }) {
try {
- return Response.json(await duplicateProject(id));
+ // The copy is named in its creator's language; an older page sends no body.
+ const { locale } = ((await req.json().catch(() => null)) ?? {}) as { locale?: string };
+ return Response.json(await duplicateProject(id, requestedLocale(locale)));
} catch (e) {
- return caught(e, "Could not duplicate project.");
+ return caught(e, new UserError("project_duplicate_error", "Could not duplicate project."));
}
},
@@ -211,20 +218,20 @@ export const projectsApi = {
if (!url) return err("No URL provided.", 400);
return Response.json(await importUrlToProject(id, url, { audio: audio === true }));
} catch (e) {
- return caught(e, "Could not import that URL.");
+ return caught(e, new UserError("url_import_failed", "Could not import that URL."));
}
},
async uploadMedia(req: Request, { id }: { id: string }) {
try {
- if (!(await readProject(id))) return err("Project not found.", 404);
+ if (!(await readProject(id))) return err(PROJECT_NOT_FOUND, 404);
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No file in upload.", 400);
const fileName = await saveMedia(id, file);
return Response.json({ fileName });
} catch (e) {
- return caught(e, "Upload failed.");
+ return caught(e, new UserError("upload_failed", "Upload failed."));
}
},
@@ -234,7 +241,7 @@ export const projectsApi = {
await deleteMedia(id, decodeURIComponent(file));
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the media file.");
+ return caught(e, new UserError("media_delete_failed", "Could not delete the media file."));
}
},
@@ -246,14 +253,14 @@ export const projectsApi = {
} catch {
return err("Bad request.", 400);
}
- if (!(await exists(p))) return err("Media file not found.", 404);
+ if (!(await exists(p))) return err(new UserError("media_file_not_found", "Media file not found."), 404);
try {
await new Promise<void>((resolve, reject) =>
execFile("open", ["-R", p], (e) => (e ? reject(e) : resolve()))
);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not reveal the file.");
+ return caught(e, new UserError("file_reveal_failed", "Could not reveal the file."));
}
},
@@ -301,14 +308,14 @@ export const projectsApi = {
} catch {
return err("Bad request.", 400);
}
- if (!(await exists(p))) return err("Export not found.", 404);
+ if (!(await exists(p))) return err(new UserError("export_not_found", "Export not found."), 404);
try {
await new Promise<void>((resolve, reject) =>
execFile("open", ["-R", p], (e) => (e ? reject(e) : resolve()))
);
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not reveal the file.");
+ return caught(e, new UserError("file_reveal_failed", "Could not reveal the file."));
}
},
@@ -318,7 +325,7 @@ export const projectsApi = {
await deleteExport(id, decodeURIComponent(file));
return Response.json({ ok: true });
} catch (e) {
- return caught(e, "Could not delete the export.");
+ return caught(e, new UserError("export_delete_failed", "Could not delete the export."));
}
},
@@ -344,11 +351,13 @@ export const projectsApi = {
async transcribePoll(req: Request, { id }: { id: string }) {
const jobId = new URL(req.url).searchParams.get("job");
const job = jobId ? getTranscribeJob(jobId) : undefined;
- if (!job || job.projectId !== id) return err("Unknown transcription job.", 404);
+ if (!job || job.projectId !== id) return err(new UserError("transcribe_job_unknown", "Unknown transcription job."), 404);
return Response.json({
status: job.status,
stage: job.stage,
error: job.error,
+ errorCode: job.errorCode,
+ errorParams: job.errorParams,
cues: job.status === "done" ? job.cues : undefined,
});
},
@@ -357,7 +366,7 @@ export const projectsApi = {
* resolution — no video baking. AI generations and stock tiles land here. */
async importImage(req: Request, { id }: { id: string }) {
try {
- if (!(await readProject(id))) return err("Project not found.", 404);
+ if (!(await readProject(id))) return err(PROJECT_NOT_FOUND, 404);
const form = await req.formData();
const file = form.get("file");
if (!(file instanceof File)) return err("No image in upload.", 400);
@@ -378,14 +387,14 @@ export const projectsApi = {
...(origin ? { origin } : {}),
});
} catch (e) {
- return caught(e, "Could not import the image.");
+ return caught(e, new UserError("image_import_failed", "Could not import the image."));
}
},
/** Render a freeze-frame still clip from a media file's frame. */
async freeze(req: Request, { id }: { id: string }) {
try {
- if (!(await readProject(id))) return err("Project not found.", 404);
+ if (!(await readProject(id))) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as {
file?: string;
srcTime?: number;
@@ -437,13 +446,13 @@ export const projectsApi = {
* the asset over to it and dropping the old bytes is the client's call. */
async convert(req: Request, { id }: { id: string }) {
try {
- if (!(await readProject(id))) return err("Project not found.", 404);
+ if (!(await readProject(id))) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as { file?: string; maxHeight?: number; mode?: unknown };
if (!body.file) return err("file is required.", 400);
const mode = convertModeIn(body.mode);
if (!mode) return err("mode is fit or reencode.", 400);
const src = mediaPath(id, body.file);
- if (!(await exists(src))) return err("Media file missing from project.", 404);
+ if (!(await exists(src))) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
const fileName = await uniqueName(mp4NameFor(body.file), (n) => mediaPath(id, n));
const outPath = mediaPath(id, fileName);
const handle = { tmpDir: "", outPath, progress: 0, log: [] as string[] };
@@ -460,7 +469,7 @@ export const projectsApi = {
...outcome,
});
} catch (e) {
- return caught(e, "Could not convert that file.");
+ return caught(e, new UserError("convert_failed", "Could not convert that file."));
}
},
@@ -471,14 +480,14 @@ export const projectsApi = {
* the master's streams (lib/proxyNames.ts). */
async proxy(req: Request, { id }: { id: string }) {
try {
- if (!(await readProject(id))) return err("Project not found.", 404);
+ if (!(await readProject(id))) return err(PROJECT_NOT_FOUND, 404);
const body = (await req.json()) as { file?: string; maxHeight?: number; crf?: number; compat?: unknown };
if (!body.file) return err("file is required.", 400);
if (typeof body.maxHeight !== "number" || typeof body.crf !== "number") return err("maxHeight and crf are required.", 400);
const compat = compatCoverIn(body.compat);
if (body.compat !== undefined && !compat) return err("compat is audio or video.", 400);
const src = mediaPath(id, body.file);
- if (!(await exists(src))) return err("Media file missing from project.", 404);
+ if (!(await exists(src))) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
const fileName = await uniqueName(compat ? compatProxyNameFor(body.file, compat, false) : proxyNameFor(body.file), (n) => mediaPath(id, n));
const outPath = mediaPath(id, fileName);
const handle = { tmpDir: "", outPath, progress: 0, log: [] as string[] };
@@ -486,7 +495,7 @@ export const projectsApi = {
const outcome = compat ? await makeCompatProxy(handle, src, outPath, { ...opts, cover: compat }) : await makeProxy(handle, src, outPath, opts);
return Response.json({ fileName, ...outcome });
} catch (e) {
- return caught(e, "Could not make the preview proxy.");
+ return caught(e, new UserError("proxy_failed", "Could not make the preview proxy."));
}
},
diff --git a/site/src/cut/server/http/proxy.ts b/site/src/cut/server/http/proxy.ts
index 942426be..0a880f5c 100644
--- a/site/src/cut/server/http/proxy.ts
+++ b/site/src/cut/server/http/proxy.ts
@@ -3,7 +3,8 @@ import os from "node:os";
import path from "node:path";
import { compatCoverIn, compatProxyNameFor } from "@/cut/lib/proxyNames";
import { makeCompatProxy, makeProxy, proxyNameFor } from "../proxy";
-import { errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
/**
* Build a preview proxy of a master the caller supplies, for a project this
@@ -50,7 +51,7 @@ export const proxyApi = {
});
} catch (e) {
return Response.json(
- { error: errorMessage(e, "Could not make the preview proxy.") },
+ errorReply(e, new UserError("proxy_failed", "Could not make the preview proxy.")),
{ status: 500 }
);
} finally {
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 1b68f7f5..d95da77d 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -1,5 +1,5 @@
import { matchRouteTable } from "./match";
-import { errorMessage } from "../util";
+import { errorReply } from "../util";
import { aiApi } from "./ai";
import { localSceneLease } from "../ai/sceneLease";
import { convertApi } from "./convert";
@@ -148,7 +148,7 @@ export async function runCutRoute(
try {
return await match.handler(req, match.params);
} catch (error) {
- return Response.json({ error: errorMessage(error, "The request failed.") }, { status: 500 });
+ return Response.json(errorReply(error, "The request failed."), { status: 500 });
}
}
diff --git a/site/src/cut/server/http/stt.ts b/site/src/cut/server/http/stt.ts
index cff4a6ab..b57a510b 100644
--- a/site/src/cut/server/http/stt.ts
+++ b/site/src/cut/server/http/stt.ts
@@ -1,5 +1,8 @@
import { createAudioTranscribeJob, getTranscribeJob } from "../transcribe";
-import { errorMessage } from "../util";
+import { UserError } from "../../lib/userError";
+import { errorReply } from "../util";
+
+const TRANSCRIBE_START_FAILED = new UserError("transcription_start_failed", "Transcription failed to start.");
/** On-device speech for audio the caller supplies, rather than for a project
* this engine stores: a cloud project renders its audible mix in the browser
@@ -19,23 +22,24 @@ export const sttApi = {
locale: typeof locale === "string" && locale ? locale : undefined,
duration: Number.isFinite(duration) ? duration : undefined,
});
- if (job.status === "error") return Response.json({ error: job.error }, { status: 400 });
+ if (job.status === "error") return Response.json(errorReply(job, TRANSCRIBE_START_FAILED), { status: 400 });
return Response.json({ id: job.id });
} catch (e) {
- return Response.json(
- { error: errorMessage(e, "Transcription failed to start.") },
- { status: 500 }
- );
+ return Response.json(errorReply(e, TRANSCRIBE_START_FAILED), { status: 500 });
}
},
status(_req: Request, { jobId }: { jobId: string }) {
const job = getTranscribeJob(jobId);
- if (!job) return Response.json({ error: "Unknown transcription job." }, { status: 404 });
+ if (!job) {
+ return Response.json(errorReply(new UserError("transcribe_job_unknown", "Unknown transcription job."), ""), { status: 404 });
+ }
return Response.json({
status: job.status,
stage: job.stage,
error: job.error,
+ errorCode: job.errorCode,
+ errorParams: job.errorParams,
cues: job.cues,
});
},
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index e85f7ee1..7a0cb3de 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -7,7 +7,8 @@ import { createJobRegistry } from "./jobRegistry";
import { containerExtension, runExport, type ExportSpec } from "./exportPipeline";
import { exportBaseName, stemsArchiveName, type ExportFiles } from "../lib/exportDelivery";
import { exportsDir, mediaPath, projectDir, readProject, setActiveJobGuard } from "./projects";
-import { errorMessage } from "./util";
+import { UserError, errorFromBody, type UserErrorParams } from "../lib/userError";
+import { errorRecord } from "./util";
export type { ExportSpec } from "./exportPipeline";
@@ -23,6 +24,8 @@ export interface Job {
status: "queued" | "running" | "done" | "error";
progress: number; // 0..1
error?: string;
+ errorCode?: string;
+ errorParams?: UserErrorParams;
/** When the job was created (queue order) and when it actually began the
* encode (elapsed clock in the dock). */
createdAt: number;
@@ -43,6 +46,18 @@ export interface Job {
log: string[];
}
+const exportCanceled = () => new UserError("export_canceled", "Export canceled.");
+const exportBusy = () => new UserError("export_busy", "Another export is already running — wait for it to finish.");
+const projectMissing = () => new UserError("project_not_found", "Project not found.");
+
+/** Settle a job as failed with `failure`'s words and code, or `fallback`'s. */
+function failJob(job: Job, failure: unknown, fallback: UserError | string): void {
+ job.status = "error";
+ job.errorCode = undefined;
+ job.errorParams = undefined;
+ Object.assign(job, errorRecord(failure, fallback));
+}
+
const MAX_RUNNING = 2; // concurrent ffmpeg exports; extra exports queue behind them
// Survives dev-server module reloads; caps the terminal backlog. Queued jobs
// are active work, not backlog, so they are exempt from eviction.
@@ -83,8 +98,7 @@ function sweepClientJobs(now = Date.now()): void {
for (const job of jobs.values()) {
if (!job.client || job.status !== "running") continue;
if (now - (job.seenAt ?? job.startedAt ?? job.createdAt) < CLIENT_RENDER_WINDOW_MS) continue;
- job.status = "error";
- job.error = "The tab rendering this export went away.";
+ failJob(job, null, new UserError("export_tab_gone", "The tab rendering this export went away."));
retire(job);
}
}
@@ -142,13 +156,14 @@ function startRun(job: Job, spec: ExportSpec) {
.then(async () => {
// A cancel that landed after the last pass settled the row already;
// its file goes the way a failed render's does.
- if (job.status !== "running") throw new Error(job.error ?? "Export canceled.");
+ if (job.status !== "running") {
+ throw errorFromBody(job, exportCanceled());
+ }
if (job.target === "preview") await publishPreview(job);
job.status = "done";
})
.catch((err: unknown) => {
- job.status = "error";
- job.error = errorMessage(err, String(err));
+ failJob(job, err, String(err));
void rm(job.outPath, { force: true }); // no half-written files in exports/
if (job.stemsPath) void rm(job.stemsPath, { force: true });
})
@@ -174,6 +189,8 @@ function jobView(j: Job) {
progress: j.progress,
outName: j.outName || undefined,
error: j.error,
+ errorCode: j.errorCode,
+ errorParams: j.errorParams,
createdAt: j.createdAt,
startedAt: j.startedAt,
};
@@ -194,19 +211,16 @@ export function cancelJob(id: string) {
if (!job) return;
if (job.status === "running" && job.proc) {
job.proc.kill("SIGKILL");
- job.status = "error";
- job.error = "Export canceled.";
+ failJob(job, null, exportCanceled());
retire(job);
} else if (job.status === "running" && job.client) {
// The tab drawing it learns of the cancel when it comes to hand the file
// in and is refused; the row settles now so every dock clears.
- job.status = "error";
- job.error = "Export canceled.";
+ failJob(job, null, exportCanceled());
retire(job);
} else if (job.status === "queued") {
// Never started: drop it from the queue and settle it so the dock clears.
- job.status = "error";
- job.error = "Export canceled.";
+ failJob(job, null, exportCanceled());
const i = pending.findIndex((p) => p.job.id === id);
if (i >= 0) pending.splice(i, 1);
retire(job);
@@ -274,7 +288,7 @@ export async function createJob(form: FormData): Promise<Job> {
tmpDir: "",
outPath: "",
outName: "",
- error: "Another export is already running — wait for it to finish.",
+ ...errorRecord(null, exportBusy()),
log: [],
};
jobs.set(id, job);
@@ -299,7 +313,9 @@ export async function createJob(form: FormData): Promise<Job> {
try {
const doc = await readProject(spec.projectId);
- if (!doc) throw new Error("Project not found.");
+ if (!doc) {
+ throw projectMissing();
+ }
job.projectName = doc.name;
if (preview) job.outName = "preview.mp4";
else await claimExportName(job, spec.name ?? doc.name, containerExtension(spec), spec.stemPlan?.length ? "fileAndStems" : "file");
@@ -327,8 +343,7 @@ export async function createJob(form: FormData): Promise<Job> {
// dropped preview just refreshes later, so bow out instead of racing.
if (runningCount() < MAX_RUNNING) startRun(job, spec);
else {
- job.status = "error";
- job.error = "Another export is already running — wait for it to finish.";
+ failJob(job, null, exportBusy());
void rm(job.tmpDir, { recursive: true, force: true });
retire(job);
}
@@ -337,8 +352,7 @@ export async function createJob(form: FormData): Promise<Job> {
pump();
}
} catch (err) {
- job.status = "error";
- job.error = errorMessage(err, String(err));
+ failJob(job, err, String(err));
if (job.tmpDir) void rm(job.tmpDir, { recursive: true, force: true });
retire(job);
}
@@ -378,14 +392,15 @@ export async function createClientJob(
jobs.set(job.id, job);
try {
const doc = await readProject(projectId);
- if (!doc) throw new Error("Project not found.");
+ if (!doc) {
+ throw projectMissing();
+ }
job.projectName = doc.name;
await claimExportName(job, name ?? doc.name, containerExtension({ container }), files);
job.outPath = path.join(exportsDir(projectId), job.outName);
await mkdir(path.dirname(job.outPath), { recursive: true });
} catch (err) {
- job.status = "error";
- job.error = errorMessage(err, String(err));
+ failJob(job, err, String(err));
retire(job);
}
return job;
@@ -436,15 +451,16 @@ export async function completeClientJob(
job.seenAt = Date.now();
const partial = `${job.outPath}.part`;
try {
- if (!body) throw new Error("The export arrived without a file.");
+ if (!body) {
+ throw new UserError("export_file_missing", "The export arrived without a file.");
+ }
await writeBody(body, partial);
await rename(partial, job.outPath);
job.status = "done";
job.progress = 1;
} catch (err) {
await rm(partial, { force: true });
- job.status = "error";
- job.error = errorMessage(err, String(err));
+ failJob(job, err, String(err));
} finally {
retire(job);
}
@@ -465,7 +481,9 @@ export async function completeClientStems(
job.seenAt = Date.now();
const partial = `${job.stemsPath}.part`;
try {
- if (!body) throw new Error("The stems arrived without a file.");
+ if (!body) {
+ throw new UserError("export_stems_missing", "The stems arrived without a file.");
+ }
await writeBody(body, partial);
await rename(partial, job.stemsPath);
} catch (err) {
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index 83d5fd8b..48c6664b 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -13,6 +13,7 @@ import { mediaPath as projectMediaPath, readProject } from "./projects";
import { makeProxy, proxyNameFor } from "./proxy";
import { templateExtras } from "./templateExtras";
import { exists, uniqueName, writeJsonAtomic } from "./util";
+import { UserError } from "@/cut/lib/userError";
/** The Mac's library: reusable media that lives outside any project, shared by
* every account that signs in on this Mac. */
@@ -229,7 +230,7 @@ function ffprobe(args: string[]): Promise<string> {
p.on("close", (code) => {
clearTimeout(timer);
if (code === 0) resolve(out.trim());
- else reject(new Error("Could not read this media file."));
+ else reject(new UserError("media_file_unreadable", "Could not read this media file."));
});
});
}
@@ -283,7 +284,7 @@ export async function register(
originalFile?: string,
): Promise<LibraryAsset> {
const type = libraryTypeOf(fileName);
- if (!type) throw new Error("Unsupported file type.");
+ if (!type) throw new UserError("file_type_unsupported", "Unsupported file type.");
// A linked item has no streams to measure; the page that checked it sends
// what its row carries instead.
const meta: { duration: number; width?: number; height?: number } =
@@ -318,7 +319,7 @@ export async function addUpload(
linked?: LinkedMeta,
prepare = false,
): Promise<LibraryAsset> {
- if (!libraryTypeOf(file.name)) throw new Error("Unsupported file type.");
+ if (!libraryTypeOf(file.name)) throw new UserError("file_type_unsupported", "Unsupported file type.");
await mkdir(libMedia(), { recursive: true });
const fileName = await freeName(file.name);
await writeFile(
@@ -361,7 +362,7 @@ export async function addFromProject(
name: string,
): Promise<LibraryAsset> {
const src = projectMediaPath(projectId, fileName);
- if (!(await exists(src))) throw new Error("Media file not found in project.");
+ if (!(await exists(src))) throw new UserError("project_media_not_found", "Media file not found in project.");
await mkdir(libMedia(), { recursive: true });
const dest = await freeName(fileName);
await copyFile(src, libMediaPath(dest));
@@ -376,7 +377,7 @@ export async function addDownloaded(
source?: LibrarySource,
posterPath?: string,
): Promise<LibraryAsset> {
- if (!libraryTypeOf(srcPath)) throw new Error("Unsupported file type.");
+ if (!libraryTypeOf(srcPath)) throw new UserError("file_type_unsupported", "Unsupported file type.");
await mkdir(libMedia(), { recursive: true });
const dest = await freeName(path.basename(srcPath));
await copyFile(srcPath, libMediaPath(dest));
@@ -398,8 +399,8 @@ export async function copyLibraryAssetToProject(
): Promise<string> {
const idx = await readIndex();
const asset = idx.assets.find((a) => a.id === assetId);
- if (!asset) throw new Error("Library asset not found.");
- if (!(await readProject(projectId))) throw new Error("Project not found.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
+ if (!(await readProject(projectId))) throw new UserError("project_not_found", "Project not found.");
const base = asset.fileName;
const dest = await uniqueName(base, (n) => projectMediaPath(projectId, n));
@@ -445,7 +446,7 @@ async function removeFiles(files: string[]) {
export async function removeAsset(id: string) {
const files = await mutateIndex((idx) => {
- if (!idx.assets.some((a) => a.id === id)) throw new Error("Library asset not found.");
+ if (!idx.assets.some((a) => a.id === id)) throw new UserError("library_asset_not_found", "Library asset not found.");
return takeAssets(idx, new Set([id]));
});
await removeFiles(files);
@@ -462,8 +463,8 @@ export function makeLibraryProxy(id: string, opts: { maxHeight: number; crf: num
if (running) return running;
const build = (async () => {
const asset = (await readIndex()).assets.find((a) => a.id === id);
- if (!asset) throw new Error("Library asset not found.");
- if (asset.type !== "video") throw new Error("Only a video takes a playable copy.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
+ if (asset.type !== "video") throw new UserError("playable_copy_video_only", "Only a video takes a playable copy.");
if (asset.proxyFile && (await exists(libMediaPath(asset.proxyFile)))) return asset;
const fileName = await freeName(proxyNameFor(asset.fileName));
const out = libMediaPath(fileName);
@@ -473,7 +474,7 @@ export function makeLibraryProxy(id: string, opts: { maxHeight: number; crf: num
// The asset may have been deleted while the copy was built.
return await mutateIndex((idx) => {
const live = idx.assets.find((a) => a.id === id);
- if (!live) throw new Error("Library asset not found.");
+ if (!live) throw new UserError("library_asset_not_found", "Library asset not found.");
live.proxyFile = fileName;
return live;
});
@@ -503,7 +504,7 @@ export async function createFolder(
parentId: string | null = null,
): Promise<LibraryFolder> {
const trimmed = name.trim();
- if (!trimmed) throw new Error("Folder name required.");
+ if (!trimmed) throw new UserError("folder_name_required", "Folder name required.");
const id = crypto.randomUUID().slice(0, 8);
return mutateIndex((idx) => {
const folder: LibraryFolder = {
@@ -524,10 +525,10 @@ export async function updateFolder(
patch: { name?: string; parentId?: string | null },
): Promise<LibraryFolder> {
const trimmed = patch.name?.trim();
- if (patch.name !== undefined && !trimmed) throw new Error("Folder name required.");
+ if (patch.name !== undefined && !trimmed) throw new UserError("folder_name_required", "Folder name required.");
return mutateIndex((idx) => {
const folder = (idx.folders ?? []).find((f) => f.id === id);
- if (!folder) throw new Error("Folder not found.");
+ if (!folder) throw new UserError("folder_not_found", "Folder not found.");
if (trimmed) folder.name = trimmed.slice(0, 80);
if (patch.parentId !== undefined) {
folder.parentId = resolveParent(idx.folders ?? [], id, patch.parentId);
@@ -565,9 +566,9 @@ export async function moveItem(id: string, folderId: string | null) {
const item =
idx.assets.find((a) => a.id === id) ??
(idx.templates ?? []).find((t) => t.id === id);
- if (!item) throw new Error("Library item not found.");
+ if (!item) throw new UserError("library_item_not_found", "Library item not found.");
if (folderId && !(idx.folders ?? []).some((f) => f.id === folderId)) {
- throw new Error("Folder not found.");
+ throw new UserError("folder_not_found", "Folder not found.");
}
item.folderId = folderId;
});
@@ -624,12 +625,12 @@ export async function importTemplate(
input: TemplateInput & { folderId?: string | null },
files: File[],
): Promise<LibraryTemplate> {
- if (templateEmpty(input)) throw new Error("Nothing to add.");
+ if (templateEmpty(input)) throw new UserError("template_nothing_to_add", "Nothing to add.");
await mkdir(libMedia(), { recursive: true });
const media: TemplateMedia[] = [];
for (const [i, m] of (input.media ?? []).entries()) {
const file = files[i];
- if (!file) throw new Error("Template media missing.");
+ if (!file) throw new UserError("template_media_missing", "Template media missing.");
const dest = await freeName(m.fileName || file.name);
await writeFile(libMediaPath(dest), Buffer.from(await file.arrayBuffer()));
media.push({ ...m, fileName: dest });
@@ -658,14 +659,14 @@ export async function saveTemplate(
projectId: string,
input: TemplateInput,
): Promise<LibraryTemplate> {
- if (!(await readProject(projectId))) throw new Error("Project not found.");
- if (templateEmpty(input)) throw new Error("Nothing to save.");
+ if (!(await readProject(projectId))) throw new UserError("project_not_found", "Project not found.");
+ if (templateEmpty(input)) throw new UserError("template_nothing_to_save", "Nothing to save.");
await mkdir(libMedia(), { recursive: true });
const media: TemplateMedia[] = [];
for (const m of input.media) {
const src = projectMediaPath(projectId, m.fileName);
if (!(await exists(src)))
- throw new Error("Media file not found in project.");
+ throw new UserError("project_media_not_found", "Media file not found in project.");
const dest = await freeName(m.fileName);
await copyFile(src, libMediaPath(dest));
media.push({
@@ -700,10 +701,10 @@ export async function saveTemplate(
/** Materialize a template into a project: copy its media in and hand the client
* the project file names (in template media order) plus the stored edit. */
export async function copyTemplateToProject(templateId: string, projectId: string) {
- if (!(await readProject(projectId))) throw new Error("Project not found.");
+ if (!(await readProject(projectId))) throw new UserError("project_not_found", "Project not found.");
const idx = await readIndex();
const template = (idx.templates ?? []).find((x) => x.id === templateId);
- if (!template) throw new Error("Template not found.");
+ if (!template) throw new UserError("template_not_found", "Template not found.");
const media: TemplateMedia[] = [];
for (const m of template.media) {
const dest = await uniqueName(m.fileName, (n) =>
@@ -730,14 +731,14 @@ export async function addMediaToTemplate(
},
): Promise<LibraryTemplate> {
const src = projectMediaPath(projectId, input.media.fileName);
- if (!(await exists(src))) throw new Error("Media file not found in project.");
+ if (!(await exists(src))) throw new UserError("project_media_not_found", "Media file not found in project.");
await mkdir(libMedia(), { recursive: true });
const dest = await freeName(input.media.fileName);
await copyFile(src, libMediaPath(dest));
try {
return await mutateIndex((idx) => {
const t = (idx.templates ?? []).find((x) => x.id === templateId);
- if (!t) throw new Error("Template not found.");
+ if (!t) throw new UserError("template_not_found", "Template not found.");
const mi = t.media.length;
t.media = [...t.media, { ...input.media, fileName: dest }];
if (input.audio)
@@ -766,7 +767,7 @@ export async function renameTemplate(
const next = itemName(name);
return mutateIndex((idx) => {
const template = (idx.templates ?? []).find((t) => t.id === id);
- if (!template) throw new Error("Template not found.");
+ if (!template) throw new UserError("template_not_found", "Template not found.");
template.name = next;
return template;
});
@@ -776,7 +777,7 @@ export async function renameAsset(id: string, name: string): Promise<LibraryAsse
const next = itemName(name);
return mutateIndex((idx) => {
const asset = idx.assets.find((a) => a.id === id);
- if (!asset) throw new Error("Library asset not found.");
+ if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
asset.name = next;
return asset;
});
diff --git a/site/src/cut/server/mic.ts b/site/src/cut/server/mic.ts
index 7009b0bd..eed1b34b 100644
--- a/site/src/cut/server/mic.ts
+++ b/site/src/cut/server/mic.ts
@@ -2,18 +2,18 @@ import { spawn, type ChildProcess } from "node:child_process";
import { assertLocalRuntime } from "./local-only";
import { createJobRegistry } from "./jobRegistry";
import { ensureStt } from "./transcribe";
+import { errorFields, UserError, type ErrorFields } from "../lib/userError";
// Live mic dictation for the AI chat composer. The browser captures the mic
// (it already holds that permission) and streams 16 kHz mono s16le PCM to the
// engine; this spawns `cut-stt --live`, forwards the PCM to its stdin, and
// exposes the evolving transcript. On-device only — nothing leaves the Mac.
-export interface MicJob {
+export interface MicJob extends ErrorFields {
id: string;
status: "running" | "done" | "error" | "canceled";
/** Latest transcript: the evolving partial while running, the final text once done. */
text: string;
- error?: string;
proc: ChildProcess;
/** Resolves once the process has emitted its final text (or died). */
finished: Promise<void>;
@@ -103,7 +103,7 @@ export async function startMicJob(locale: string): Promise<MicJob> {
// that is still receiving audio is someone speaking — reject instead of
// killing their dictation mid-sentence.
if (reclaimStale().liveRemains) {
- throw new Error("A dictation is already running — finish it first.");
+ throw new UserError("dictation_busy", "A dictation is already running — finish it first.");
}
const bin = await ensureStt();
const id = crypto.randomUUID().slice(0, 12);
@@ -131,7 +131,7 @@ export async function startMicJob(locale: string): Promise<MicJob> {
job.text = ev.text ?? job.text;
if (job.status === "running") job.status = "done";
} else if (ev.type === "error") {
- job.error = ev.text || "Transcription failed.";
+ Object.assign(job, errorFields(ev.text, new UserError("transcription_failed", "Transcription failed.")));
if (job.status === "running") job.status = "error";
}
} catch {
@@ -156,7 +156,11 @@ export async function startMicJob(locale: string): Promise<MicJob> {
if (job.status === "running") {
// Closed without a final line — surface whatever the process complained about.
job.status = code === 0 ? "done" : "error";
- if (job.status === "error") job.error = stderr.trim().split("\n").slice(-2).join("\n") || `cut-stt exited ${code}`;
+ if (job.status === "error") {
+ // The tool's own complaint stays in its words; a silent exit names itself.
+ const tail = stderr.trim().split("\n").slice(-2).join("\n");
+ Object.assign(job, errorFields(tail, new UserError("tool_exited", `cut-stt exited ${code}`, { tool: "cut-stt", code: String(code) })));
+ }
}
resolveFinished();
retire(job);
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index 78288ff5..579ceb17 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -2,9 +2,12 @@ import fsSync from "node:fs";
import { isDeliveryName } from "../lib/exportDelivery";
import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
+import { defaultNames } from "@/cut/lib/defaultNames";
import { resolveParent, settleParents, subtreeOf } from "@/cut/lib/folderTree";
import { timelineEnd } from "@/cut/lib/timelineEnd";
import type { Aspect, ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
+import { DEFAULT_LOCALE, type Locale } from "@/i18n/locales";
+import { UserError } from "@/cut/lib/userError";
import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { exists, uniqueName, writeJsonAtomic } from "./util";
@@ -23,8 +26,8 @@ const ID_RE = /^[a-z0-9][a-z0-9-]{2,40}$/;
/** The Finder-safe folder name for a display name: path-hostile characters
* become spaces, leading dots go (a hidden project folder helps nobody), and
- * an empty result falls back to Untitled. */
-function dirNameFrom(name: string): string {
+ * an empty result falls back to `fallback`. */
+function dirNameFrom(name: string, fallback: string): string {
const cleaned = name
.replace(/[/\\:*?"<>|]/g, " ")
.replace(/\s+/g, " ")
@@ -32,7 +35,7 @@ function dirNameFrom(name: string): string {
.replace(/^\.+/, "")
.slice(0, 60)
.trim();
- return cleaned || "Untitled";
+ return cleaned || fallback;
}
// Names inside projects/ that belong to the app itself, never to a project
@@ -163,7 +166,8 @@ function followName(id: string, name: string) {
const current = resolveDirName(id);
if (!current || hasActiveJobs(id)) return;
const root = projectsRoot();
- const want = dirNameFrom(name);
+ // A name with nothing Finder can hold leaves the folder where it is.
+ const want = dirNameFrom(name, current);
if (want.toLowerCase() === current.toLowerCase()) {
if (want === current) return;
// Case-only rename: same folder on a case-insensitive disk, so there is
@@ -358,11 +362,13 @@ export async function writeProject(id: string, doc: ProjectDoc) {
export async function createProject(
name: string,
folderId: string | null = null,
- aspect: Aspect | null = null
+ aspect: Aspect | null = null,
+ locale: Locale = DEFAULT_LOCALE
): Promise<ProjectSummary> {
const id = crypto.randomUUID().slice(0, 10);
- const displayName = name.trim() || "Untitled";
- const dirName = await claimDir(dirNameFrom(displayName));
+ const names = await defaultNames(locale);
+ const displayName = name.trim() || names.untitled;
+ const dirName = await claimDir(dirNameFrom(displayName, names.untitled));
const dir = path.join(projectsRoot(), dirName);
await mkdir(path.join(dir, "media"), { recursive: true });
await mkdir(path.join(dir, "exports"), { recursive: true });
@@ -391,12 +397,12 @@ export async function createProject(
export async function deleteProject(id: string) {
const dir = projectDir(id);
const doc = await readProject(id);
- if (!doc) throw new Error("Project not found.");
+ if (!doc) throw new UserError("project_not_found", "Project not found.");
// Final backstop before an rm -rf: the folder's own doc must carry the id
// being deleted, so a mis-resolved folder can never be the one removed.
if (doc.id !== undefined && doc.id !== id) {
dirIndex.delete(id);
- throw new Error("Project not found.");
+ throw new UserError("project_not_found", "Project not found.");
}
await rm(dir, { recursive: true, force: true });
dirIndex.delete(id);
@@ -498,7 +504,7 @@ export async function createProjectFolder(
parentId: string | null = null
): Promise<ProjectFolder> {
const trimmed = name.trim();
- if (!trimmed) throw new Error("Folder name required.");
+ if (!trimmed) throw new UserError("folder_name_required", "Folder name required.");
const id = crypto.randomUUID().slice(0, 8);
return mutateFolders(({ folders }) => {
const folder: ProjectFolder = {
@@ -519,10 +525,10 @@ export async function updateProjectFolder(
patch: { name?: string; parentId?: string | null }
): Promise<ProjectFolder> {
const trimmed = patch.name?.trim();
- if (patch.name !== undefined && !trimmed) throw new Error("Folder name required.");
+ if (patch.name !== undefined && !trimmed) throw new UserError("folder_name_required", "Folder name required.");
return mutateFolders(({ folders }) => {
const folder = folders.find((f) => f.id === id);
- if (!folder) throw new Error("Folder not found.");
+ if (!folder) throw new UserError("folder_not_found", "Folder not found.");
if (trimmed) folder.name = trimmed.slice(0, 80);
if (patch.parentId !== undefined) folder.parentId = resolveParent(folders, id, patch.parentId);
return folder;
@@ -546,9 +552,9 @@ export async function deleteProjectFolder(id: string) {
export async function moveProjectToFolder(id: string, folderId: string | null) {
const doc = await readProject(id);
- if (!doc) throw new Error("Project not found.");
+ if (!doc) throw new UserError("project_not_found", "Project not found.");
if (folderId && !(await readFolders()).some((f) => f.id === folderId)) {
- throw new Error("Folder not found.");
+ throw new UserError("folder_not_found", "Folder not found.");
}
doc.folderId = folderId;
await writeProject(id, doc);
@@ -556,12 +562,13 @@ export async function moveProjectToFolder(id: string, folderId: string | null) {
/** Duplicate a project: copy the doc and its media (not its exports) into a
* fresh project folder. */
-export async function duplicateProject(id: string): Promise<ProjectSummary> {
+export async function duplicateProject(id: string, locale: Locale = DEFAULT_LOCALE): Promise<ProjectSummary> {
const doc = await readProject(id);
- if (!doc) throw new Error("Project not found.");
+ if (!doc) throw new UserError("project_not_found", "Project not found.");
const newId = crypto.randomUUID().slice(0, 10);
- const name = `${doc.name} copy`;
- const dirName = await claimDir(dirNameFrom(name));
+ const names = await defaultNames(locale);
+ const name = names.copy(doc.name);
+ const dirName = await claimDir(dirNameFrom(name, names.untitled));
const dir = path.join(projectsRoot(), dirName);
await mkdir(path.join(dir, "media"), { recursive: true });
await mkdir(path.join(dir, "exports"), { recursive: true });
diff --git a/site/src/cut/server/proxy.ts b/site/src/cut/server/proxy.ts
index de9685fa..43a89a92 100644
--- a/site/src/cut/server/proxy.ts
+++ b/site/src/cut/server/proxy.ts
@@ -4,6 +4,7 @@ import { hasVp9Encoder, runFfmpeg, videoEncoder, vtQuality, type RenderHandle }
import { assertGraphSafe } from "./filterGraph";
import { streamCodecs } from "./convert";
import { videoDimensions } from "./util";
+import { UserError } from "../lib/userError";
import type { CompatCover } from "../lib/proxyNames";
/**
@@ -134,13 +135,13 @@ export function probeProxySource(file: string): Promise<ProxySource> {
let out = "";
const timer = setTimeout(() => {
p.kill("SIGKILL");
- reject(new Error("Media inspection timed out."));
+ reject(new UserError("media_inspect_timed_out", "Media inspection timed out."));
}, 30_000);
timer.unref();
p.stdout.on("data", (d) => (out += d));
p.on("close", (code) => {
clearTimeout(timer);
- if (code !== 0) return reject(new Error("Could not inspect this media file."));
+ if (code !== 0) return reject(new UserError("media_inspect_failed", "Could not inspect this media file."));
try {
const streams = (JSON.parse(out).streams ?? []) as {
codec_type?: string;
@@ -151,7 +152,7 @@ export function probeProxySource(file: string): Promise<ProxySource> {
side_data_list?: { rotation?: number }[];
}[];
const video = streams.find((s) => s.codec_type === "video");
- if (!video) return reject(new Error("That file carries no video."));
+ if (!video) return reject(new UserError("media_no_video", "That file carries no video."));
resolve({
matrix: proxyMatrixOf(video.color_space),
fullRange: video.color_range === "pc",
@@ -294,8 +295,8 @@ export async function makeCompatProxy(
opts: CompatArgs & { onProgress?: (seconds: number) => void }
): Promise<ProxyOutcome> {
const codecs = await streamCodecs(src);
- if (opts.cover === "video" && !codecs.video) throw new Error("That file carries no video.");
- if (opts.cover === "video" && !(await hasVp9Encoder())) throw new Error("This machine's ffmpeg has no VP9 encoder.");
+ if (opts.cover === "video" && !codecs.video) throw new UserError("media_no_video", "That file carries no video.");
+ if (opts.cover === "video" && !(await hasVp9Encoder())) throw new UserError("proxy_no_vp9_encoder", "This machine's ffmpeg has no VP9 encoder.");
const [source, dims, h264] = await Promise.all([
codecs.video ? probeProxySource(src) : Promise.resolve(null),
codecs.video ? videoDimensions(src) : Promise.resolve(null),
diff --git a/site/src/cut/server/sourceExport.ts b/site/src/cut/server/sourceExport.ts
index 97a71655..90925790 100644
--- a/site/src/cut/server/sourceExport.ts
+++ b/site/src/cut/server/sourceExport.ts
@@ -4,6 +4,7 @@ import { ALL_FORMATS, CustomSource, Input } from "mediabunny";
import { prepareSourceRemux, prepareTrimRemux } from "../lib/sourceRemux";
import type { SourceSegment } from "../lib/sourceExportPlan";
import { runFfmpeg, type RenderHandle } from "./exportPipeline";
+import { UserError, errorFromBody } from "../lib/userError";
/** The Mac and worker share the packet copier with browser exports. */
export async function exportSourceFiles(job: RenderHandle, resolve: (file: string) => string, segments: SourceSegment[], codec: "h264" | "hevc", audioBitrate?: number) {
@@ -11,7 +12,11 @@ export async function exportSourceFiles(job: RenderHandle, resolve: (file: strin
const sources: Awaited<ReturnType<typeof open>>[] = [];
const readers: Input[] = [];
const scratch: string[] = [];
- const stop = () => { if (job.error) throw new Error(job.error); };
+ const stop = () => {
+ if (job.error) {
+ throw errorFromBody(job, job.error);
+ }
+ };
const read = async (file: string) => {
const source = await open(file, "r");
sources.push(source);
@@ -23,7 +28,9 @@ export async function exportSourceFiles(job: RenderHandle, resolve: (file: strin
while (filled < buffer.length) {
stop();
const { bytesRead } = await source.read(buffer, filled, buffer.length - filled, start + filled);
- if (!bytesRead) throw new Error("Source file ended during export.");
+ if (!bytesRead) {
+ throw new UserError("source_export_truncated", "Source file ended during export.");
+ }
filled += bytesRead;
}
return buffer;
@@ -41,7 +48,9 @@ export async function exportSourceFiles(job: RenderHandle, resolve: (file: strin
let written = 0;
while (written < data.length) {
const { bytesWritten } = await target.write(data, written, data.length - written, position + written);
- if (!bytesWritten) throw new Error("Could not write source export.");
+ if (!bytesWritten) {
+ throw new UserError("source_export_write_failed", "Could not write source export.");
+ }
written += bytesWritten;
}
},
@@ -78,7 +87,9 @@ export async function exportSourceFiles(job: RenderHandle, resolve: (file: strin
(seconds) => { job.progress = 0.3 + Math.min(0.5, seconds / duration * 0.5); });
stop();
const joined = await prepareTrimRemux(await read(videoPath), { file: videoPath, from: 0, to: duration }, codec, await read(audioPath));
- if (!joined) throw new Error("Could not mux the source export audio.");
+ if (!joined) {
+ throw new UserError("source_export_mux_failed", "Could not mux the source export audio.");
+ }
await write(joined, job.outPath, (ratio) => { job.progress = 0.8 + ratio * 0.2; });
return true;
} finally {
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index bff040dc..3331a9ed 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -10,7 +10,8 @@ import { mediaPath, readProject } from "./projects";
import { retimeOf, type SpeedNode } from "@donkeycut/effects-kit";
import { CLIP_MIN_SECONDS } from "../lib/types";
import { bakeRetimedAudio, type BakedAudio } from "./retimeAudio";
-import { atempoChain, findOnPath, hasStream, num, round, errorMessage } from "./util";
+import { atempoChain, findOnPath, hasStream, num, round, errorRecord } from "./util";
+import { UserError, type ErrorFields } from "../lib/userError";
/** The audible slice of the cut, in timeline time (mirrors ExportSpec). */
export interface TranscribeSpec {
@@ -54,12 +55,11 @@ export interface Cue {
words: Word[];
}
-export interface TranscribeJob {
+export interface TranscribeJob extends ErrorFields {
id: string;
projectId: string;
status: "running" | "done" | "error";
stage: "audio" | "model" | "transcribe";
- error?: string;
cues?: Cue[];
}
@@ -120,7 +120,8 @@ function run(cmd: string, args: string[], notFound?: string, timeoutMs = 600_000
let err = "";
const timer = setTimeout(() => {
p.kill("SIGKILL");
- reject(new Error(`${cmd} timed out after ${Math.round(timeoutMs / 1000)}s.`));
+ const seconds = Math.round(timeoutMs / 1000);
+ reject(new UserError("tool_timed_out", `${cmd} timed out after ${seconds}s.`, { tool: cmd, seconds }));
}, timeoutMs);
timer.unref();
p.stdout.on("data", (d) => (out += d));
@@ -131,8 +132,13 @@ function run(cmd: string, args: string[], notFound?: string, timeoutMs = 600_000
});
p.on("close", (code) => {
clearTimeout(timer);
- if (code === 0) resolve(out);
- else reject(new Error(err.trim().split("\n").slice(-4).join("\n") || `${cmd} exited ${code}`));
+ if (code === 0) {
+ return resolve(out);
+ }
+
+ // The tool's own complaint stays in its words; a silent exit names itself.
+ const tail = err.trim().split("\n").slice(-4).join("\n");
+ reject(tail ? new Error(tail) : new UserError("tool_exited", `${cmd} exited ${code}`, { tool: cmd, code: String(code) }));
});
});
}
@@ -148,7 +154,7 @@ export async function ensureStt(): Promise<string> {
const prebuilt = await findOnPath("cut-stt");
if (prebuilt) return prebuilt;
if (process.env.DONKEY_CUT_ENGINE) {
- throw new Error("The speech tool is missing. Update Donkey to restore transcription.");
+ throw new UserError("speech_tool_missing", "The speech tool is missing. Update Donkey to restore transcription.");
}
const src = path.join(process.cwd(), "src", "cut", "server", "native", "cut-stt.swift");
@@ -156,7 +162,7 @@ export async function ensureStt(): Promise<string> {
const [b, s] = await Promise.all([stat(bin).catch(() => null), stat(src).catch(() => null)]);
if (b?.isFile() && (!s || b.mtimeMs >= s.mtimeMs)) return bin;
if (!s) {
- throw new Error("The speech tool is missing. Update Donkey to restore transcription.");
+ throw new UserError("speech_tool_missing", "The speech tool is missing. Update Donkey to restore transcription.");
}
await mkdir(path.dirname(bin), { recursive: true });
await run(
@@ -164,7 +170,7 @@ export async function ensureStt(): Promise<string> {
["-O", "-parse-as-library", src, "-o", bin],
"Swift compiler not found. Install the Xcode Command Line Tools: xcode-select --install"
).catch((e: Error) => {
- throw new Error(`Could not build the on-device speech engine (needs macOS 26+).\n${e.message}`);
+ throw new UserError("speech_engine_build_failed", `Could not build the on-device speech engine (needs macOS 26+).\n${e.message}`, { reason: e.message });
});
return bin;
}
@@ -290,7 +296,7 @@ export async function createAudioTranscribeJob(
void inSpeechTurn(() => runAudioTranscribe(job, audio, opts))
.catch((err: unknown) => {
job.status = "error";
- job.error = errorMessage(err, String(err));
+ Object.assign(job, errorRecord(err, String(err)));
})
.finally(() => retire(job));
return job;
@@ -344,19 +350,19 @@ export async function createTranscribeJob(spec: TranscribeSpec): Promise<Transcr
void inSpeechTurn(() => runTranscribe(job, spec))
.catch((err: unknown) => {
job.status = "error";
- job.error = errorMessage(err, String(err));
+ Object.assign(job, errorRecord(err, String(err)));
})
.finally(() => retire(job));
return job;
}
async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
- if (!(await readProject(spec.projectId))) throw new Error("Project not found.");
+ if (!(await readProject(spec.projectId))) throw new UserError("project_not_found", "Project not found.");
// Video clips or a soundtrack clip are both valid speech sources (the render
// below mixes either), so an audio-only cut — a voiceover with no video, or a
// brief-to-video run transcribing its audio spine — transcribes fine.
if (spec.clips.length === 0 && spec.audio.length === 0)
- throw new Error("Add audio or video to the timeline first.");
+ throw new UserError("timeline_media_required", "Add audio or video to the timeline first.");
const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-stt-"));
try {
@@ -372,7 +378,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
await Promise.all(
paths.map(async (p, i) => {
if (!(await stat(p).catch(() => null)))
- throw new Error(`Media file missing: ${files[i]}`);
+ throw new UserError("media_file_missing_named", `Media file missing: ${files[i]}`, { name: files[i] });
})
);
files.forEach((f, i) => {
diff --git a/site/src/cut/server/urlDownload.ts b/site/src/cut/server/urlDownload.ts
index baa764ea..d001dff9 100644
--- a/site/src/cut/server/urlDownload.ts
+++ b/site/src/cut/server/urlDownload.ts
@@ -8,6 +8,7 @@ import { parseHTML } from "linkedom";
import { convertToMp4, fitsAlready, streamCodecs } from "./convert";
import type { LibrarySource } from "./library";
import { pexelsFileUrl, pexelsVideo } from "./pexels";
+import { UserError } from "../lib/userError";
// Bring back whatever a URL points at. yt-dlp, resolved from PATH, pulls
// anything with a video or audio stream (TikTok, YouTube, Instagram, …); X's
@@ -120,7 +121,7 @@ export async function download(
}
}
const first = failures[0];
- throw first instanceof Error ? first : new Error("Nothing could be imported from that URL.");
+ throw first instanceof Error ? first : new UserError("url_nothing_imported", "Nothing could be imported from that URL.");
}
/** A Pexels video by its page link: the page refuses a server, so its best
@@ -135,8 +136,10 @@ async function downloadPexels(
const file = video.file ?? (await pexelsFileUrl(video.id));
// Newer videos name their files by a second id only the page shows.
if (!file)
- throw new Error(
- `Pexels video ${video.id} keeps its files under names only its page shows: read the page for its videos.pexels.com/video-files/${video.id}/… link (the 1920 or 1080 wide one) and import that link.`
+ throw new UserError(
+ "pexels_files_hidden",
+ `Pexels video ${video.id} keeps its files under names only its page shows: read the page for its videos.pexels.com/video-files/${video.id}/… link (the 1920 or 1080 wide one) and import that link.`,
+ { id: video.id }
);
const got = await downloadMedia(file, tmp, opts);
const title = (video.file ? video.title : `${video.title} (Pexels ${video.id})`).slice(0, 120);
@@ -154,7 +157,11 @@ class MediaHostError extends Error {}
/** The bundled tool is missing — every retry lands here, so the first attempt
* is the last. */
-class MissingToolError extends Error {}
+class MissingToolError extends UserError {
+ constructor() {
+ super("url_tool_missing", "yt-dlp is not available in this build.");
+ }
+}
async function downloadMedia(url: string, tmp: string, opts: DownloadOptions = {}): Promise<Downloaded> {
// Read what sits at the URL before pulling any bytes. The extractor name
@@ -186,7 +193,7 @@ async function downloadMedia(url: string, tmp: string, opts: DownloadOptions = {
}
// Pick the largest media file left behind (the merged output).
const names = (await readdir(out)).filter((f) => MEDIA_EXT.test(f));
- if (names.length === 0) throw new Error("Nothing downloadable was found at that URL.");
+ if (names.length === 0) throw new UserError("url_nothing_downloadable", "Nothing downloadable was found at that URL.");
const sized = await Promise.all(
names.map(async (n) => ({ n, size: (await stat(path.join(out, n))).size }))
);
@@ -267,7 +274,7 @@ async function savePoster(
async function downloadDirectImage(url: string, dir: string): Promise<Downloaded> {
const res = await fetch(url);
- if (!res.ok) throw new Error("Could not download that image.");
+ if (!res.ok) throw new UserError("image_download_failed", "Could not download that image.");
const name = path.basename(new URL(url).pathname) || "image.jpg";
const file = path.join(dir, name);
await writeFile(file, Buffer.from(await res.arrayBuffer()));
@@ -384,7 +391,7 @@ async function xArticle(
const cover = scraped.cover || article.cover_media?.media_info?.original_img_url;
const text = clamp([postWords, title, body].filter(Boolean).join("\n\n"), MAX_PAGE_TEXT);
if (!text && !cover) {
- throw new Error("Could not read that X Article — import the post that published it.");
+ throw new UserError("x_article_unreadable", "Could not read that X Article — import the post that published it.");
}
const files = cover
? [await savePhoto(cover, dir, "article-cover", title || "Article cover")]
@@ -455,7 +462,7 @@ async function savePhoto(
): Promise<{ file: string; title: string }> {
let img = await fetch(`${photoUrl}${photoUrl.includes("?") ? "&" : "?"}name=orig`);
if (!img.ok) img = await fetch(photoUrl);
- if (!img.ok) throw new Error("Could not download the post's photos.");
+ if (!img.ok) throw new UserError("post_photos_download_failed", "Could not download the post's photos.");
const ext = (
/\.(png|jpe?g|webp|gif)(?:$|\?)/i.exec(photoUrl)?.[1] ||
(img.headers.get("content-type")?.includes("png") ? "png" : "jpg")
@@ -478,9 +485,9 @@ async function fetchPage(url: string): Promise<{ html: string; url: string }> {
headers: { "user-agent": PAGE_UA, accept: "text/html,application/xhtml+xml,*/*" },
redirect: "follow",
});
- if (!res.ok) throw new Error(`That page could not be read (${res.status}).`);
+ if (!res.ok) throw new UserError("page_read_failed", `That page could not be read (${res.status}).`, { status: res.status });
const type = res.headers.get("content-type") ?? "";
- if (type && !/text\/|xml|json/i.test(type)) throw new Error("That URL is not a readable page.");
+ if (type && !/text\/|xml|json/i.test(type)) throw new UserError("url_not_readable_page", "That URL is not a readable page.");
const buf = await res.arrayBuffer();
const bytes = buf.byteLength > MAX_PAGE_BYTES ? buf.slice(0, MAX_PAGE_BYTES) : buf;
return { html: Buffer.from(bytes).toString("utf8"), url: res.url || url };
@@ -725,7 +732,7 @@ function ytDlpBinaries(): string[] {
* the build that answered so the download starts with the one that works. */
async function probeUrl(url: string): Promise<{ meta: YtMeta; bin: string }> {
const bins = ytDlpBinaries();
- if (bins.length === 0) throw new MissingToolError("yt-dlp is not available in this build.");
+ if (bins.length === 0) throw new MissingToolError();
let first: unknown;
for (const bin of bins) {
try {
@@ -734,7 +741,7 @@ async function probeUrl(url: string): Promise<{ meta: YtMeta; bin: string }> {
first ??= e;
}
}
- throw first instanceof Error ? first : new Error("Nothing could be read at that URL.");
+ throw first instanceof Error ? first : new UserError("url_nothing_readable", "Nothing could be read at that URL.");
}
// What the whole ladder may spend. Someone is watching a tile the entire time,
@@ -769,7 +776,7 @@ async function runYtDlp(
first ??= e;
}
}
- throw first instanceof Error ? first : new Error("Download failed.");
+ throw first instanceof Error ? first : new UserError("download_failed", "Download failed.");
}
function ytDlp(
@@ -871,7 +878,7 @@ function ytDlpJson(bin: string, args: string[], timeoutMs = 300_000): Promise<Yt
const p = spawn(bin, ["--no-playlist", "--no-progress", ...args]);
const timer = setTimeout(() => {
p.kill("SIGKILL");
- reject(new Error("Download timed out."));
+ reject(new UserError("download_timed_out", "Download timed out."));
}, timeoutMs);
timer.unref();
let out = "";
@@ -883,7 +890,7 @@ function ytDlpJson(bin: string, args: string[], timeoutMs = 300_000): Promise<Yt
// Bun and Node word a missing binary differently; the code is the same.
reject(
(e as NodeJS.ErrnoException).code === "ENOENT"
- ? new MissingToolError("yt-dlp is not available in this build.")
+ ? new MissingToolError()
: e
);
});
diff --git a/site/src/cut/server/urlImport.ts b/site/src/cut/server/urlImport.ts
index ad71dd9e..978ef8ed 100644
--- a/site/src/cut/server/urlImport.ts
+++ b/site/src/cut/server/urlImport.ts
@@ -7,6 +7,7 @@ import { mediaDir, mediaPath as projectMediaPath, readProject } from "./projects
import { download, type Downloaded, type DownloadOptions } from "./urlDownload";
import { URL_BUSY_MESSAGE, URL_DOWNLOADS_MAX } from "../lib/urlBatch";
import { uniqueName } from "./util";
+import { UserError } from "../lib/userError";
// Import a URL (TikTok, YouTube, Instagram, an X post, a page, …) into the
// library or a project. The fetch itself lives in urlDownload.ts (the bundled yt-dlp,
@@ -29,9 +30,9 @@ async function withDownload<T>(
consume: (dl: Downloaded) => Promise<T>
): Promise<T> {
assertLocalRuntime();
- if (!/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");
+ if (!/^https?:\/\//i.test(url.trim())) throw new UserError("url_invalid", "Enter a valid http(s) URL.");
if (active >= MAX_ACTIVE) {
- throw new Error(URL_BUSY_MESSAGE);
+ throw new UserError("downloads_busy", URL_BUSY_MESSAGE);
}
active++;
try {
@@ -55,7 +56,7 @@ export async function importFromUrl(
opts: DownloadOptions = {}
): Promise<LibraryAsset[]> {
return withDownload(url, opts, async (dl) => {
- if (dl.files.length === 0) throw new Error("That link has no media to import.");
+ if (dl.files.length === 0) throw new UserError("link_no_media", "That link has no media to import.");
const assets: LibraryAsset[] = [];
for (const f of dl.files) {
assets.push(await addDownloaded(f.file, f.title, dl.source, f.poster));
@@ -73,7 +74,7 @@ export async function importUrlToProject(
url: string,
opts: DownloadOptions = {}
): Promise<{ files: { fileName: string; title: string }[]; source: LibrarySource; text?: string }> {
- if (!(await readProject(projectId))) throw new Error("Project not found.");
+ if (!(await readProject(projectId))) throw new UserError("project_not_found", "Project not found.");
return withDownload(url, opts, async (dl) => {
await mkdir(mediaDir(projectId), { recursive: true });
const files: { fileName: string; title: string }[] = [];
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index 64001a33..6795b7d6 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -1,13 +1,38 @@
import { spawn } from "node:child_process";
import { access, constants, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
+import { errorBody, errorFields, UserError, type ErrorBody, type ErrorFields } from "../lib/userError";
-/** A failure's message for the person. A full disk names itself in plain words;
+const DISK_FULL_CODES = new Set(["ENOSPC", "EDQUOT"]);
+
+/** A failure as the person reads it. A full disk names itself in plain words;
* its raw text carries a code and a private path. */
-export function errorMessage(e: unknown, fallback: string): string {
+function personFailure(e: unknown): unknown {
const code = (e as { code?: unknown } | null)?.code;
- if (code === "ENOSPC" || code === "EDQUOT") return "This Mac is out of disk space. Free up space and try again.";
- return e instanceof Error ? e.message : fallback;
+ if (typeof code === "string" && DISK_FULL_CODES.has(code)) {
+ return new UserError("disk_full", "This Mac is out of disk space. Free up space and try again.");
+ }
+ return e;
+}
+
+/** A failure's message for the person. */
+export function errorMessage(e: unknown, fallback: string): string {
+ const failure = personFailure(e);
+ return failure instanceof Error ? failure.message : fallback;
+}
+
+/** A failure's reply body for the person: its English, and its code when it
+ * has one, so the page words it in the reader's language.
+ *
+ * Response.json(errorReply(e, new UserError("convert_failed", "Could not convert that file.")), { status: 500 })
+ */
+export function errorReply(e: unknown, fallback: UserError | string): ErrorBody {
+ return errorBody(personFailure(e), fallback);
+}
+
+/** The fields a job record keeps for a failure, the way errorReply words it. */
+export function errorRecord(e: unknown, fallback: UserError | string): ErrorFields {
+ return errorFields(personFailure(e), fallback);
}
/** Does a file/dir exist? (stat, coerced to a boolean.) */
diff --git a/site/src/cut/worker/cardJob.ts b/site/src/cut/worker/cardJob.ts
index 56292330..7a171fe0 100644
--- a/site/src/cut/worker/cardJob.ts
+++ b/site/src/cut/worker/cardJob.ts
@@ -5,6 +5,7 @@ import type { RenderHandle } from "../server/exportPipeline";
import { assertGraphSafe } from "../server/filterGraph";
import { prisma, registerObject, type ClaimedJob } from "./db";
import { cardKey, uploadFile } from "./r2";
+import { UserError } from "../lib/userError";
// The share card: what a link to a shared project unfurls with. The render
// itself is an ordinary export of the cut's opening seconds (runExportJob
@@ -45,7 +46,9 @@ function ffmpeg(handle: RenderHandle, args: string[]): Promise<void> {
proc.on("close", (code) => {
clearTimeout(timer);
if (code === 0) resolve();
- else reject(new Error(`ffmpeg exited with code ${code}.\n${tail}`));
+ else {
+ reject(new UserError("export_ffmpeg_exited", `ffmpeg exited with code ${code}.\n${tail}`, { code: String(code), log: tail }));
+ }
});
});
}
@@ -109,7 +112,9 @@ export async function storeCardArtifacts(
where: { id: job.id },
select: { state: true },
});
- if (live?.state !== "running") throw new Error("Canceled.");
+ if (live?.state !== "running") {
+ throw new UserError("render_canceled", "Canceled.");
+ }
const stillKey = cardKey(job.userId, projectId, "jpg");
const animKey = cardKey(job.userId, projectId, "gif");
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index 4b9f2a26..027824c3 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -9,6 +9,7 @@ import { prisma, registerObjectIn, storageTransaction, type ClaimedJob } from ".
import { deleteObjects, downloadToFile, exportKey, mediaKey, mimeFor, uploadFile } from "./r2";
import { overlayKey } from "../server/cloud/r2";
import { STORAGE_FULL } from "../lib/operationFailure";
+import { UserError } from "../lib/userError";
import { isTabExport, specMediaFiles, STEMS_MIME, stemsArchiveName } from "../lib/exportDelivery";
import { runnerSession } from "./session";
import type { DocExportAudio } from "../lib/exportPresets";
@@ -126,10 +127,13 @@ export async function runExportJob(
const stored = job.spec as ExportJobSpec;
const projectId = job.projectId ?? stored.spec?.projectId;
if (!projectId) throw new Error("Export job has no project.");
- if (stored.fromDoc && !stored.fromDoc.snapshot?.doc)
- throw new Error("This render has no captured document. Queue the export again.");
+ if (stored.fromDoc && !stored.fromDoc.snapshot?.doc) {
+ throw new UserError("render_snapshot_missing", "This render has no captured document. Queue the export again.");
+ }
// A tab render's claim carries no spec: the tab that made it draws it.
- if (isTabExport(stored)) throw new Error("This export renders in the browser tab that started it.");
+ if (isTabExport(stored)) {
+ throw new UserError("render_in_tab", "This export renders in the browser tab that started it.");
+ }
if (!stored.fromDoc && (!stored.spec || !Array.isArray(stored.spec.clips))) {
throw new Error("Malformed export spec.");
}
@@ -185,7 +189,9 @@ export async function runExportJob(
where: { id: job.id },
select: { state: true },
});
- if (live?.state !== "running") throw new Error("Canceled.");
+ if (live?.state !== "running") {
+ throw new UserError("render_canceled", "Canceled.");
+ }
const mime = mimeFor(outName);
if (body.mediaFrom === "overlays") {
@@ -202,7 +208,9 @@ export async function runExportJob(
if (!preview && typeof stored.maxBytes === "number") {
const size =
(await stat(handle.outPath)).size + (handle.stemsPath ? (await stat(handle.stemsPath)).size : 0);
- if (size > stored.maxBytes) throw new Error(STORAGE_FULL);
+ if (size > stored.maxBytes) {
+ throw new UserError("storage_quota_exceeded", STORAGE_FULL);
+ }
}
// The file and, when asked for, its stems: each its own object and row,
// charged at its own size.
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
index 65214133..1ad4658f 100644
--- a/site/src/cut/worker/importUrlJob.ts
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -11,6 +11,7 @@ import { download } from "../server/urlDownload";
import { videoDimensions } from "../server/util";
import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";
import { deleteObjects, libraryKey, mediaKey, mimeFor, uploadFile } from "./r2";
+import { UserError } from "../lib/userError";
/** What a project import_url job records in CutRenderJob.result — the same
* shape the engine's synchronous import route returns to the client. */
@@ -53,8 +54,8 @@ export async function runImportUrlJob(
maxBytes?: number;
};
if (typeof maxBytes !== "number" || !(maxBytes > 0))
- throw new Error("There is no storage left on this account for an import.");
- if (!url || !/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");
+ throw new UserError("import_no_storage", "There is no storage left on this account for an import.");
+ if (!url || !/^https?:\/\//i.test(url.trim())) throw new UserError("url_invalid", "Enter a valid http(s) URL.");
const toLibrary = target === "library";
const projectId = job.projectId;
if (!toLibrary && !projectId) throw new Error("Import job has no project.");
@@ -80,14 +81,14 @@ export async function runImportUrlJob(
const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-dl-"));
try {
const dl = await download(url.trim(), tmp, { audio: audio === true });
- if (isCanceled()) throw new Error("Import canceled.");
+ if (isCanceled()) throw new UserError("import_canceled", "Import canceled.");
let landing = 0;
for (const f of dl.files) {
landing += (await stat(f.file)).size;
if (f.poster) landing += (await stat(f.poster)).size;
}
if (landing > maxBytes)
- throw new Error("The download is larger than the storage left on this account.");
+ throw new UserError("download_over_storage", "The download is larger than the storage left on this account.");
const rows = await prisma.cutMediaObject.findMany({
where: toLibrary ? { userId: job.userId, kind: "library" } : { projectId, kind: "media" },
@@ -105,7 +106,7 @@ export async function runImportUrlJob(
const libraryRows: string[] = [];
try {
for (const f of dl.files) {
- if (isCanceled()) throw new Error("Import canceled.");
+ if (isCanceled()) throw new UserError("import_canceled", "Import canceled.");
const base = toLibrary ? safeFileName(f.file) : path.basename(f.file);
const fileName = dedupeName(base, taken);
taken.add(fileName);
@@ -201,7 +202,7 @@ async function addLibraryRow(
filing?: { folderId: string; origin: "inspiration" }
): Promise<LibraryAsset> {
const type = libraryTypeOf(fileName);
- if (!type) throw new Error("Unsupported file type.");
+ if (!type) throw new UserError("file_type_unsupported", "Unsupported file type.");
const duration = type === "image" ? 0 : await probeDuration(localFile);
const dims = type === "audio" ? null : await videoDimensions(localFile);
const meta = {
diff --git a/site/src/cut/worker/libraryProxyJob.ts b/site/src/cut/worker/libraryProxyJob.ts
index 9ff8215a..76c36e4f 100644
--- a/site/src/cut/worker/libraryProxyJob.ts
+++ b/site/src/cut/worker/libraryProxyJob.ts
@@ -12,6 +12,7 @@ import { dedupeName } from "../server/cloud/util";
import type { LibraryAsset } from "../server/library";
import { prisma, registerObjectIn, storageTransaction, type ClaimedJob } from "./db";
import { deleteObjects, downloadToFile, libraryKey, uploadFile } from "./r2";
+import { UserError } from "../lib/userError";
/** The edges a library proxy job crosses, stubbed by its test. */
export interface LibraryProxyIO {
@@ -59,9 +60,9 @@ export async function runLibraryProxyJob(
const compat = compatCoverIn(asked);
if (!assetId) throw new Error("Library proxy job has no asset.");
const row = await io.db.cutLibraryAsset.findFirst({ where: { id: assetId, userId: job.userId, deletedAt: null } });
- if (!row) throw new Error(DELETED);
+ if (!row) throw new UserError("library_file_deleted", DELETED);
const media = await io.db.cutMediaObject.findFirst({ where: { id: row.mediaObjectId, userId: job.userId } });
- if (!media) throw new Error("Library media is missing.");
+ if (!media) throw new UserError("library_media_missing", "Library media is missing.");
// A replay, or a second ask after the copy landed, returns what is there.
const had = (row.meta as { proxyFile?: string } | null)?.proxyFile;
@@ -74,7 +75,7 @@ export async function runLibraryProxyJob(
try {
const src = path.join(tmp, path.basename(media.fileName));
await io.download(media.r2Key, src);
- if (isCanceled()) throw new Error("Proxy canceled.");
+ if (isCanceled()) throw new UserError("proxy_canceled", "Proxy canceled.");
// The copy shares the library prefix, so its name is deduped against
// every file the shelf holds there.
@@ -96,7 +97,7 @@ export async function runLibraryProxyJob(
},
};
await (compat ? io.makeCompat(handle, src, out, { ...opts, cover: compat }) : io.make(handle, src, out, opts));
- if (isCanceled()) throw new Error("Proxy canceled.");
+ if (isCanceled()) throw new UserError("proxy_canceled", "Proxy canceled.");
key = libraryKey(job.userId, fileName);
const mime = compat === "video" ? "video/webm" : "video/mp4";
@@ -106,7 +107,7 @@ export async function runLibraryProxyJob(
const updated = await io.transact(async (tx) => {
// The asset may have been deleted while the copy was built.
const live = await tx.cutLibraryAsset.findFirst({ where: { id: assetId, userId: job.userId, deletedAt: null } });
- if (!live) throw new Error(DELETED);
+ if (!live) throw new UserError("library_file_deleted", DELETED);
await io.register(tx, {
userId: job.userId, projectId: null, r2Key: stored, fileName, mime, bytes, kind: "proxy",
});
diff --git a/site/src/cut/worker/libraryUploadJob.ts b/site/src/cut/worker/libraryUploadJob.ts
index c480b69d..de6c9536 100644
--- a/site/src/cut/worker/libraryUploadJob.ts
+++ b/site/src/cut/worker/libraryUploadJob.ts
@@ -9,6 +9,7 @@ import { assetView } from "@/cut/server/cloud/library";
import type { LibraryAsset } from "@/cut/server/library";
import { prisma, registerObjectIn, storageTransaction, type ClaimedJob } from "@/cut/worker/db";
import { deleteObjects, downloadToFile, libraryKey, uploadFile } from "@/cut/worker/r2";
+import { UserError } from "@/cut/lib/userError";
const dependencies = {
db: prisma, download: downloadToFile, upload: uploadFile, remove: deleteObjects,
@@ -27,15 +28,15 @@ export async function runLibraryUploadJob(
const source = await io.db.cutMediaObject.findFirst({
where: { userId: job.userId, r2Key: input.key, kind: "library", projectId: null },
});
- if (!source || libraryUploadId(source.id) !== job.id) throw new Error("Upload not found.");
+ if (!source || libraryUploadId(source.id) !== job.id) throw new UserError("upload_not_found", "Upload not found.");
const already = await io.db.cutLibraryAsset.findFirst({ where: { id: job.id, userId: job.userId } });
if (already) {
- if (already.deletedAt) throw new Error("This imported file was deleted.");
+ if (already.deletedAt) throw new UserError("imported_file_deleted", "This imported file was deleted.");
const media = await io.db.cutMediaObject.findFirst({ where: { id: already.mediaObjectId, userId: job.userId } });
- if (!media) throw new Error("Imported media is missing.");
+ if (!media) throw new UserError("imported_media_missing", "Imported media is missing.");
return assetView(already, media);
}
- const checkCanceled = () => { if (isCanceled()) throw new Error("Import canceled."); };
+ const checkCanceled = () => { if (isCanceled()) throw new UserError("import_canceled", "Import canceled."); };
const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-library-upload-"));
handle.tmpDir = tmp;
let stagedKey: string | undefined;
@@ -46,11 +47,11 @@ export async function runLibraryUploadJob(
await io.download(source.r2Key, src);
checkCanceled();
const bytes = (await stat(src)).size;
- if (bytes !== Number(source.bytes)) throw new Error("The uploaded file is incomplete.");
+ if (bytes !== Number(source.bytes)) throw new UserError("uploaded_file_incomplete", "The uploaded file is incomplete.");
const codecs = await io.codecs(src);
const type = codecs.video ? "video" : "audio";
const duration = await io.duration(src);
- if (!(duration > 0)) throw new Error("This file has no readable media duration.");
+ if (!(duration > 0)) throw new UserError("media_duration_unreadable", "This file has no readable media duration.");
const outputName = `${source.id}.${type === "video" ? "mp4" : "m4a"}`;
const out = path.join(tmp, outputName);
handle.outPath = out;
@@ -71,10 +72,10 @@ export async function runLibraryUploadJob(
const row = await io.transact(async (tx) => {
checkCanceled();
const active = await tx.cutRenderJob.findFirst({ where: { id: job.id, userId: job.userId, state: "running" } });
- if (!active) throw new Error("Import canceled.");
+ if (!active) throw new UserError("import_canceled", "Import canceled.");
if (input.folderId && !(await tx.cutFolder.findFirst({
where: { id: input.folderId, userId: job.userId, scope: "library" },
- }))) throw new Error("The destination folder was deleted.");
+ }))) throw new UserError("destination_folder_deleted", "The destination folder was deleted.");
const sourceId = await io.register(tx, {
userId: job.userId, projectId: null, r2Key: source.r2Key, fileName: source.fileName,
mime: source.mime, bytes, kind: "library",
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 3aaaecba..81082bec 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -10,6 +10,7 @@ import { runTurnJob } from "./turnJob";
import { describeRuntime, installHeadlessRuntime } from "../lib/headless/runtime";
import { deleteObjects } from "./r2";
import { failedJobFate, InputFault, staleRunningFate, TAB_EXPORT_SILENCE_MS } from "./settle";
+import { failureCode, UserError } from "../lib/userError";
// The cloud render worker: a headless loop that claims CutRenderJob rows the
// hosted API queues (export, preview, import_url, convert, proxy, agent_turn),
@@ -23,6 +24,12 @@ import { failedJobFate, InputFault, staleRunningFate, TAB_EXPORT_SILENCE_MS } fr
// someone watches a progress bar. Parallelism comes from replicas instead
// (max_instances / REPLICAS, wrangler.jsonc + cf/worker.ts).
const MAX_RUNNING = 1;
+
+// The failures the loop itself writes to a row.
+const RAN_TOO_LONG = new UserError("job_timed_out", "The job ran too long and was stopped.");
+// A bare network rejection reads as "fetch failed" and says nothing to
+// whoever asked for the render. The row carries words instead.
+const UNREACHABLE = new UserError("render_unreachable", "Could not reach the service — the render stopped. Try it again.");
const IDLE_POLL_MS = 2000;
const WATCH_MS = 1000; // progress write + cancellation check cadence
// Drain-and-exit: once the queue stays empty this long with nothing running,
@@ -133,7 +140,7 @@ function watchJob(id: string, entry: ActiveJob): ReturnType<typeof setInterval>
entry.handle.proc?.kill("SIGKILL");
await prisma.cutRenderJob.updateMany({
where: { id, state: "running" },
- data: { state: "error", error: "The job ran too long and was stopped." },
+ data: { state: "error", error: RAN_TOO_LONG.message, result: { errorCode: RAN_TOO_LONG.code } },
});
return;
}
@@ -219,11 +226,8 @@ async function runJob(job: ClaimedJob): Promise<void> {
console.log(`[cut-worker] ${job.kind} ${job.id} done`);
} catch (err) {
const raw = err instanceof Error ? err.message : String(err);
- // A bare network rejection reads as "fetch failed" and says nothing to
- // whoever asked for the render. The row carries words instead.
- const message = /^(fetch failed|network error|terminated)$/i.test(raw.trim())
- ? "Could not reach the service — the render stopped. Try it again."
- : raw;
+ const failure = /^(fetch failed|network error|terminated)$/i.test(raw.trim()) ? UNREACHABLE : err;
+ const message = failure === UNREACHABLE ? UNREACHABLE.message : raw;
// A canceled job's row already says so; the running-state guard also
// keeps this from resurrecting a row canceled between watcher ticks.
const fate = failedJobFate({ canceled: entry.canceled, signaled, proc: entry.handle.proc });
@@ -237,12 +241,17 @@ async function runJob(job: ClaimedJob): Promise<void> {
})
.catch(() => {});
} else if (fate === "error") {
- // A failure on the job's input records which, for the route to read.
- const fault = err instanceof InputFault ? { result: { fault: err.fault } } : {};
+ // A failure on the job's input records which, and a coded failure its
+ // code, for the route to read.
+ const coded = failureCode(failure);
+ const result = {
+ ...(err instanceof InputFault ? { fault: err.fault } : {}),
+ ...(coded ? { errorCode: coded.code, errorParams: coded.params } : {}),
+ };
await prisma.cutRenderJob
.updateMany({
where: { id: job.id, state: "running" },
- data: { state: "error", error: message, ...fault },
+ data: { state: "error", error: message, ...(Object.keys(result).length ? { result } : {}) },
})
.catch(() => {});
}
diff --git a/site/src/cut/worker/turnJob.ts b/site/src/cut/worker/turnJob.ts
index 95d6d443..aa8c96aa 100644
--- a/site/src/cut/worker/turnJob.ts
+++ b/site/src/cut/worker/turnJob.ts
@@ -1,5 +1,7 @@
import type { UIMessage } from "ai";
+import { DEFAULT_LOCALE, isLocale } from "@/i18n/locales";
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
+import { bindCreatorLocale, requestedLocale } from "../lib/defaultNames";
import { openCloudProject, pushCloudProject } from "../lib/headless/docSession";
import { dropPiSession, streamCutChat } from "../lib/pi/cutAgent";
import { headlessDeps, type HeadlessSession } from "../lib/pi/serverDeps";
@@ -98,6 +100,9 @@ export async function runTurnJob(
if (!spec?.threadId || !Array.isArray(spec.messages))
throw new Error("Turn job carries no thread payload.");
+ // What the turn's tools create is named in the language of the person asking.
+ await bindCreatorLocale(requestedLocale(spec.locale));
+
const session = runnerSession(job);
const doc = await openCloudProject(session, job.projectId);
@@ -133,6 +138,7 @@ export async function runTurnJob(
threadId: piKey,
model: spec.model ?? geminiModelRoleNames.chat,
messages: spec.messages as UIMessage[],
+ locale: isLocale(spec.locale) ? spec.locale : DEFAULT_LOCALE,
abortSignal: abort.signal,
deps,
}).getReader();