Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .sync-ref
Original file line number Diff line number Diff line change
@@ -1 +1 @@
chaibuilder/pro@a4127ad93f51d4f04e4945a035f5845739418ca3
chaibuilder/pro@caffb5c71cef15f8d88ff077343079cca754c220
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import { useAtom, useSetAtom } from "jotai";
import { filter, find, get, has, isEmpty, isFunction } from "lodash-es";
import { DragEvent, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
canvasRenderKeyAtom,
Expand Down Expand Up @@ -63,6 +64,7 @@ import { ChaiBlock } from "~/types/common";
* <div onDrop={onDrop} />
*/
export const useBlockDrop = () => {
const { t } = useTranslation();
const [draggedBlock, setDraggedBlock] = useAtom(dragAndDropAtom);
const setDropIndicator = useSetAtom(dropIndicatorAtom);
const [iframe] = useCanvasIframe();
Expand Down Expand Up @@ -211,7 +213,7 @@ export const useBlockDrop = () => {
const partialBlockId = dropBlock.partialBlockId || "";
const { canAdd, reason } = checkPartialCanAdd(partialBlockId);
if (!canAdd) {
toast.error(reason || `Cannot add this ${singular}`);
toast.error(reason || t("Cannot add this {{name}}", { name: singular }));
return;
}
addCoreBlock(
Expand Down
24 changes: 13 additions & 11 deletions src/builder/core/components/canvas/static/bubble-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
UnderlineIcon,
} from "@radix-ui/react-icons";
import { Editor } from "@tiptap/react";
import { useTranslation } from "react-i18next";
import { cn } from "~/lib/utils";

const BUBBLE_MENU_ICONS = {
Expand Down Expand Up @@ -59,10 +60,11 @@ interface BubbleMenuProps {
}

export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
const { t } = useTranslation();
if (!editor) return null;

const addLink = () => {
const url = window.prompt("Enter URL");
const url = window.prompt(t("Enter URL"));
if (url) {
editor.chain().focus().setLink({ href: url }).run();
}
Expand All @@ -73,32 +75,32 @@ export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
<div className="flex items-center p-1">
<BubbleMenuButton
icon="bold"
title="Bold"
title={t("Bold")}
onClick={() => editor.chain().focus().toggleBold().run()}
isActive={editor.isActive("bold")}
/>
<BubbleMenuButton
icon="italic"
title="Italic"
title={t("Italic")}
onClick={() => editor.chain().focus().toggleItalic().run()}
isActive={editor.isActive("italic")}
/>
<BubbleMenuButton
icon="underline"
title="Underline"
title={t("Underline")}
onClick={() => editor.chain().focus().toggleUnderline().run()}
isActive={editor.isActive("underline")}
/>
<BubbleMenuButton
icon="strikethrough"
title="Strikethrough"
title={t("Strikethrough")}
onClick={() => editor.chain().focus().toggleStrike().run()}
isActive={editor.isActive("strike")}
/>
<div className="mx-1 h-4 w-[1px] bg-white/20" />
<BubbleMenuButton
icon="link"
title={editor.isActive("link") ? "Remove link" : "Add link"}
title={editor.isActive("link") ? t("Remove link") : t("Add link")}
onClick={() => {
if (editor.isActive("link")) {
editor.chain().focus().unsetLink().run();
Expand All @@ -111,32 +113,32 @@ export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
<div className="mx-1 h-4 w-[1px] bg-white/20" />
<BubbleMenuButton
icon="bulletList"
title="Bullet list"
title={t("Bullet list")}
onClick={() => editor.chain().focus().toggleBulletList().run()}
isActive={editor.isActive("bulletList")}
/>
<BubbleMenuButton
icon="orderedList"
title="Numbered list"
title={t("Numbered list")}
onClick={() => editor.chain().focus().toggleOrderedList().run()}
isActive={editor.isActive("orderedList")}
/>
<div className="mx-1 h-4 w-[1px] bg-white/20" />
<BubbleMenuButton
icon="alignLeft"
title="Align left"
title={t("Align left")}
onClick={() => editor.chain().focus().setTextAlign("left").run()}
isActive={editor.isActive({ textAlign: "left" })}
/>
<BubbleMenuButton
icon="alignCenter"
title="Align center"
title={t("Align center")}
onClick={() => editor.chain().focus().setTextAlign("center").run()}
isActive={editor.isActive({ textAlign: "center" })}
/>
<BubbleMenuButton
icon="alignRight"
title="Align right"
title={t("Align right")}
onClick={() => editor.chain().focus().setTextAlign("right").run()}
isActive={editor.isActive({ textAlign: "right" })}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { useTranslation } from "react-i18next";

export const ErrorFallback = () => {
const { t } = useTranslation();
return (
<div className="flex min-h-[100px] items-center justify-center bg-red-50 p-2 text-center text-red-500">
Something went wrong.
{t("Something went wrong.")}
</div>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -341,11 +341,14 @@ const ChaiSlotPlaceholder = ({ name }: { name: string }) => {
);
};

const PartialDepthExceededPlaceholder = () => (
<div className="border-destructive bg-destructive/10 text-destructive flex items-center justify-center rounded-md border p-4 text-center text-sm">
<p>Maximum partial nesting depth ({MAX_PARTIAL_DEPTH} levels) exceeded</p>
</div>
);
const PartialDepthExceededPlaceholder = () => {
const { t } = useTranslation();
return (
<div className="border-destructive bg-destructive/10 text-destructive flex items-center justify-center rounded-md border p-4 text-center text-sm">
<p>{t("Maximum partial nesting depth ({{depth}} levels) exceeded", { depth: MAX_PARTIAL_DEPTH })}</p>
</div>
);
};

const PartialBlocksRenderer = ({ partialBlockId }: { partialBlockId: string }) => {
const { getPartialBlocks } = usePartialBlocksStore();
Expand Down
12 changes: 7 additions & 5 deletions src/builder/core/components/canvas/topbar/page-validation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ export const PageValidation = () => {

const getMessage = () => {
if (hasErrors && hasWarnings) {
return `${errorCount} error${errorCount > 1 ? "s" : ""}, ${warningCount} warning${warningCount > 1 ? "s" : ""}`;
return `${t("{{count}} errors", { count: errorCount })}, ${t("{{count}} warnings", { count: warningCount })}`;
}
if (hasErrors) {
return `${errorCount} error${errorCount > 1 ? "s" : ""}`;
return t("{{count}} errors", { count: errorCount });
}
if (hasWarnings) {
return `${warningCount} warning${warningCount > 1 ? "s" : ""}`;
return t("{{count}} warnings", { count: warningCount });
}
return "";
};
Expand Down Expand Up @@ -67,13 +67,15 @@ export const PageValidation = () => {
? "border border-red-200 bg-red-50 text-red-700"
: "border border-orange-200 bg-orange-50 text-orange-700"
}`}>
<div className="font-medium">{error.severity === "error" ? "Error:" : "Warning:"}</div>
<div className="font-medium">{error.severity === "error" ? t("Error:") : t("Warning:")}</div>
<div>{error.message}</div>
</div>
))}

{errors.length > 5 && (
<p className="text-xs italic text-gray-500">... and {errors.length - 5} more issues</p>
<p className="text-xs italic text-gray-500">
{t("... and {{count}} more issues", { count: errors.length - 5 })}
</p>
)}
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const ValidationErrorsModal = ({
errors,
actionLabel,
showSnooze = false,
blocked = false,
}: {
isOpen: boolean;
onClose: () => void;
Expand All @@ -36,6 +37,8 @@ export const ValidationErrorsModal = ({
errors: StructureError[];
actionLabel: string;
showSnooze?: boolean;
/** Errors must be fixed first: hides the continue action and snooze. */
blocked?: boolean;
}) => {
const { t } = useTranslation();
const [snoozeDays, setSnoozeDays] = useState(NO_SNOOZE);
Expand All @@ -45,7 +48,7 @@ export const ValidationErrorsModal = ({
if (isOpen) setSnoozeDays(NO_SNOOZE);
}, [isOpen]);
const [, setSelectedBlockIds] = useSelectedBlockIds();
const gotoPage = useBuilderProp("gotoPage", (_arg: { pageId: string; lang?: string }) => {});
const gotoPage = useBuilderProp("gotoPage", (_arg: { pageId: string; lang?: string }) => { });
const { selectedLang, fallbackLang } = useLanguages();

const errorList = errors.filter((e) => e.severity === "error");
Expand Down Expand Up @@ -74,7 +77,9 @@ export const ValidationErrorsModal = ({
{t("Page Validation Issues")}
</DialogTitle>
<DialogDescription>
{t("The following issues were found on this page. You can fix them or continue anyway.")}
{blocked
? t("The following issues were found on this page.")
: t("The following issues were found on this page. You can fix them or continue anyway.")}
</DialogDescription>
</DialogHeader>

Expand Down Expand Up @@ -112,7 +117,9 @@ export const ValidationErrorsModal = ({
</div>

<DialogFooter className="gap-2 sm:items-center sm:justify-between sm:gap-0">
{showSnooze ? (
{blocked ? (
<span className="text-xs font-medium text-red-600">{t("Resolve errors to publish the page.")}</span>
) : showSnooze ? (
<div className="flex items-center gap-2">
<span className="text-muted-foreground whitespace-nowrap text-xs">{t("Do not show for")}</span>
<Select value={snoozeDays} onValueChange={setSnoozeDays}>
Expand All @@ -138,9 +145,11 @@ export const ValidationErrorsModal = ({
<Button variant="outline" size="sm" onClick={onClose}>
{t("Cancel")}
</Button>
<Button size="sm" onClick={() => onContinue(showSnooze ? Number(snoozeDays) : 0)}>
{actionLabel}
</Button>
{!blocked && (
<Button size="sm" onClick={() => onContinue(showSnooze ? Number(snoozeDays) : 0)}>
{actionLabel}
</Button>
)}
</div>
</DialogFooter>
</DialogContent>
Expand All @@ -164,12 +173,11 @@ const ValidationErrorItem = ({

return (
<div
className={`rounded p-2 text-xs ${
isError
className={`rounded p-2 text-xs ${isError
? "border border-red-200 bg-red-50 text-red-700"
: "border border-orange-200 bg-orange-50 text-orange-700"
}`}>
<div className="mb-1">{error.message}</div>
}`}>
<div>{error.message}</div>
<div className="flex items-center gap-2">
{error.blockId && !isInPartial && (
<button
Expand Down
86 changes: 86 additions & 0 deletions src/builder/core/components/chaibuilder-editor-locale.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// @vitest-environment happy-dom
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, render, screen } from "@testing-library/react";
import { useTranslation } from "react-i18next";
import { describe, expect, it } from "vitest";
import i18n from "~/builder/core/locales/load";
import { ChaiBuilderEditor } from "./chaibuilder-editor";

const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { enabled: false, retry: false } } });

describe("ChaiBuilderEditor locale plumbing", () => {
it("applies translations before changeLanguage and renders locale='es' on first paint without English flash", () => {
const renderedValues: string[] = [];

const TestLayout = () => {
const { t } = useTranslation();
const label = t("Save");
const custom = t("Host Custom Block");
renderedValues.push(label);
return (
<div>
<span data-testid="save-label">{label}</span>
<span data-testid="custom-label">{custom}</span>
</div>
);
};

render(
<QueryClientProvider client={createQueryClient()}>
<ChaiBuilderEditor
blocks={[]}
locale="es"
translations={{ es: { Save: "Guardar", "Host Custom Block": "Bloque personalizado" } }}
layout={TestLayout}
/>
</QueryClientProvider>,
);

expect(screen.getByTestId("save-label").textContent).toBe("Guardar");
expect(screen.getByTestId("custom-label").textContent).toBe("Bloque personalizado");
// Must not flash the English fallback on the initial render pass.
expect(renderedValues[0]).toBe("Guardar");
});

it("re-renders when a translation bundle is added after mount (bindI18nStore: added)", () => {
const TestLayout = () => {
const { t } = useTranslation();
return <span data-testid="late-key">{t("Late Added Key")}</span>;
};

render(
<QueryClientProvider client={createQueryClient()}>
<ChaiBuilderEditor blocks={[]} locale="es" layout={TestLayout} />
</QueryClientProvider>,
);
expect(screen.getByTestId("late-key").textContent).toBe("Late Added Key");

act(() => {
i18n.addResourceBundle("es", "translation", { "Late Added Key": "Clave agregada tarde" }, true, true);
});

expect(screen.getByTestId("late-key").textContent).toBe("Clave agregada tarde");
});

it("updates language when locale prop changes", () => {
const TestLayout = () => {
const { t } = useTranslation();
return <span data-testid="save-label">{t("Save")}</span>;
};

const queryClient = createQueryClient();
const { rerender } = render(
<QueryClientProvider client={queryClient}>
<ChaiBuilderEditor blocks={[]} locale="es" translations={{ es: { Save: "Guardar" } }} layout={TestLayout} />
</QueryClientProvider>,
);
expect(screen.getByTestId("save-label").textContent).toBe("Guardar");

rerender(
<QueryClientProvider client={queryClient}>
<ChaiBuilderEditor blocks={[]} locale="en" translations={{ es: { Save: "Guardar" } }} layout={TestLayout} />
</QueryClientProvider>,
);
expect(screen.getByTestId("save-label").textContent).toBe("Save");
});
});
Loading
Loading