refactor: consolidate English translations (#6640)

This commit is contained in:
Thomas authored and GitHub committed 2026-08-21 19:00:27 +02:00
1 parent 81aa704537
commit 9e14a07e64
449 files changed
+3515 -3922

No files matched your search

+2 -4
View File
@@ -17,8 +17,6 @@ import {
users,
} from "@homarr/db/schema";
import { getAppManagementAccess, getIntegrationManagementAccess } from "@homarr/definitions";
import type { TranslationObject } from "@homarr/translation";
import { createTRPCRouter, publicProcedure } from "../trpc";
const getFullAccessIntegrationIdsAsync = async (db: Database, userId: string) => {
@@ -49,8 +47,8 @@ const getFullAccessIntegrationIdsAsync = async (db: Database, userId: string) =>
};
interface HomeStatistic {
titleKey: keyof TranslationObject["management"]["page"]["home"]["statistic"];
subtitleKey: keyof TranslationObject["management"]["page"]["home"]["statisticLabel"];
titleKey: "app" | "board" | "group" | "integration" | "invite" | "media" | "searchEngine" | "user";
subtitleKey: "authentication" | "authorization" | "boards" | "resources";
count: number;
path: string;
}
@@ -1,6 +1,7 @@
import type { V1NodeList, VersionInfo } from "@kubernetes/client-node";
import { TRPCError } from "@trpc/server";
import { invariantTechnicalLabels } from "@homarr/definitions";
import type { ClusterResourceCount, KubernetesCluster } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
@@ -81,7 +82,7 @@ export const clusterRouter = createTRPCRouter({
metricsAvailable: nodeMetricsClient !== null,
capacity: [
{
type: "CPU",
type: invariantTechnicalLabels.cpu,
resourcesStats: [
{
percentageValue: reservedCPUPercentage,
+14
View File
@@ -35,6 +35,7 @@ export const resolveAssistantModelId = (models: AssistantModelOption[], value: s
const providerIconBaseUrl = "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-svg@latest/icons";
interface AssistantProviderPreset {
label?: string;
baseUrl: string;
modelDiscoveryPath: string | null;
requiresApiKey: boolean;
@@ -46,6 +47,7 @@ interface AssistantProviderPreset {
export const assistantProviderPresets = {
homarr: {
label: "Homarr",
// Browser and server code replace this public fallback with WORKSHOP_API_URL at runtime.
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
@@ -55,6 +57,7 @@ export const assistantProviderPresets = {
iconUrl: "https://homarr.dev/img/logo.png",
},
openrouter: {
label: "OpenRouter",
baseUrl: "https://openrouter.ai/api/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -63,6 +66,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/openrouter-color.svg`,
},
openai: {
label: "OpenAI",
baseUrl: "https://api.openai.com/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -71,6 +75,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/openai.svg`,
},
anthropic: {
label: "Anthropic Claude",
baseUrl: "https://api.anthropic.com/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -79,6 +84,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/anthropic.svg`,
},
"google-gemini": {
label: "Google Gemini",
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -87,6 +93,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/gemini-color.svg`,
},
xai: {
label: "xAI",
baseUrl: "https://api.x.ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -95,6 +102,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/xai.svg`,
},
groq: {
label: "Groq",
baseUrl: "https://api.groq.com/openai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -104,6 +112,7 @@ export const assistantProviderPresets = {
darkIconUrl: "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-png@latest/dark/groq.png",
},
mistral: {
label: "Mistral AI",
baseUrl: "https://api.mistral.ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -112,6 +121,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/mistral-color.svg`,
},
deepseek: {
label: "DeepSeek",
baseUrl: "https://api.deepseek.com",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -120,6 +130,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/deepseek-color.svg`,
},
together: {
label: "Together AI",
baseUrl: "https://api.together.xyz/v1",
modelDiscoveryPath: "/models",
requiresApiKey: true,
@@ -128,6 +139,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/together-color.svg`,
},
ollama: {
label: "Ollama",
baseUrl: "http://localhost:11434/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
@@ -136,6 +148,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/ollama.svg`,
},
"lm-studio": {
label: "LM Studio",
baseUrl: "http://localhost:1234/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
@@ -144,6 +157,7 @@ export const assistantProviderPresets = {
iconUrl: `${providerIconBaseUrl}/lmstudio.svg`,
},
custom: {
label: undefined,
baseUrl: "",
modelDiscoveryPath: "/models",
requiresApiKey: false,
+2
View File
@@ -2,6 +2,7 @@ export * from "./board";
export * from "./integration";
export * from "./section";
export * from "./widget";
export * from "./widget-name";
export * from "./permissions";
export * from "./docker";
export * from "./kubernetes";
@@ -20,3 +21,4 @@ export * from "./docker-service-discovery";
export * from "./integration-url-template";
export * from "./release-provider";
export * from "./assistant";
export * from "./invariant-technical-labels";
@@ -0,0 +1,14 @@
export const invariantTechnicalLabels = {
cpu: "CPU",
docker: "Docker",
gpu: "GPU",
ram: "RAM",
os: "OS",
id: "ID",
json: "JSON",
jsonSchema: "JSON Schema",
jsx: "JSX",
url: "URL",
} as const;
export type InvariantTechnicalLabel = (typeof invariantTechnicalLabels)[keyof typeof invariantTechnicalLabels];
+3 -2
View File
@@ -1,7 +1,9 @@
import { invariantTechnicalLabels } from "./invariant-technical-labels";
export const kubernetesNodeStates = ["Ready", "NotReady"] as const;
export const kubernetesNamespaceStates = ["Active", "Terminating"] as const;
export const kubernetesResourceTypes = ["Reserved", "Used"] as const;
export const kubernetesCapacityTypes = ["Pods", "CPU", "Memory"] as const;
export const kubernetesCapacityTypes = ["Pods", invariantTechnicalLabels.cpu, "Memory"] as const;
export const kubernetesLabelResourceTypes = [
"configmaps",
"pods",
@@ -12,7 +14,6 @@ export const kubernetesLabelResourceTypes = [
"services",
"volumes",
] as const;
export type KubernetesNodeState = (typeof kubernetesNodeStates)[number];
export type KubernetesNamespaceState = (typeof kubernetesNamespaceStates)[number];
export type KubernetesResourceType = (typeof kubernetesResourceTypes)[number];
+24
View File
@@ -0,0 +1,24 @@
import type { IntegrationKind } from "./integration";
import { getIntegrationName } from "./integration";
import type { WidgetKind } from "./widget";
const widgetIntegrationKinds: Partial<Record<WidgetKind, IntegrationKind>> = {
coolify: "coolify",
tracearr: "tracearr",
paperlessNgx: "paperlessNgx",
patchmon: "patchmon",
bazarr: "bazarr",
uptimeKuma: "uptimeKuma",
traefik: "traefik",
};
export const getWidgetIntegrationName = (kind: WidgetKind): string | undefined => {
const integrationKind = widgetIntegrationKinds[kind];
if (!integrationKind) return undefined;
return getIntegrationName(integrationKind);
};
type WidgetNameTranslator = (key: never) => string;
export const getWidgetName = (kind: WidgetKind, translate: WidgetNameTranslator): string =>
getWidgetIntegrationName(kind) ?? translate(`widget.${kind}.name` as never);
+1
View File
@@ -24,6 +24,7 @@
"@homarr/api": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/form": "workspace:^0.1.0",
"@homarr/notifications": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
@@ -43,7 +43,7 @@ vi.mock("@homarr/auth/client", () => ({
}));
vi.mock("@homarr/translation", () => ({ supportedLanguages: [] }));
vi.mock("@homarr/translation/client", () => ({
useScopedI18n: () => (key: string, params?: Record<string, string>) =>
useI18n: () => (key: string, params?: Record<string, string>) =>
params ? `${key}:${Object.values(params).join(",")}` : key,
}));
vi.mock("../upload-media/upload-media", () => ({
@@ -35,7 +35,7 @@ import {
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { supportedLanguages } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { UploadMedia } from "../upload-media/upload-media";
import { arrangeIconPickerSections, isDirectImageUrl, isImageSource, isSvgImage } from "./icon-picker.utils";
@@ -72,7 +72,7 @@ export const IconPicker = ({
const [keyboardIndex, setKeyboardIndex] = useState(-1);
const [previewState, setPreviewState] = useState<PreviewState>("idle");
const { data: session } = useSession();
const tCommon = useScopedI18n("common");
const tCommon = useI18n("common");
const [debouncedDraft] = useDebouncedValue(draft, 250);
const directUrl = isDirectImageUrl(draft) ? draft.trim() : null;
@@ -7,7 +7,7 @@ import type { z } from "zod/v4";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { appManageSchema } from "@homarr/validation/app";
import { AppForm } from "./_form";
@@ -19,14 +19,14 @@ export const AppNewForm = ({
showCreateAnother: boolean;
showBackToOverview: boolean;
}) => {
const tScoped = useScopedI18n("app.page.create.notification");
const t = useI18n();
const tScoped = useI18n("app.page.create.notification");
const tCommon = useI18n("common");
const router = useRouter();
const { mutate, isPending } = clientApi.app.create.useMutation({
onError: () => {
showErrorNotification({
title: tScoped("error.title"),
title: tCommon("notification.create.error"),
message: tScoped("error.message"),
});
},
@@ -37,7 +37,7 @@ export const AppNewForm = ({
mutate(values, {
onSuccess() {
showSuccessNotification({
title: tScoped("success.title"),
title: tCommon("notification.create.success"),
message: tScoped("success.message"),
});
afterSuccess?.();
@@ -51,14 +51,14 @@ export const AppNewForm = ({
},
});
},
[mutate, router, tScoped],
[mutate, router, tCommon, tScoped],
);
return (
<AppForm
buttonLabels={{
submit: t("common.action.create"),
submitAndCreateAnother: showCreateAnother ? t("common.action.createAnother") : undefined,
submit: tCommon("action.create"),
submitAndCreateAnother: showCreateAnother ? tCommon("action.createAnother") : undefined,
}}
showBackToOverview={showBackToOverview}
handleSubmit={handleSubmit}
@@ -7,6 +7,7 @@ import { useDisclosure } from "@mantine/hooks";
import type { z } from "zod/v4";
import { useZodForm } from "@homarr/form";
import { invariantTechnicalLabels } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { appManageSchema } from "@homarr/validation/app";
@@ -50,7 +51,8 @@ export const AppForm = ({
hideButtons,
formRef,
}: AppFormProps) => {
const t = useI18n();
const tApp = useI18n("app");
const tCommon = useI18n("common");
const form = useZodForm(appManageSchema, {
initialValues: toFormValues(initialValues),
@@ -127,25 +129,25 @@ export const AppForm = ({
const formFields = (
<Stack>
<TextInput {...form.getInputProps("name")} withAsterisk label={t("app.field.name.label")} />
<TextInput {...form.getInputProps("name")} withAsterisk label={tCommon("field.name")} />
<IconPicker
{...form.getInputProps("iconUrl")}
suggestedSearch={initialValues === undefined ? form.values.name : undefined}
/>
<Textarea
{...form.getInputProps("description")}
label={t("app.field.description.label")}
label={tApp("field.description.label")}
autosize
minRows={2}
resize="vertical"
/>
<TextInput {...form.getInputProps("href")} label={t("app.field.url.label")} />
<TextInput {...form.getInputProps("href")} label={invariantTechnicalLabels.url} />
<Checkbox
checked={opened}
onChange={handleClickDifferentUrlPing}
label={t("app.field.useDifferentUrlForPing.checkbox.label")}
description={t("app.field.useDifferentUrlForPing.checkbox.description")}
label={tApp("field.useDifferentUrlForPing.checkbox.label")}
description={tApp("field.useDifferentUrlForPing.checkbox.description")}
mt="md"
/>
@@ -157,7 +159,7 @@ export const AppForm = ({
<Group justify="end">
{showBackToOverview && (
<Button variant="default" component={Link} href="/manage/apps">
{t("common.action.backToOverview")}
{tCommon("action.backToOverview")}
</Button>
)}
{buttonLabels.submitAndCreateAnother && (
@@ -3,7 +3,7 @@
import { PasswordInput, Stack } from "@mantine/core";
import type { PasswordInputProps } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { CustomPasswordInput } from "@homarr/ui";
interface UserCreatePasswordFieldsProps {
@@ -17,7 +17,7 @@ export const UserCreatePasswordFields = ({
confirmPasswordInputProps,
variant,
}: UserCreatePasswordFieldsProps) => {
const t = useScopedI18n("user.field");
const t = useI18n("user.field");
return (
<Stack gap="md">
@@ -5,7 +5,7 @@ import { clientApi } from "@homarr/api/client";
import { AppForm } from "@homarr/forms-collection";
import { createModal, modalSizeForm } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { appManageSchema } from "@homarr/validation/app";
interface QuickAddAppModalProps {
@@ -13,13 +13,14 @@ interface QuickAddAppModalProps {
}
export const QuickAddAppModal = createModal<QuickAddAppModalProps>(({ actions, innerProps }) => {
const tScoped = useScopedI18n("app.page.create.notification");
const t = useI18n();
const tScoped = useI18n("app.page.create.notification");
const tCommon = useI18n("common");
const tBoard = useI18n("board");
const { mutate, isPending } = clientApi.app.create.useMutation({
onError: () => {
showErrorNotification({
title: tScoped("error.title"),
title: tCommon("notification.create.error"),
message: tScoped("error.message"),
});
},
@@ -29,7 +30,7 @@ export const QuickAddAppModal = createModal<QuickAddAppModalProps>(({ actions, i
mutate(values, {
onSuccess(app) {
showSuccessNotification({
title: tScoped("success.title"),
title: tCommon("notification.create.success"),
message: tScoped("success.message"),
});
@@ -42,7 +43,7 @@ export const QuickAddAppModal = createModal<QuickAddAppModalProps>(({ actions, i
return (
<AppForm
buttonLabels={{
submit: t("board.action.quickCreateApp.modal.createAndUse"),
submit: tBoard("action.quickCreateApp.modal.createAndUse"),
submitAndCreateAnother: undefined,
}}
showBackToOverview={false}
@@ -12,7 +12,8 @@ import { useI18n } from "@homarr/translation/client";
import { boardColumnCountSchema, boardCreateSchema, boardNameSchema } from "@homarr/validation/board";
export const AddBoardModal = createModal(({ actions }) => {
const t = useI18n();
const tBoard = useI18n("board");
const tCommon = useI18n("common");
const router = useRouter();
const form = useZodForm(boardCreateSchema, {
mode: "controlled",
@@ -39,8 +40,8 @@ export const AddBoardModal = createModal(({ actions }) => {
onSuccess: (result) => {
actions.closeModal();
showSuccessNotification({
title: t("board.action.create.notification.success.title"),
message: t("board.action.create.notification.success.message", { name: values.name }),
title: tBoard("action.create.notification.success.title"),
message: tBoard("action.create.notification.success.message", { name: values.name }),
});
const name = encodeURIComponent(result.name);
const layoutId = encodeURIComponent(result.layoutId);
@@ -48,8 +49,8 @@ export const AddBoardModal = createModal(({ actions }) => {
},
onError() {
showErrorNotification({
title: t("board.action.create.notification.error.title"),
message: t("board.action.create.notification.error.message", { name: values.name }),
title: tBoard("action.create.notification.error.title"),
message: tBoard("action.create.notification.error.message", { name: values.name }),
});
},
});
@@ -57,7 +58,7 @@ export const AddBoardModal = createModal(({ actions }) => {
>
<Stack>
<TextInput
label={t("board.field.name.label")}
label={tCommon("field.name")}
data-autofocus
{...form.getInputProps("name")}
description={
@@ -71,7 +72,7 @@ export const AddBoardModal = createModal(({ actions }) => {
) : null
}
/>
<InputWrapper label={t("board.field.columnCount.label")} {...form.getInputProps("columnCount")}>
<InputWrapper label={tBoard("field.columnCount.label")} {...form.getInputProps("columnCount")}>
<Slider
min={boardColumnCountSchema.minValue ?? undefined}
max={boardColumnCountSchema.maxValue ?? undefined}
@@ -81,17 +82,17 @@ export const AddBoardModal = createModal(({ actions }) => {
</InputWrapper>
<Switch
label={t("board.field.isPublic.label")}
description={t("board.field.isPublic.description")}
label={tBoard("field.isPublic.label")}
description={tBoard("field.isPublic.description")}
{...form.getInputProps("isPublic")}
/>
<Group justify="right">
<Button onClick={actions.closeModal} variant="subtle" color="gray">
{t("common.action.cancel")}
{tCommon("action.cancel")}
</Button>
<Button type="submit" loading={isPending}>
{t("common.action.create")}
{tCommon("action.create")}
</Button>
</Group>
</Stack>
@@ -102,7 +103,8 @@ export const AddBoardModal = createModal(({ actions }) => {
});
export const useBoardNameStatus = (name: string) => {
const t = useI18n();
const tBoard = useI18n("board");
const tCommon = useI18n("common");
const [debouncedName] = useDebouncedValue(name, 250);
const { data: boardExists, isLoading } = clientApi.board.exists.useQuery(debouncedName, {
enabled: boardNameSchema.safeParse(debouncedName).success,
@@ -115,19 +117,19 @@ export const useBoardNameStatus = (name: string) => {
? undefined
: isLoading
? {
label: t("board.action.create.availability.checking"),
label: tBoard("action.create.availability.checking"),
}
: boardExists === undefined
? undefined
: boardExists
? {
icon: IconAlertTriangle,
label: t("common.zod.errors.custom.boardAlreadyExists"), // The board ${debouncedName} already exists
label: tCommon("zod.errors.custom.boardAlreadyExists"), // The board ${debouncedName} already exists
color: "red",
}
: {
icon: IconCircleCheck,
label: t("board.action.create.availability.available", { name: debouncedName }),
label: tBoard("action.create.availability.available", { name: debouncedName }),
color: "green",
},
};
@@ -18,7 +18,8 @@ interface InnerProps {
}
export const DuplicateBoardModal = createModal<InnerProps>(({ actions, innerProps }) => {
const t = useI18n();
const tBoard = useI18n("board");
const tCommon = useI18n("common");
const form = useZodForm(boardDuplicateSchema.omit({ id: true }), {
mode: "controlled",
initialValues: {
@@ -46,14 +47,14 @@ export const DuplicateBoardModal = createModal<InnerProps>(({ actions, innerProp
onSuccess() {
actions.closeModal();
showSuccessNotification({
title: t("board.action.duplicate.notification.success.title"),
message: t("board.action.duplicate.notification.success.message"),
title: tBoard("action.duplicate.notification.success.title"),
message: tBoard("action.duplicate.notification.success.message"),
});
},
onError() {
showErrorNotification({
title: t("board.action.duplicate.notification.error.title"),
message: t("board.action.duplicate.notification.error.message"),
title: tBoard("action.duplicate.notification.error.title"),
message: tBoard("action.duplicate.notification.error.message"),
});
},
},
@@ -62,11 +63,11 @@ export const DuplicateBoardModal = createModal<InnerProps>(({ actions, innerProp
>
<Stack>
<Text size="sm" c="gray.6">
{t("board.action.duplicate.message", { name: innerProps.board.name })}
{tBoard("action.duplicate.message", { name: innerProps.board.name })}
</Text>
<TextInput
label={t("board.field.name.label")}
label={tCommon("field.name")}
data-autofocus
{...form.getInputProps("name")}
description={
@@ -82,10 +83,10 @@ export const DuplicateBoardModal = createModal<InnerProps>(({ actions, innerProp
<Group justify="end">
<Button variant="subtle" color="gray" onClick={actions.closeModal}>
{t("common.action.cancel")}
{tCommon("action.cancel")}
</Button>
<Button type="submit" loading={isPending}>
{t("common.action.create")}
{tCommon("action.create")}
</Button>
</Group>
</Stack>
@@ -7,11 +7,17 @@ describe("createDockerRemovalConfirmation", () => {
const remove = vi.fn();
const t = vi.fn((key: string, values?: Record<string, string>) => `${key}:${JSON.stringify(values)}`);
const confirmation = createDockerRemovalConfirmation([{ name: "sonarr" }, { name: "radarr" }], t as never, remove);
const confirmation = createDockerRemovalConfirmation(
[{ name: "sonarr" }, { name: "radarr" }],
t as never,
"Remove",
remove,
);
expect(remove).not.toHaveBeenCalled();
expect(confirmation.title).toContain('"count":"2"');
expect(confirmation.children).toContain('"names":"sonarr, radarr"');
expect(confirmation.confirmProps.children).toBe("Remove");
confirmation.onConfirm();
expect(remove).toHaveBeenCalledOnce();
@@ -3,7 +3,7 @@
import { useCallback } from "react";
import { useConfirmModal } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
interface DockerContainerName {
name: string;
@@ -11,7 +11,8 @@ interface DockerContainerName {
export const createDockerRemovalConfirmation = (
containers: DockerContainerName[],
t: ReturnType<typeof useScopedI18n<"docker.action.remove">>,
t: ReturnType<typeof useI18n<"docker.action.remove">>,
confirmLabel: string,
onConfirm: () => void | Promise<void>,
) => ({
title: t("confirmation.title", { count: String(containers.length) }),
@@ -19,18 +20,19 @@ export const createDockerRemovalConfirmation = (
count: String(containers.length),
names: containers.map(({ name }) => name).join(", "),
}),
confirmProps: { children: t("label"), color: "red.9" },
confirmProps: { children: confirmLabel, color: "red.9" },
onConfirm,
});
export const useDockerContainerRemovalConfirmation = () => {
const t = useScopedI18n("docker.action.remove");
const t = useI18n("docker.action.remove");
const commonT = useI18n("common.action");
const { openConfirmModal } = useConfirmModal();
return useCallback(
(containers: DockerContainerName[], onConfirm: () => void | Promise<void>) => {
openConfirmModal(createDockerRemovalConfirmation(containers, t, onConfirm));
openConfirmModal(createDockerRemovalConfirmation(containers, t, commonT("remove"), onConfirm));
},
[openConfirmModal, t],
[commonT, openConfirmModal, t],
);
};
@@ -9,7 +9,8 @@ import { useI18n } from "@homarr/translation/client";
import { groupCreateSchema } from "@homarr/validation/group";
export const AddGroupModal = createModal<void>(({ actions }) => {
const t = useI18n();
const tGroup = useI18n("group");
const tCommon = useI18n("common");
const { mutate, isPending } = clientApi.group.createGroup.useMutation();
const form = useZodForm(groupCreateSchema, {
initialValues: {
@@ -25,27 +26,27 @@ export const AddGroupModal = createModal<void>(({ actions }) => {
actions.closeModal();
void revalidatePathActionAsync("/manage/users/groups");
showSuccessNotification({
title: t("common.notification.create.success"),
message: t("group.action.create.notification.success.message"),
title: tCommon("notification.create.success"),
message: tGroup("action.create.notification.success.message"),
});
},
onError() {
showErrorNotification({
title: t("common.notification.create.error"),
message: t("group.action.create.notification.error.message"),
title: tCommon("notification.create.error"),
message: tGroup("action.create.notification.error.message"),
});
},
});
})}
>
<Stack>
<TextInput label={t("group.field.name")} data-autofocus {...form.getInputProps("name")} />
<TextInput label={tCommon("field.name")} data-autofocus {...form.getInputProps("name")} />
<Group justify="right">
<Button onClick={actions.closeModal} variant="subtle" color="gray">
{t("common.action.cancel")}
{tCommon("action.cancel")}
</Button>
<Button loading={isPending} type="submit">
{t("common.action.create")}
{tCommon("action.create")}
</Button>
</Group>
</Stack>
@@ -2,12 +2,13 @@ import { usePathname } from "next/navigation";
import { Button, CopyButton, Mark, Stack, Text } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { invariantTechnicalLabels } from "@homarr/definitions";
import { createModal } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
export const InviteCopyModal = createModal<RouterOutputs["invite"]["createInvite"]>(({ actions, innerProps }) => {
const t = useScopedI18n("management.page.user.invite");
const t = useI18n("management.page.user.invite");
const inviteUrl = useInviteUrl(innerProps);
return (
@@ -19,7 +20,7 @@ export const InviteCopyModal = createModal<RouterOutputs["invite"]["createInvite
</Text>
<Link href={createPath(innerProps)}>{t("action.copy.link")}</Link>
<Stack gap="xs">
<Text fw="bold">{t("field.id.label")}:</Text>
<Text fw="bold">{invariantTechnicalLabels.id}:</Text>
<Mark style={{ borderRadius: 4 }} color="gray" px={5}>
{innerProps.id}
</Mark>
@@ -6,7 +6,7 @@ import relativeTime from "dayjs/plugin/relativeTime";
import { clientApi } from "@homarr/api/client";
import { useForm } from "@homarr/form";
import { createModal, useModalAction } from "@homarr/modals";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { InviteCopyModal } from "./invite-copy-modal";
@@ -17,7 +17,7 @@ interface FormType {
}
export const InviteCreateModal = createModal<void>(({ actions }) => {
const tInvite = useScopedI18n("management.page.user.invite");
const tInvite = useI18n("management.page.user.invite");
const t = useI18n();
const { openModal } = useModalAction(InviteCopyModal);
+3 -3
View File
@@ -11,7 +11,7 @@ import { revalidatePathActionAsync } from "@homarr/common/client";
import { useZodForm } from "@homarr/form";
import { UserCreatePasswordFields } from "@homarr/forms-collection";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { groupCreateSchema } from "@homarr/validation/group";
import { userInitSchema } from "@homarr/validation/user";
@@ -41,7 +41,7 @@ export const AccountSetup = ({ environment }: OnboardingStudioProps) => {
};
const CredentialsSetup = () => {
const t = useScopedI18n("init.studio.account");
const t = useI18n("init.studio.account");
const [requiresSignIn, setRequiresSignIn] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const recoveryActionRef = useRef<HTMLAnchorElement>(null);
@@ -129,7 +129,7 @@ const CredentialsSetup = () => {
};
const ExternalGroupSetup = () => {
const t = useScopedI18n("init.studio.externalGroup");
const t = useI18n("init.studio.externalGroup");
const [submitError, setSubmitError] = useState<string | null>(null);
const sounds = useOnboardingSounds();
const mutation = clientApi.group.createInitialExternalGroup.useMutation({
+2 -2
View File
@@ -6,7 +6,7 @@ import { IconArrowRight, IconBook2, IconSparkles, IconTool } from "@tabler/icons
import confetti from "canvas-confetti";
import { createDocumentationLink } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { OnboardingBackdrop } from "./onboarding-backdrop";
@@ -16,7 +16,7 @@ import { useOnboardingSounds } from "./use-onboarding-sounds";
import classes from "./onboarding-studio.module.css";
export const Finish = ({ environment }: OnboardingStudioProps) => {
const t = useScopedI18n("init.studio.finish");
const t = useI18n("init.studio.finish");
const sounds = useOnboardingSounds();
const primaryColor = environment.initialBoard?.primaryColor ?? "#fa5252";
const secondaryColor = environment.initialBoard?.secondaryColor ?? "#fd7e14";
@@ -4,7 +4,7 @@ import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { Alert, Button, Center, Paper, Stack, Text, Title } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import type { OnboardingStudioProps } from "./types";
@@ -22,8 +22,8 @@ const getInitialClaimState = (accessState: ReturnType<typeof getOnboardingAccess
};
export const OnboardingStudio = (props: OnboardingStudioProps) => {
const t = useScopedI18n("init.studio.claim");
const tCommon = useScopedI18n("common.action");
const t = useI18n("init.studio.claim");
const tCommon = useI18n("common.action");
const accessState = getOnboardingAccessState(props.environment);
const [claimState, setClaimState] = useState<ClaimState>(() => getInitialClaimState(accessState));
const [claimError, setClaimError] = useState<string | null>(null);
@@ -5,7 +5,7 @@ import { useRef, useState } from "react";
import { FloatingIndicator, Stack, TextInput, UnstyledButton } from "@mantine/core";
import type { UrlTemplateMode } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { useOnboardingSounds } from "./use-onboarding-sounds";
import classes from "./onboarding-studio.module.css";
@@ -78,7 +78,7 @@ export const ServiceUrlTemplate = ({
readOnly,
required,
}: ServiceUrlTemplateProps) => {
const t = useScopedI18n("common.serviceUrlTemplate");
const t = useI18n("common.serviceUrlTemplate");
return (
<Stack gap="sm">
+19 -18
View File
@@ -90,7 +90,7 @@ import {
} from "@homarr/definitions";
import { showErrorNotification, showSuccessNotification, showWarningNotification } from "@homarr/notifications";
import type { SupportedLanguage } from "@homarr/translation";
import { useCurrentLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentLocale, useI18n } from "@homarr/translation/client";
import { BoardColorInput, ColorSchemeCombobox, IntegrationAvatar, LanguageCombobox, Link } from "@homarr/ui";
import { IntegrationMultiSelectGrid } from "@homarr/ui/integration-select-grid";
@@ -153,8 +153,8 @@ const emptyDiscoveredIntegrations: DockerDiscoveryData["integrations"] = [];
const emptyDiscoveredApps: DockerDiscoveryData["apps"] = [];
export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingStudioProps) => {
const t = useScopedI18n("init.studio");
const tCommon = useScopedI18n("common.action");
const t = useI18n("init.studio");
const tCommon = useI18n("common.action");
const currentLocale = useCurrentLocale();
const { colorScheme, setColorScheme } = useMantineColorScheme();
const sounds = useOnboardingSounds();
@@ -709,7 +709,7 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
aria-expanded={incompleteIntegrationConfirmationOpened}
onClick={() => setIncompleteIntegrationConfirmationOpened((opened) => !opened)}
>
{t("continue")}
{tCommon("continue")}
</Button>
</Popover.Target>
<Popover.Dropdown role="dialog" aria-label={t("connect.incompleteConfirmation")}>
@@ -743,7 +743,7 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
rightSection={<IconArrowRight size={16} />}
onClick={continueOnboarding}
>
{t("continue")}
{tCommon("continue")}
</Button>
)}
</Group>
@@ -848,7 +848,7 @@ const SectionHeading = ({
);
const Essentials = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.essentials");
const t = useI18n("init.studio.essentials");
const [isHydrated, setIsHydrated] = useState(false);
useEffect(() => setIsHydrated(true), []);
return (
@@ -897,7 +897,7 @@ const Essentials = (props: StudioSectionProps) => {
};
const Discovery = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.discover");
const t = useI18n("init.studio.discover");
const dockerStatus = !props.environment.dockerConfigured
? "disabled"
: props.docker.isPending
@@ -1025,7 +1025,7 @@ const CapabilityRow = ({
detail: string;
action?: ReactNode;
}) => {
const t = useScopedI18n("init.studio.discover.status");
const t = useI18n("init.studio.discover.status");
const color =
status === "available"
? "green"
@@ -1068,7 +1068,7 @@ const CapabilityRow = ({
};
const Connections = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.connect");
const t = useI18n("init.studio.connect");
return (
<Stack gap="xl">
<SectionHeading headingRef={props.headingRef} title={t("title")} description={t("description")} />
@@ -1209,7 +1209,8 @@ const IntegrationEditor = ({
update: (patch: Partial<IntegrationDraft>) => void;
selectSecretOption: (option: number) => void;
}) => {
const t = useScopedI18n("init.studio.connect");
const t = useI18n("init.studio.connect");
const tCommon = useI18n("common.field");
const sounds = useOnboardingSounds();
const options = getAllSecretKindOptions(draft.kind);
const apiKeyUrl = getIntegrationApiKeyUrl(draft.url, draft.kind);
@@ -1274,7 +1275,7 @@ const IntegrationEditor = ({
<Stack>
<SimpleGrid cols={{ base: 1, sm: 2 }}>
<TextInput
label={t("name")}
label={tCommon("name")}
value={draft.name}
onChange={(event) => updateAndResetTest({ name: event.currentTarget.value })}
/>
@@ -1376,7 +1377,7 @@ const formatSecretKind = (kind: IntegrationSecretKind) =>
kind.replace(/([A-Z])/g, " $1").replace(/^./, (letter) => letter.toUpperCase());
const BoardBuilder = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.board");
const t = useI18n("init.studio.board");
const sounds = useOnboardingSounds();
const validationErrors = getBoardValidationErrors({
attempted: props.boardValidationAttempted,
@@ -1595,7 +1596,7 @@ const BoardPreview = ({
};
const Extensions = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.extend");
const t = useI18n("init.studio.extend");
return (
<Stack gap={0}>
<Title id="studio-section-title" ref={props.headingRef} order={2} tabIndex={-1} mb="xs">
@@ -1610,7 +1611,7 @@ const Extensions = (props: StudioSectionProps) => {
{t("assistant")}
</Tabs.Tab>
<Tabs.Tab value="mcp" leftSection={<IconCode size={16} />}>
{t("mcp")}
MCP
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="workshop" pt="xs">
@@ -1634,7 +1635,7 @@ const AssistantSetup = ({
environment: StudioSectionProps["environment"];
configuration: ReactNode;
}) => {
const t = useScopedI18n("init.studio.extend.assistantSetup");
const t = useI18n("init.studio.extend.assistantSetup");
if (!environment.canConfigurePrivileged) {
return (
<Alert icon={<IconKey size={18} />} title={t("loginTitle")}>
@@ -1658,7 +1659,7 @@ const WorkshopSetup = ({
environment: StudioSectionProps["environment"];
runtimeCapabilities: StudioSectionProps["runtimeCapabilities"];
}) => {
const t = useScopedI18n("init.studio.extend.workshopSetup");
const t = useI18n("init.studio.extend.workshopSetup");
const status = runtimeCapabilities.isPending
? "checking"
: runtimeCapabilities.data?.workshop.status === "available"
@@ -1716,7 +1717,7 @@ const WorkshopFeature = ({ title, description }: { title: string; description: s
);
const McpSetup = ({ environment }: { environment: StudioSectionProps["environment"] }) => {
const t = useScopedI18n("init.studio.extend.mcpSetup");
const t = useI18n("init.studio.extend.mcpSetup");
const [apiKey, setApiKey] = useState<string | null>(null);
const sounds = useOnboardingSounds();
const createKey = clientApi.apiKeys.create.useMutation({
@@ -1822,7 +1823,7 @@ const McpSetup = ({ environment }: { environment: StudioSectionProps["environmen
};
const Review = (props: StudioSectionProps) => {
const t = useScopedI18n("init.studio.review");
const t = useI18n("init.studio.review");
const themeLabel = {
auto: t("themeAuto"),
light: t("themeLight"),
+3 -3
View File
@@ -7,7 +7,7 @@ import { IconArrowRight, IconDatabaseImport } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { OnboardingBackdrop } from "./onboarding-backdrop";
import { OnboardingWordmark } from "./onboarding-wordmark";
@@ -16,8 +16,8 @@ import { useOnboardingSounds, useWelcomeSound } from "./use-onboarding-sounds";
import classes from "./onboarding-studio.module.css";
export const Welcome = ({ environment, sqliteRestore }: OnboardingStudioProps) => {
const t = useScopedI18n("init.studio.welcome");
const claimT = useScopedI18n("init.studio.claim");
const t = useI18n("init.studio.welcome");
const claimT = useI18n("init.studio.claim");
const [showRestore, setShowRestore] = useState(false);
const [claimPending, setClaimPending] = useState(false);
const [claimError, setClaimError] = useState<string | null>(null);
@@ -74,7 +74,7 @@ const appChildrenOptions = createChildrenOptions<App>({
export const appsSearchGroup = createGroup<App>({
keyPath: "id",
title: (t) => t("search.mode.appIntegrationBoard.group.app.title"),
title: (t) => t("common.entity.apps"),
Component: (app) => (
<Group px="md" py="sm">
<Avatar
@@ -125,7 +125,7 @@ const boardChildrenOptions = createChildrenOptions<Board>({
export const boardsSearchGroup = createGroup<Board>({
keyPath: "id",
title: "Boards",
title: (t) => t("common.entity.boards"),
Component: (board) => (
<Group px="md" py="sm">
{board.logoImageUrl ? (
@@ -9,7 +9,7 @@ import { interaction } from "../../lib/interaction";
export const integrationsSearchGroup = createGroup<{ id: string; kind: IntegrationKind; name: string }>({
keyPath: "id",
title: (t) => t("search.mode.appIntegrationBoard.group.integration.title"),
title: (t) => t("common.entity.integrations"),
Component: (integration) => (
<Group px="md" py="sm">
<IntegrationAvatar size="sm" kind={integration.kind} />
@@ -2,13 +2,13 @@ import type { ReactNode } from "react";
import { Center, Group, Loader, Stack, Text } from "@mantine/core";
import { IconCheck } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { interaction } from "../../../../lib/interaction";
export const PreferenceDetailHeader = ({ titleKey }: { titleKey: string }) => {
const tOption = useScopedI18n("search.mode.command.group.preferences.option");
const t = useScopedI18n("search.mode.command.group.preferences");
const tOption = useI18n("search.mode.command.group.preferences.option");
const t = useI18n("search.mode.command.group.preferences");
return (
<Stack mx="md" my="sm" gap="xs">
@@ -10,14 +10,18 @@ import { useSession } from "@homarr/auth/client";
import type { ColorScheme } from "@homarr/definitions";
import { visiblePreferenceDefinitions } from "@homarr/settings";
import { localeConfigurations } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { createChildrenOptions } from "../../../../lib/children";
import type { ChildrenAction } from "../../../../lib/children";
import { interaction } from "../../../../lib/interaction";
import { useUserPreferences } from "../../../../preferences/use-user-preference";
import { preferenceChildrenOptionsByKey, preferenceIcons } from "../../../../preferences/preference-registry";
import {
preferenceChildrenOptionsByKey,
preferenceIcons,
userFieldPreferenceLabels,
} from "../../../../preferences/preference-registry";
dayjs.extend(localeData);
@@ -65,8 +69,9 @@ const LinkRow = ({ label, Icon }: { label: string; Icon: TablerIcon }) => (
const SELECT_KINDS = new Set(["select", "searchEngine", "board"]);
const useSettingsActions = (_: Record<string, unknown>, query: string): SettingsAction[] => {
const t = useScopedI18n("search.mode.command.group.preferences.option");
const tColorScheme = useScopedI18n("common.colorScheme.options");
const t = useI18n("search.mode.command.group.preferences.option");
const tUserField = useI18n("user.field");
const tColorScheme = useI18n("common.colorScheme.options");
const { data: session } = useSession();
const isAuthenticated = Boolean(session?.user);
const normalizedQuery = query.trim().toLowerCase();
@@ -95,7 +100,8 @@ const useSettingsActions = (_: Record<string, unknown>, query: string): Settings
return visiblePreferenceDefinitions(isAuthenticated)
.map((definition): SettingsAction | null => {
const label = t(`${definition.key}.label` as never);
const userFieldKey = userFieldPreferenceLabels[definition.key];
const label = userFieldKey ? tUserField(`${userFieldKey}.label` as never) : t(`${definition.key}.label` as never);
const Icon = preferenceIcons[definition.key];
const matchesSearch = [label, ...definition.aliases].some((v) => v.toLowerCase().includes(normalizedQuery));
@@ -143,7 +149,7 @@ const useSettingsActions = (_: Record<string, unknown>, query: string): Settings
export const settingsChildrenOptions = createChildrenOptions<Record<string, unknown>>({
useActions: useSettingsActions,
DetailComponent: () => {
const t = useScopedI18n("search.mode.command.group.preferences");
const t = useI18n("search.mode.command.group.preferences");
return (
<Stack mx="md" my="sm" gap="xs">
<Text>{t("title")}</Text>
@@ -14,7 +14,7 @@ import { useSession } from "@homarr/auth/client";
import type { GroupPermissionKey } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals";
import { AddBoardModal, AddGroupModal, InviteCreateModal } from "@homarr/modals-collection";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { createGroup } from "../../lib/group";
@@ -48,7 +48,7 @@ export const globalCommandGroup = createGroup<Command>({
return option.name.toLowerCase().includes(query.toLowerCase());
},
useOptions() {
const tOption = useScopedI18n("search.mode.command.group.globalCommand.option");
const tOption = useI18n("search.mode.command.group.globalCommand.option");
const { data: session } = useSession();
const pathname = usePathname();
const router = useRouter();
@@ -10,7 +10,7 @@ import { getIntegrationKindsByCategory, getIntegrationName } from "@homarr/defin
import { useModalAction } from "@homarr/modals";
import { RequestMediaModal } from "@homarr/modals-collection";
import { useSettings } from "@homarr/settings";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { createChildrenOptions } from "../../lib/children";
import { createGroup } from "../../lib/group";
@@ -135,7 +135,7 @@ export const mediaRequestsChildrenOptions = createChildrenOptions<MediaRequestCh
(option.result.type === "movie" && option.result.inLibrary) ||
option.integration.permissions?.hasInteractAccess === false,
Component(option) {
const t = useScopedI18n("search.mode.media");
const t = useI18n("search.mode.media");
return (
<Group mx="md" my="sm" wrap="nowrap">
<IconDownload stroke={1.5} />
@@ -164,7 +164,7 @@ export const mediaRequestsChildrenOptions = createChildrenOptions<MediaRequestCh
{
key: "open",
Component({ integration }) {
const tChildren = useScopedI18n("search.mode.media");
const tChildren = useI18n("search.mode.media");
return (
<Group mx="md" my="sm" wrap="nowrap">
<IconSearch stroke={1.5} />
@@ -220,7 +220,7 @@ export const searchEnginesChildrenOptions = createChildrenOptions<SearchEngine>(
{
key: "search",
Component: ({ name }) => {
const tChildren = useScopedI18n("search.mode.external.group.searchEngine.children");
const tChildren = useI18n("search.mode.external.group.searchEngine.children");
return (
<Group mx="md" my="sm">
@@ -265,7 +265,7 @@ export const searchEnginesChildrenOptions = createChildrenOptions<SearchEngine>(
}));
},
DetailComponent({ options }) {
const tChildren = useScopedI18n("search.mode.external.group.searchEngine.children");
const tChildren = useI18n("search.mode.external.group.searchEngine.children");
return (
<Stack mx="md" my="sm">
<Text>{options.type === "generic" ? tChildren("detail.title") : tChildren("searchResults.title")}</Text>
@@ -298,7 +298,7 @@ const buildSearchUrl = (template: string, query: string) => {
export const searchEnginesSearchGroups = createGroup<ExternalOption>({
keyPath: "key",
title: (t) => t("search.mode.external.group.searchEngine.title"),
title: (t) => t("common.entity.searchEngines"),
Component: (option) => {
if (option.kind === "hint") {
return (
@@ -403,7 +403,7 @@ export const searchEnginesSearchGroups = createGroup<ExternalOption>({
return { type: "none" };
},
useQueryOptions(query) {
const tExternal = useScopedI18n("search.mode.external.group.searchEngine");
const tExternal = useI18n("search.mode.external.group.searchEngine");
const { ddgBangs } = useSettings();
const { bangToken, searchText, locked } = parseBangQuery(query);
const [debouncedBangToken] = useDebouncedValue(bangToken, 150);
@@ -10,7 +10,7 @@ import {
import { useSession } from "@homarr/auth/client";
import { createDocumentationLink } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { createGroup } from "../../lib/group";
@@ -33,7 +33,8 @@ type QuickLinkOption = {
export const useHomeEmptyGroups = () => {
const { data: session } = useSession();
const tPages = useScopedI18n("search.mode.page.group.page.option");
const tPages = useI18n("search.mode.page.group.page.option");
const tHelp = useI18n("management.navbar.items.help.items");
const visibleSearchModes: SearchMode[] = [appIntegrationBoardMode, externalMode, mediaMode, commandMode, pageMode];
if (session?.user.permissions.includes("admin")) {
@@ -88,7 +89,7 @@ export const useHomeEmptyGroups = () => {
title: (t) => t("search.mode.help.group.mode.title"),
options: visibleSearchModes.map(({ character, modeKey }) => ({ character, modeKey })),
Component: ({ modeKey, character }) => {
const t = useScopedI18n(`search.mode.${modeKey}`);
const t = useI18n(`search.mode.${modeKey}`);
return (
<Group px="md" py="xs" w="100%" wrap="nowrap" align="center" justify="space-between">
@@ -102,25 +103,23 @@ export const useHomeEmptyGroups = () => {
}),
createGroup({
keyPath: "href",
title: (t) => t("search.mode.help.group.help.title"),
title: (t) => t("management.navbar.items.help.label"),
useOptions() {
const t = useScopedI18n("search.mode.help.group.help.option");
return [
{
href: createDocumentationLink("/docs/getting-started"),
icon: IconBook2,
label: t("documentation.label"),
label: tHelp("documentation"),
},
{
href: "https://github.com/homarr-labs/homarr/issues/new/choose",
icon: IconBrandGithub,
label: t("submitIssue.label"),
label: tHelp("submitIssue"),
},
{
href: "https://discord.com/invite/aCsmEV5RgA",
icon: IconBrandDiscord,
label: t("discord.label"),
label: tHelp("discord"),
},
];
},
@@ -9,7 +9,7 @@ import { clientApi } from "@homarr/api/client";
import { getIntegrationName } from "@homarr/definitions";
import type { MediaAvailability } from "@homarr/integrations/types";
import { mediaAvailabilityConfiguration } from "@homarr/integrations/types";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { createGroup } from "../../lib/group";
import { mediaRequestSearchScopeAtom } from "../../spotlight-store";
@@ -37,7 +37,7 @@ export const mediaRequestSearchGroup = createGroup<MediaRequestSearchOption>({
keyPath: "key",
title: (t) => t("search.mode.media.group.title"),
Component(option) {
const tMedia = useScopedI18n("search.mode.media");
const tMedia = useI18n("search.mode.media");
if (option.kind !== "result") {
return (
@@ -96,7 +96,7 @@ export const mediaRequestSearchGroup = createGroup<MediaRequestSearchOption>({
return useMediaRequestSearchInteraction(option.result.integration, option.result);
},
useQueryOptions(query) {
const tMedia = useScopedI18n("search.mode.media");
const tMedia = useI18n("search.mode.media");
const scope = useAtomValue(mediaRequestSearchScopeAtom);
const [debouncedQuery] = useDebouncedValue(query.trim(), 150);
const targetsQuery = clientApi.integration.mediaRequestSearchTargets.useQuery();
@@ -17,7 +17,7 @@ import {
} from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { createGroup } from "../../lib/group";
@@ -59,7 +59,7 @@ export const pagesSearchGroup = createGroup<{
},
useOptions() {
const { data: session } = useSession();
const t = useScopedI18n("search.mode.page.group.page.option");
const t = useI18n("search.mode.page.group.page.option");
const managePages = [
{
@@ -3,14 +3,21 @@ import { IconSettings } from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import { colorSchemes } from "@homarr/definitions";
import type { UserPreferenceKey } from "@homarr/settings";
import { visiblePreferenceDefinitions } from "@homarr/settings";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { createGroup } from "../../lib/group";
import { preferenceChildrenOptionsByKey, preferenceIcons } from "../../preferences/preference-registry";
import {
preferenceChildrenOptionsByKey,
preferenceIcons,
userFieldPreferenceLabels,
} from "../../preferences/preference-registry";
import { settingsChildrenOptions } from "../command/children/preferences/settings-children";
type PreferencesGroupOption = { key: "settings"; preferenceKey: null } | { key: string; preferenceKey: string };
type PreferencesGroupOption =
| { key: "settings"; preferenceKey: null }
| { key: UserPreferenceKey; preferenceKey: UserPreferenceKey };
const settingsOption: PreferencesGroupOption = { key: "settings", preferenceKey: null };
@@ -19,7 +26,8 @@ export const preferencesGroup = createGroup<PreferencesGroupOption>({
title: (t) => t("search.mode.command.group.preferences.title"),
useOptions(query) {
const t = useI18n();
const tColorScheme = useScopedI18n("common.colorScheme.options");
const tColorScheme = useI18n("common.colorScheme.options");
const tUserField = useI18n("user.field");
const { data: session } = useSession();
const definitions = visiblePreferenceDefinitions(Boolean(session?.user));
const q = query.trim().toLowerCase();
@@ -28,7 +36,10 @@ export const preferencesGroup = createGroup<PreferencesGroupOption>({
const matching = definitions.flatMap((def): PreferencesGroupOption[] => {
if (!preferenceChildrenOptionsByKey[def.key]) return [];
const label = t(`search.mode.command.group.preferences.option.${def.key}.label` as never);
const userFieldKey = userFieldPreferenceLabels[def.key];
const label = userFieldKey
? tUserField(`${userFieldKey}.label` as never)
: t(`search.mode.command.group.preferences.option.${def.key}.label` as never);
const searchValues = [
label,
...def.aliases,
@@ -47,12 +58,19 @@ export const preferencesGroup = createGroup<PreferencesGroupOption>({
return allSearchValues.some((v) => v.toLowerCase().includes(q)) ? [settingsOption] : [];
},
Component: (option) => {
const t = useScopedI18n("search.mode.command.group.preferences");
const tOption = useScopedI18n("search.mode.command.group.preferences.option");
const t = useI18n("search.mode.command.group.preferences");
const tOption = useI18n("search.mode.command.group.preferences.option");
const tUserField = useI18n("user.field");
const Icon = option.preferenceKey
? preferenceIcons[option.preferenceKey as keyof typeof preferenceIcons]
: IconSettings;
const label = option.preferenceKey ? tOption(`${option.preferenceKey}.label` as never) : t("title");
let label = t("title");
if (option.preferenceKey) {
const userFieldKey = userFieldPreferenceLabels[option.preferenceKey];
label = userFieldKey
? tUserField(`${userFieldKey}.label` as never)
: tOption(`${option.preferenceKey}.label` as never);
}
return (
<Group px="md" py="sm" wrap="nowrap" gap="sm">
@@ -70,7 +70,7 @@ const groupChildrenOptions = createChildrenOptions<Group>({
export const groupsSearchGroup = createGroup<Group>({
keyPath: "id",
title: "Groups",
title: (t) => t("common.entity.groups"),
Component: ({ name }) => (
<Group px="md" py="sm">
<Text>{name}</Text>
@@ -48,7 +48,7 @@ const userChildrenOptions = createChildrenOptions<User>({
export const usersSearchGroup = createGroup<User>({
keyPath: "id",
title: (t) => t("search.mode.userGroup.group.user.title"),
title: (t) => t("common.entity.users"),
Component: (user) => (
<Group px="md" py="sm">
<UserAvatar user={user} size="sm" />
@@ -20,7 +20,7 @@ import localeData from "dayjs/plugin/localeData";
import { clientApi } from "@homarr/api/client";
import { colorSchemes } from "@homarr/definitions";
import type { UserPreferenceKey } from "@homarr/settings";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { createChildrenOptions } from "../lib/children";
@@ -37,6 +37,21 @@ dayjs.extend(localeData);
type ChildrenFactory = ReturnType<typeof createChildrenOptions<Record<string, unknown>>>;
export type UserFieldPreferenceKey =
| "defaultSearchEngine"
| "openSearchInNewTab"
| "ddgBangs"
| "pingIconsEnabled"
| "enableRightClickOnWidgets";
export const userFieldPreferenceLabels: Partial<Record<UserPreferenceKey, UserFieldPreferenceKey>> = {
defaultSearchEngineId: "defaultSearchEngine",
openSearchInNewTab: "openSearchInNewTab",
ddgBangs: "ddgBangs",
pingIconsEnabled: "pingIconsEnabled",
enableRightClickOnWidgets: "enableRightClickOnWidgets",
} satisfies Partial<Record<UserPreferenceKey, UserFieldPreferenceKey>>;
export const preferenceIcons: Record<UserPreferenceKey, TablerIcon> = {
colorScheme: IconDeviceDesktop,
locale: IconLanguage,
@@ -82,7 +97,7 @@ const createAsyncSelectableChildren = <TItem,>(
useActions: (_, query) => {
const { value, setValue, isPending } = useUserPreference(preferenceKey);
const result = useQuery();
const t = useScopedI18n("search.mode.command.group.preferences.option");
const t = useI18n("search.mode.command.group.preferences.option");
if (result.isLoading) return [createLoadingPreferenceAction()];
@@ -103,7 +118,7 @@ const firstDayOfWeekOptions: DayOfWeek[] = [1, 6, 0];
export const preferenceChildrenOptionsByKey: Partial<Record<UserPreferenceKey, ChildrenFactory>> = {
colorScheme: createStaticChildren("colorScheme", () => {
const t = useScopedI18n("common.colorScheme.options");
const t = useI18n("common.colorScheme.options");
return colorSchemes.map((s) => ({ key: s, label: t(s), value: s }));
}),
locale: languageChildrenOptions,
-3
View File
@@ -18,7 +18,4 @@ declare module "next-intl" {
// Keep these as direct exports so Turbopack and webpack can statically inspect
// the client package's public surface.
export const useI18n = useTranslations;
export const useScopedI18n = useTranslations;
export const useI18nMessages = () => useMessages();
export { useTranslations };
File diff suppressed because it is too large. Load diff
+1 -4
View File
@@ -10,9 +10,6 @@ declare module "next-intl" {
}
}
export const { getI18n, getScopedI18n } = {
getI18n: getTranslations,
getScopedI18n: getTranslations,
};
export const getI18n = getTranslations;
export { getMessages as getI18nMessages } from "next-intl/server";
+2 -2
View File
@@ -2,13 +2,13 @@ import type { NamespaceKeys, NestedKeyOf } from "next-intl";
import type { RemoveReadonly } from "@homarr/common/types";
import type { useI18n, useScopedI18n } from "./client";
import type { useI18n } from "./client";
import type enTranslation from "./lang/en.json";
export type TranslationFunction = ReturnType<typeof useI18n<never>>;
export type ScopedTranslationFunction<
NestedKey extends NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>> = never,
> = ReturnType<typeof useScopedI18n<NestedKey>>;
> = ReturnType<typeof useI18n<NestedKey>>;
export type TranslationObject = typeof enTranslation;
export type stringOrTranslation = string | ((t: TranslationFunction) => string);
+3 -3
View File
@@ -3,17 +3,17 @@
import type { BadgeProps } from "@mantine/core";
import { Badge } from "@mantine/core";
import { useTranslations } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
interface BetaBadgeProps {
size: BadgeProps["size"];
}
export const BetaBadge = ({ size }: BetaBadgeProps) => {
const t = useTranslations();
const t = useI18n("common");
return (
<Badge size={size} color="green" variant="outline">
{t("common.beta")}
{t("beta")}
</Badge>
);
};
@@ -6,7 +6,7 @@ import { IconCheck, IconDeviceDesktop, IconMoon, IconSun } from "@tabler/icons-r
import type { ColorScheme } from "@homarr/definitions";
import { colorSchemes } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
const schemeIcons: Record<ColorScheme, React.ElementType> = {
auto: IconDeviceDesktop,
@@ -22,7 +22,7 @@ interface ColorSchemeComboboxProps {
}
export const ColorSchemeCombobox = ({ label, value, onChange, width }: ColorSchemeComboboxProps) => {
const tOptions = useScopedI18n("common.colorScheme.options");
const tOptions = useI18n("common.colorScheme.options");
const combobox = useCombobox({ onDropdownClose: () => combobox.resetSelectedOption() });
return (
@@ -2,7 +2,7 @@ import type { PropsWithChildren } from "react";
import { useState } from "react";
import { Popover, Progress, Text } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { passwordRequirements } from "@homarr/validation/user";
import { PasswordRequirement } from "./password-requirement";
@@ -14,7 +14,7 @@ const strengthColorMap = [
] as const;
export const PasswordRequirementsPopover = ({ password, children }: PropsWithChildren<{ password: string }>) => {
const tPassword = useScopedI18n("user.field.password");
const tPassword = useI18n("user.field.password");
const requirements = useRequirements();
const strength = useStrength(password);
const [popoverOpened, setPopoverOpened] = useState(false);
@@ -46,7 +46,7 @@ export const PasswordRequirementsPopover = ({ password, children }: PropsWithChi
};
const useRequirements = () => {
const t = useScopedI18n("user.field.password.suggestion");
const t = useI18n("user.field.password.suggestion");
return passwordRequirements.map(({ check, value }) => ({ check, label: t(value) }));
};
@@ -4,6 +4,7 @@ import { useCallback, useMemo, useState } from "react";
import { Badge, Card, Center, Group, Stack, Text, Tooltip, UnstyledButton } from "@mantine/core";
import { IconBrandDocker, IconCheck, IconPuzzle } from "@tabler/icons-react";
import { getWidgetName } from "@homarr/definitions";
import type { IntegrationKind } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
@@ -109,7 +110,7 @@ export const IntegrationMultiSelectGrid = ({
<Stack gap={4}>
{integration.widgets.map((widgetKind) => (
<Text key={widgetKind} size="xs">
{t(`widget.${widgetKind}.name`)}
{getWidgetName(widgetKind, t)}
</Text>
))}
</Stack>
@@ -42,6 +42,7 @@ import {
IconZoomQuestion,
} from "@tabler/icons-react";
import { getWidgetName } from "@homarr/definitions";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
@@ -219,7 +220,7 @@ const IntegrationTiedWidgets = ({ widgets, limit }: { widgets: WidgetKind[]; lim
leftSection={<WidgetIcon size={12} />}
style={{ fontWeight: 500 }}
>
{t(`widget.${widgetKind}.name`)}
{getWidgetName(widgetKind, t)}
</Badge>
);
})}
+1
View File
@@ -25,6 +25,7 @@
"./errors": "./src/errors/component.tsx",
"./manifest": "./src/manifest.ts",
"./options": "./src/options.ts",
"./option-translation": "./src/option-translation.ts",
"./errors/classes": "./src/errors/index.ts",
"./widget-integration-select": "./src/widget-integration-select.tsx",
"./modals": "./src/modals/index.ts",
+17 -3
View File
@@ -1,7 +1,11 @@
import type { WidgetKind } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { WidgetOptionOfType, WidgetOptionType } from "../options";
import {
getWidgetOptionDescriptionTranslationNamespace,
getWidgetOptionTranslationNamespace,
} from "../option-translation";
export interface CommonWidgetInputProps<TKey extends WidgetOptionType> {
kind: WidgetKind;
@@ -25,7 +29,17 @@ type UseWidgetInputTranslationReturnType = (key: "label" | "description" | "plac
* is defined for the option. The method does sadly not reconize issues with those definitions. So it does not yell at you when you somewhere show the label without having it defined in the translations.
*/
export const useWidgetInputTranslation = (kind: WidgetKind, property: string): UseWidgetInputTranslationReturnType => {
return useScopedI18n(
`widget.${kind}.option.${property}` as never, // Because the type is complex and not recognized by typescript, we need to cast it to never to make it work.
const inputNamespace = getWidgetOptionTranslationNamespace(kind, property);
const descriptionNamespace = getWidgetOptionDescriptionTranslationNamespace(kind, property);
const tInput = useI18n(
inputNamespace as never, // Because the type is complex and not recognized by typescript, we need to cast it to never to make it work.
) as unknown as UseWidgetInputTranslationReturnType;
const tDescription = useI18n(
(descriptionNamespace ?? inputNamespace) as never,
) as unknown as UseWidgetInputTranslationReturnType;
return (key) => {
if (key === "description" && descriptionNamespace) return tDescription("description");
return tInput(key);
};
};
@@ -5,16 +5,16 @@ import { Loader, Select } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import { clientApi } from "@homarr/api/client";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
export const WidgetAnchorNoteInput = ({ property, kind, options }: CommonWidgetInputProps<"anchorNote">) => {
const t = useI18n();
const tCommon = useI18n("common");
const tWidget = useWidgetInputTranslation(kind, property);
const tAnchor = useScopedI18n("widget.anchorNote");
const tAnchor = useI18n("widget.anchorNote");
const form = useFormContext();
const integrationId = form.values.integrationIds[0];
@@ -46,7 +46,7 @@ export const WidgetAnchorNoteInput = ({ property, kind, options }: CommonWidgetI
<Select
label={tWidget("label")}
description={options.withDescription ? tWidget("description") : undefined}
placeholder={integrationId ? t("common.select.placeholder") : tAnchor("integrationRequired")}
placeholder={integrationId ? tCommon("select.placeholder") : tAnchor("integrationRequired")}
nothingFoundMessage={integrationId ? tAnchor("noNotes") : tAnchor("integrationRequired")}
searchable
searchValue={search}
@@ -24,7 +24,8 @@ const renderHereLink = (children: React.ReactNode) => (
);
export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">) => {
const t = useI18n();
const tCommon = useI18n("common");
const tApp = useI18n("widget.common.app");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const { data: apps, isPending, refetch } = clientApi.app.selectable.useQuery();
@@ -44,7 +45,7 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
label={tInput("label")}
searchable
leftSection={<MemoizedLeftSection isPending={isPending} currentApp={currentApp} />}
nothingFoundMessage={t("widget.common.app.noData")}
nothingFoundMessage={tApp("noData")}
renderOption={renderSelectOption}
data={
apps?.map((app) => ({
@@ -56,8 +57,8 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
inputWrapperOrder={["label", "input", "description", "error"]}
description={
<Text component="span" size="xs">
{t.rich("widget.common.app.description", {
here: renderHereLink,
{tApp.rich("description", {
here: () => renderHereLink(tCommon("here")),
})}
</Text>
}
@@ -79,7 +80,7 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
})
}
>
{t("widget.common.app.quickCreate")}
{tApp("quickCreate")}
</Button>
)}
</SimpleGrid>
@@ -25,7 +25,7 @@ import { normalizeCustomWidgetOptions, validateCustomWidgetOptions } from "@homa
import { CustomWidgetCodeEditor } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetEditorMessages } from "@homarr/custom-widgets/workbench";
import { IconPicker } from "@homarr/forms-collection";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useFormContext } from "./form";
@@ -34,7 +34,7 @@ export const WidgetCustomWidgetConfigurationInput = ({
property,
}: CommonWidgetInputProps<"customWidgetConfiguration">) => {
const form = useFormContext();
const labels = useScopedI18n("widget.customApi.configuration");
const labels = useI18n("widget.customApi.configuration");
const board = useOptionalBoard();
const definitionId = typeof form.values.options.definitionId === "string" ? form.values.options.definitionId : "";
const configurationValue = form.values.options[property];
@@ -72,7 +72,7 @@ vi.mock("@homarr/boards/context", () => ({
}));
vi.mock("@homarr/translation/client", () => ({
useScopedI18n: () => (key: string) =>
useI18n: () => (key: string) =>
({
migrationRequired: "Migration required",
migrationDescription: "Copy its redacted prompt to an LLM, then paste the single JSON response into Homarr.",
@@ -19,7 +19,7 @@ import { IconAlertTriangle, IconApi } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useOptionalBoard } from "@homarr/boards/context";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import type { CommonWidgetInputProps } from "./common";
@@ -32,7 +32,7 @@ export const WidgetCustomWidgetSelectInput = ({
options,
}: CommonWidgetInputProps<"customWidgetSelect">) => {
const t = useWidgetInputTranslation(kind, property);
const labels = useScopedI18n("widget.customApi.picker");
const labels = useI18n("widget.customApi.picker");
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const form = useFormContext();
@@ -24,7 +24,7 @@ import dayjs from "dayjs";
import { createId } from "@homarr/common";
import type { WidgetKind } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { formatWallDateTime, resolveWallDateTimeString } from "../countdown/recurrence";
import type { DateTimeEventRecurrence, OptionDateTimeEvent } from "../options";
@@ -314,4 +314,4 @@ type EventListTranslationKey =
type EventListTranslation = (key: EventListTranslationKey, values?: Record<string, string | number>) => string;
const useEventListTranslation = (kind: WidgetKind) =>
useScopedI18n(`widget.${kind}.dateTimeEventList` as never) as unknown as EventListTranslation;
useI18n(`widget.${kind}.dateTimeEventList` as never) as unknown as EventListTranslation;
@@ -2,7 +2,7 @@
import { Loader, MultiSelect } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
@@ -13,7 +13,8 @@ export const WidgetDynamicMultiSelectInput = ({
kind,
options,
}: CommonWidgetInputProps<"dynamicMultiSelect">) => {
const t = useScopedI18n("widget.dynamicSelect");
const t = useI18n("widget.common.select");
const tCommon = useI18n("common");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const inputProps = form.getInputProps(`options.${property}`);
@@ -36,7 +37,7 @@ export const WidgetDynamicMultiSelectInput = ({
searchable
clearable
maxValues={options.maxValues}
nothingFoundMessage={t("noResults")}
nothingFoundMessage={tCommon("noResults")}
data={data}
disabled={isError}
error={isError ? t("loadError") : inputProps.error}
@@ -6,7 +6,7 @@ import { useDebouncedValue } from "@mantine/hooks";
import { IconCheck } from "@tabler/icons-react";
import { translateIfNecessary } from "@homarr/translation";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
@@ -25,7 +25,7 @@ export const WidgetDynamicSelectInput = ({
boardId,
}: CommonWidgetInputProps<"dynamicSelect">) => {
const t = useI18n();
const tSelect = useScopedI18n("widget.dynamicSelect");
const tCommon = useI18n("common");
const tWidget = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const inputProps = form.getInputProps(`options.${property}`);
@@ -78,7 +78,7 @@ export const WidgetDynamicSelectInput = ({
searchValue={search}
onSearchChange={setSearch}
placeholder={tWidget("placeholder")}
nothingFoundMessage={tSelect("noResults")}
nothingFoundMessage={tCommon("noResults")}
leftSection={isPending && <Loader size="xs" />}
renderOption={({ option, checked }) => {
return (
@@ -2,20 +2,20 @@
import { MultiSelect, Text } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
const useIntegrationSelectTranslation = () => useScopedI18n("widget.integrationSelect");
export const WidgetIntegrationMultiSelectInput = ({
property,
kind,
options,
}: CommonWidgetInputProps<"integrationMultiSelect">) => {
const t = useIntegrationSelectTranslation();
const t = useI18n("widget.integrationSelect");
const tSelect = useI18n("widget.common.select");
const tCommon = useI18n("common");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
@@ -40,8 +40,8 @@ export const WidgetIntegrationMultiSelectInput = ({
}
const description = options.withDescription ? tInput("description") : undefined;
const placeholder = isPending ? t("loading") : tInput("placeholder");
const loadError = isError ? t("loadError") : undefined;
const placeholder = isPending ? tSelect("loading") : tInput("placeholder");
const loadError = isError ? tSelect("loadError") : undefined;
return (
<MultiSelect
@@ -51,7 +51,7 @@ export const WidgetIntegrationMultiSelectInput = ({
placeholder={placeholder}
searchable
clearable
nothingFoundMessage={t("noResults")}
nothingFoundMessage={tCommon("noResults")}
data={data}
disabled={isError}
error={loadError ?? inputProps.error}
@@ -2,20 +2,20 @@
import { Select, Text } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
const useIntegrationSelectTranslation = () => useScopedI18n("widget.integrationSelect");
export const WidgetIntegrationSelectInput = ({
property,
kind,
options,
}: CommonWidgetInputProps<"integrationSelect">) => {
const t = useIntegrationSelectTranslation();
const t = useI18n("widget.integrationSelect");
const tSelect = useI18n("widget.common.select");
const tCommon = useI18n("common");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
@@ -35,8 +35,8 @@ export const WidgetIntegrationSelectInput = ({
}
const description = options.withDescription ? tInput("description") : undefined;
const placeholder = isPending ? t("loading") : t("placeholder");
const error = isError ? t("loadError") : undefined;
const placeholder = isPending ? tSelect("loading") : t("placeholder");
const error = isError ? tSelect("loadError") : undefined;
return (
<Select
@@ -45,7 +45,7 @@ export const WidgetIntegrationSelectInput = ({
placeholder={placeholder}
clearable={options.clearable}
searchable={options.searchable}
nothingFoundMessage={t("noResults")}
nothingFoundMessage={tCommon("noResults")}
data={data}
disabled={isError}
error={error}
@@ -46,7 +46,7 @@ vi.mock("@homarr/modals", () => ({
vi.mock("@homarr/translation/client", () => ({
useCurrentIntlLocale: () => "en",
useScopedI18n: () => (key: string) => key,
useI18n: () => (key: string) => key,
}));
vi.mock("./common", async (importOriginal) => ({
@@ -21,7 +21,7 @@ import { IconClick, IconListSearch } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { createModal, useModalAction } from "@homarr/modals";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { formatLocalizedCompactNumber } from "../common/locale";
import type { OptionLocation } from "../options";
@@ -31,7 +31,7 @@ import { useFormContext } from "./form";
export const WidgetLocationInput = ({ property, kind, options }: CommonWidgetInputProps<"location">) => {
const t = useWidgetInputTranslation(kind, property);
const tLocation = useScopedI18n("widget.common.location");
const tLocation = useI18n("widget.common.location");
const form = useFormContext();
const { openModal } = useModalAction(LocationSearchModal);
const fieldPath = `options.${property}`;
@@ -149,8 +149,8 @@ interface LocationSearchInnerProps {
}
const LocationSearchModal = createModal<LocationSearchInnerProps>(({ actions, innerProps }) => {
const t = useScopedI18n("widget.common.location.table");
const tCommon = useScopedI18n("common");
const t = useI18n("widget.common.location.table");
const tCommon = useI18n("common");
const { data, isPending, error } = clientApi.location.searchCity.useQuery({
query: innerProps.query,
});
@@ -216,7 +216,7 @@ interface LocationSearchTableRowProps {
}
const LocationSelectTableRow = ({ city, onLocationSelect, closeModal }: LocationSearchTableRowProps) => {
const t = useScopedI18n("widget.common.location.table");
const t = useI18n("widget.common.location.table");
const locale = useCurrentIntlLocale();
const onSelect = useCallback(() => {
onLocationSelect({
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react";
import { Combobox, Pill, PillsInput, useCombobox } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
@@ -9,7 +9,7 @@ import { useFormContext } from "./form";
export const WidgetMultiTextInput = ({ property, kind, options }: CommonWidgetInputProps<"multiText">) => {
const t = useWidgetInputTranslation(kind, property);
const tCommon = useScopedI18n("common");
const tCommon = useI18n("common");
const combobox = useCombobox({
onDropdownClose: () => combobox.resetSelectedOption(),
onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"),
@@ -48,7 +48,7 @@ import {
import { IconPicker } from "@homarr/forms-collection";
import { createModal, useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { MaskedImage } from "@homarr/ui";
import type { ReleasesRepository, ReleasesVersionFilter } from "../releases/releases-repository";
@@ -69,7 +69,8 @@ export const WidgetMultiReleasesRepositoriesInput = ({
itemId,
}: CommonWidgetInputProps<"multiReleasesRepositories">) => {
const t = useWidgetInputTranslation(kind, property);
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const actionT = useI18n("common.action");
const form = useFormContext();
const repositories = form.values.options[property] as ReleasesRepository[];
const { openModal: openEditModal } = useModalAction(RepositoryEditModal);
@@ -232,7 +233,7 @@ export const WidgetMultiReleasesRepositoriesInput = ({
leftSection={<IconEdit size="var(--mantine-font-size-sm)" />}
size="xs"
>
{tRepository("edit.label")}
{actionT("edit")}
</Button>
<ActionIcon variant="transparent" color="red" onClick={() => onRepositoryRemove(index)}>
@@ -267,7 +268,7 @@ const providersWithAuth: ReleaseProviderKind[] = [
];
const ProviderTokensSection = ({ itemId, repositories }: { itemId: string; repositories: ReleasesRepository[] }) => {
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const { data: configuredKinds = [], refetch } = clientApi.widget.secrets.getConfiguredKinds.useQuery({ itemId });
const setSecret = clientApi.widget.secrets.setSecret.useMutation({
onSuccess: () => refetch(),
@@ -331,7 +332,8 @@ const ProviderTokenInput = ({
onSave: (value: string) => Promise<void>;
onDelete: () => Promise<void>;
}) => {
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const actionT = useI18n("common.action");
const [value, setValue] = useState("");
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
@@ -375,7 +377,7 @@ const ProviderTokenInput = ({
/>
{editing && value.trim() && (
<Button size="xs" onClick={handleSave} loading={saving}>
{tRepository("tokens.save")}
{actionT("save")}
</Button>
)}
{hasToken && !editing && (
@@ -412,7 +414,8 @@ interface RepositoryEditProps {
}
const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, actions }) => {
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const actionT = useI18n("common.action");
const [loading, setLoading] = useState(false);
const [tempRepository, setTempRepository] = useState(() => ({ ...innerProps.repository }));
const [formErrors, setFormErrors] = useState<FormErrors>({});
@@ -576,11 +579,11 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
<Divider my={"sm"} />
<Group justify="flex-end">
<Button variant="default" onClick={handleCancel} color="gray.5">
{tRepository("editForm.cancel.label")}
{actionT("cancel")}
</Button>
<Button data-autofocus onClick={handleConfirm} loading={loading}>
{tRepository("editForm.confirm.label")}
{actionT("confirm")}
</Button>
</Group>
</Stack>
@@ -611,7 +614,7 @@ const ImportRepositorySelect = ({
disabled = false,
onImageSelectionChanged = undefined,
}: ImportRepositorySelectProps) => {
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const provider = repository.provider;
return (
@@ -687,7 +690,8 @@ interface RepositoryImportProps {
}
const RepositoryImportModal = createModal<RepositoryImportProps>(({ innerProps, actions }) => {
const tRepository = useScopedI18n("widget.releases.option.repositories");
const tRepository = useI18n("widget.releases.option.repositories");
const actionT = useI18n("common.action");
const [loading, setLoading] = useState(false);
const [selectedImages, setSelectedImages] = useState([] as ReleasesRepositoryImport[]);
@@ -847,11 +851,11 @@ const RepositoryImportModal = createModal<RepositoryImportProps>(({ innerProps,
<Group justify="flex-end">
<Button variant="default" onClick={actions.closeModal} color="gray.5">
{tRepository("editForm.cancel.label")}
{actionT("cancel")}
</Button>
<Button onClick={handleConfirm} loading={loading} disabled={selectedImages.length === 0}>
{tRepository("editForm.confirm.label")}
{actionT("confirm")}
</Button>
</Group>
</Stack>
@@ -22,7 +22,7 @@ import { IconGripVertical, IconPlus, IconTrash } from "@tabler/icons-react";
import { createId } from "@homarr/common";
import type { WidgetKind } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { OptionTimezone } from "../options";
import type { CommonWidgetInputProps } from "./common";
@@ -246,4 +246,4 @@ type TimezoneListTranslationKey =
type TimezoneListTranslation = (key: TimezoneListTranslationKey, values?: Record<string, string | number>) => string;
const useTimezoneListTranslation = (kind: WidgetKind) =>
useScopedI18n(`widget.${kind}.timezoneList` as never) as unknown as TimezoneListTranslation;
useI18n(`widget.${kind}.timezoneList` as never) as unknown as TimezoneListTranslation;
@@ -3,14 +3,15 @@
import { Select, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
export const WidgetUmamiEventInput = ({ property, kind }: CommonWidgetInputProps<"umamiEventName">) => {
const t = useScopedI18n("widget.umami.option.eventName");
const t = useI18n("widget.umami.option.eventName");
const tEvents = useI18n("widget.umami.option.events");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
@@ -25,7 +26,7 @@ export const WidgetUmamiEventInput = ({ property, kind }: CommonWidgetInputProps
if (!websiteId || integrationIds.length === 0) {
return (
<Text size="sm" c="dimmed">
{t("configureWebsiteFirst")}
{tEvents("configureWebsiteFirst")}
</Text>
);
}
@@ -36,9 +37,9 @@ export const WidgetUmamiEventInput = ({ property, kind }: CommonWidgetInputProps
<Select
label={tInput("label")}
description={tInput("description")}
placeholder={isPending ? t("loading") : undefined}
placeholder={isPending ? tEvents("loading") : undefined}
searchable
nothingFoundMessage={t("noEvents")}
nothingFoundMessage={tEvents("noEvents")}
data={data}
{...form.getInputProps(`options.${property}`)}
/>
@@ -3,14 +3,15 @@
import { MultiSelect, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
export const WidgetUmamiEventNamesInput = ({ property, kind }: CommonWidgetInputProps<"umamiEventNames">) => {
const t = useScopedI18n("widget.umami.option.eventNames");
const t = useI18n("widget.umami.option.eventNames");
const tEvents = useI18n("widget.umami.option.events");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
@@ -25,7 +26,7 @@ export const WidgetUmamiEventNamesInput = ({ property, kind }: CommonWidgetInput
if (!websiteId || integrationIds.length === 0) {
return (
<Text size="sm" c="dimmed">
{t("configureWebsiteFirst")}
{tEvents("configureWebsiteFirst")}
</Text>
);
}
@@ -34,9 +35,9 @@ export const WidgetUmamiEventNamesInput = ({ property, kind }: CommonWidgetInput
<MultiSelect
label={tInput("label")}
description={tInput("description")}
placeholder={isPending ? t("loading") : t("placeholder")}
placeholder={isPending ? tEvents("loading") : t("placeholder")}
searchable
nothingFoundMessage={t("noEvents")}
nothingFoundMessage={tEvents("noEvents")}
data={eventNames ?? []}
{...form.getInputProps(`options.${property}`)}
/>
@@ -3,14 +3,14 @@
import { Select, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
export const WidgetUmamiWebsiteInput = ({ property, kind }: CommonWidgetInputProps<"umamiWebsite">) => {
const t = useScopedI18n("widget.umami.option.websiteId");
const t = useI18n("widget.umami.option.websiteId");
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
@@ -6,7 +6,7 @@ import { Box, Group, Paper, ScrollArea, SimpleGrid, Stack, Text, VisuallyHidden
import { IconMapPin } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state";
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
@@ -28,7 +28,7 @@ import {
} from "./display";
export default function AirQualityWidget({ options, width, height, displayMode }: WidgetComponentProps<"airQuality">) {
const t = useScopedI18n("widget.airQuality");
const t = useI18n("widget.airQuality");
const query = clientApi.widget.airQuality.atLocation.useQuery({
latitude: options.location.latitude,
longitude: options.location.longitude,
@@ -66,7 +66,7 @@ const CompactAirQuality = ({
width,
}: AirQualityViewProps & { height: number; width: number }) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.airQuality");
const t = useI18n("widget.airQuality");
const layout = getCompactAirQualityLayout(width, height);
const standard = getAqiStandard(options.aqiStandard, locale);
const value = getAqiValue(airQuality.current, standard);
@@ -158,7 +158,7 @@ const CompactAirQuality = ({
const AdvancedAirQuality = ({ airQuality, options, width }: AirQualityViewProps & { width: number }) => {
const chartId = useId();
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.airQuality");
const t = useI18n("widget.airQuality");
const standard = getAqiStandard(options.aqiStandard, locale);
const value = getAqiValue(airQuality.current, standard);
const category = getAqiCategory(value, standard);
@@ -358,7 +358,7 @@ const pollutantKeys: PollutantKey[] = ["pm2_5", "pm10", "ozone", "nitrogenDioxid
const pollenKeys: PollenKey[] = ["alder", "birch", "grass", "mugwort", "olive", "ragweed"];
const useAirQualityLabels = () => {
const t = useScopedI18n("widget.airQuality");
const t = useI18n("widget.airQuality");
return {
pollutants: {
pm2_5: t("pollutant.pm2_5"),
@@ -389,7 +389,7 @@ const formatDecimal = (value: number | null, locale: string) => {
return new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(value);
};
type ScopedAirQualityTranslator = ReturnType<typeof useScopedI18n<"widget.airQuality">>;
type ScopedAirQualityTranslator = ReturnType<typeof useI18n<"widget.airQuality">>;
const formatConcentration = (value: number | null, locale: string, t: ScopedAirQualityTranslator) =>
t("unit.concentration", { value: formatDecimal(value, locale) });
+11 -9
View File
@@ -9,7 +9,7 @@ import { clientApi } from "@homarr/api/client";
import { useIntegrationsWithInteractAccess } from "@homarr/auth/client";
import { useTimeAgo } from "@homarr/common";
import type { AnchorNotePermission } from "@homarr/integrations";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state";
import type { WidgetComponentProps } from "../definition";
@@ -42,7 +42,7 @@ export default function AnchorNoteWidget({
height,
displayMode,
}: WidgetComponentProps<"anchorNote">) {
const t = useScopedI18n("widget.anchorNote");
const t = useI18n("widget.anchorNote");
const noteId = options.noteId.trim();
if (!noteId) {
return (
@@ -85,7 +85,9 @@ const AnchorNoteWidgetContent = ({
height,
isAdvanced,
}: AnchorNoteWidgetContentProps) => {
const t = useScopedI18n("widget.anchorNote");
const t = useI18n("widget.anchorNote");
const tWidgetCommon = useI18n("widget.common");
const actionT = useI18n("common.action");
const locale = useCurrentIntlLocale();
const noteQuery = clientApi.widget.anchorNotes.getNote.useQuery({
integrationId,
@@ -206,7 +208,7 @@ const AnchorNoteWidgetContent = ({
)}
{!isEditing && (isAdvanced || options.showUpdatedAt) && (
<Text size="xs" c="dimmed">
{t("updatedAt", { date: updatedAtRelative })}
{tWidgetCommon("updatedAt", { date: updatedAtRelative })}
</Text>
)}
{!isEditing && isViewer && (
@@ -243,21 +245,21 @@ const AnchorNoteWidgetContent = ({
{isEditing ? (
<>
<Button size="xs" onClick={handleSave} loading={isUpdating} disabled={!hasChanges || !canEdit}>
{t("save")}
{actionT("save")}
</Button>
<Button size="xs" variant="subtle" onClick={handleCancel} disabled={isUpdating}>
{t("cancel")}
{actionT("cancel")}
</Button>
</>
) : isAdvanced ? (
<Button size="xs" variant="light" onClick={handleEdit} disabled={isUpdating}>
{t("edit")}
{actionT("edit")}
</Button>
) : (
<Tooltip label={t("edit")}>
<Tooltip label={actionT("edit")}>
<ActionIcon
className={actionTargetClasses.root}
aria-label={t("edit")}
aria-label={actionT("edit")}
size="md"
variant="light"
onClick={handleEdit}
+4 -3
View File
@@ -23,7 +23,8 @@ import { PingDot } from "./ping/ping-dot";
import { PingIndicator } from "./ping/ping-indicator";
export default function AppWidget({ options, isEditMode, height, width }: WidgetComponentProps<"app">) {
const t = useI18n();
const tCommon = useI18n("common");
const tApp = useI18n("widget.app");
const settings = useSettings();
const board = useRequiredBoard();
const appQuery = clientApi.app.byId.useQuery({ id: options.appId }, { enabled: Boolean(options.appId) });
@@ -121,14 +122,14 @@ export default function AppWidget({ options, isEditMode, height, width }: Widget
!settings.forceDisableStatus &&
!board.disableStatus &&
Boolean(app.pingUrl ?? app.href) ? (
<Suspense fallback={<PingDot icon={IconMinus} color="gray" tooltip={`${t("common.action.loading")}…`} />}>
<Suspense fallback={<PingDot icon={IconMinus} color="gray" tooltip={`${tCommon("action.loading")}…`} />}>
<PingIndicator appId={app.id} />
</Suspense>
) : null}
</AppLink>
{appQuery.error && (
<Box pos="absolute" top={4} right={4}>
<WidgetQueryErrorIndicator error={appQuery.error} label={t("widget.app.name")} />
<WidgetQueryErrorIndicator error={appQuery.error} label={tApp("name")} />
</Box>
)}
</Box>
+2 -2
View File
@@ -55,7 +55,7 @@ export const { definition, componentLoader } = createWidgetDefinition("app", {
options: [
{
label(t) {
return t("widget.app.option.layout.option.column");
return t("widget.common.layout.option.vertical");
},
value: "column",
icon: IconLayoutNavbarExpand,
@@ -69,7 +69,7 @@ export const { definition, componentLoader } = createWidgetDefinition("app", {
},
{
label(t) {
return t("widget.app.option.layout.option.row");
return t("widget.common.layout.option.horizontal");
},
value: "row",
icon: IconLayoutSidebarLeftExpand,
@@ -10,12 +10,12 @@ interface PingIndicatorProps {
}
export const PingIndicator = ({ appId }: PingIndicatorProps) => {
const t = useI18n();
const t = useI18n("common");
const { data: pingResult, error } = clientApi.widget.app.ping.useQuery({ id: appId }, { refetchOnMount: false });
if (error) return <PingDot icon={IconX} color="red" tooltip={t("common.error")} />;
if (error) return <PingDot icon={IconX} color="red" tooltip={t("error")} />;
if (!pingResult) return <PingDot icon={IconMinus} color="gray" tooltip={`${t("common.action.loading")}…`} />;
if (!pingResult) return <PingDot icon={IconMinus} color="gray" tooltip={`${t("action.loading")}…`} />;
const isError = "error" in pingResult || pingResult.statusCode >= 500;
@@ -5,7 +5,7 @@ import { Avatar, Badge, Card, Group, ScrollArea, SimpleGrid, Stack, Text } from
import { clientApi } from "@homarr/api/client";
import { formatByteRate } from "@homarr/common";
import { getIconUrl } from "@homarr/definitions";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import { WidgetQueryErrorIndicator } from "../common/query-state-indicator";
@@ -47,7 +47,8 @@ const ArchiveTeamWarriorWidgetContent = ({
height: number;
isAdvanced: boolean;
}) => {
const t = useScopedI18n("widget.archiveTeamWarrior");
const t = useI18n("widget.archiveTeamWarrior");
const tWidgetCommon = useI18n("widget.common");
const locale = useCurrentIntlLocale();
const [data, statusQuery] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({ integrationId });
@@ -107,7 +108,7 @@ const ArchiveTeamWarriorWidgetContent = ({
{t("runnerStatus", { status: t(`status.${getStatusKey(status.runnerStatus ?? status.status)}`) })}
</Text>
<Text size="xs" c="dimmed">
{t("updatedAt", { date: new Date(status.updatedAt).toLocaleString(locale) })}
{tWidgetCommon("updatedAt", { date: new Date(status.updatedAt).toLocaleString(locale) })}
</Text>
</Group>
<Group gap="xs" wrap="wrap">
+2 -2
View File
@@ -3,14 +3,14 @@
import { Center, Stack, Text, ThemeIcon } from "@mantine/core";
import { IconRobot } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import { useAssistantWidgetRenderer } from "./context";
export default function AssistantWidget(props: WidgetComponentProps<"assistant">) {
const Renderer = useAssistantWidgetRenderer();
const t = useScopedI18n("widget.assistant.unavailable");
const t = useI18n("widget.assistant.unavailable");
if (Renderer) return <Renderer {...props} />;
@@ -4,7 +4,7 @@ import type { CSSProperties } from "react";
import { Text } from "@mantine/core";
import type { AudiobookshelfDashboardData, NavidromeDashboardData } from "@homarr/integrations/types";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import classes from "./component.module.css";
import type { AudioStatsBackend, AudioStatsDisplayOptions } from "./shared";
@@ -49,7 +49,7 @@ export function AudioStatsContent({
width,
height,
}: AudioStatsContentProps) {
const t = useScopedI18n(AUDIO_STATS_TRANSLATION_SCOPE);
const t = useI18n(AUDIO_STATS_TRANSLATION_SCOPE);
const compact = options.compactMode ?? false;
const enabledStats = prioritizeVisibleStats(getVisibleStats(backend, options, stats, showAllStats), compact);
const visibleStats = enabledStats.slice(0, getVisibleStatLimit(width, height, enabledStats.length, compact));
@@ -23,7 +23,8 @@ export default function AudioStatsWidget({
displayMode = "compact",
widgetRuntimeRef,
}: WidgetComponentProps<"audioStats">) {
const t = useI18n();
const tAudio = useI18n("widget.audioStats");
const tMediaServer = useI18n("widget.mediaServer");
const statsInput = { integrationId: integrationIds[0] ?? "" };
const { data: response, error: statsError } = clientApi.widget.audioStats.getStats.useQuery(statsInput);
const streamsInput = { integrationIds: [statsInput.integrationId], showOnlyPlaying: true };
@@ -56,7 +57,7 @@ export default function AudioStatsWidget({
return (
<Box h="100%" pos="relative">
<Box pos="absolute" top={4} right={8} style={{ zIndex: 1 }}>
<WidgetQueryErrorIndicator error={statsError} label={t("widget.audioStats.name")} />
<WidgetQueryErrorIndicator error={statsError} label={tAudio("name")} />
</Box>
{summary}
</Box>
@@ -74,8 +75,8 @@ export default function AudioStatsWidget({
<div style={{ minHeight: 150 }}>{summary}</div>
{(statsError || streamsError || hasStreamErrors) && (
<Group justify="flex-end">
<WidgetQueryErrorIndicator error={statsError} label={t("widget.audioStats.name")} />
<WidgetQueryErrorIndicator error={streamsError} label={t("widget.mediaServer.name")} />
<WidgetQueryErrorIndicator error={statsError} label={tAudio("name")} />
<WidgetQueryErrorIndicator error={streamsError} label={tMediaServer("name")} />
<IntegrationErrorIndicator results={currentStreams} />
</Group>
)}
+13 -4
View File
@@ -5,7 +5,8 @@ import { Text } from "@mantine/core";
import { IconAlertTriangle, IconBell, IconDeviceTv, IconMovie, IconPlugConnected } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { getIntegrationName } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state";
import type { WidgetComponentProps } from "../definition";
@@ -60,7 +61,7 @@ export default function BazarrWidget({
height,
displayMode,
}: WidgetComponentProps<"bazarr">) {
const t = useScopedI18n("widget.bazarr");
const t = useI18n("widget.bazarr");
const { data: badges, error } = clientApi.widget.bazarr.getBadges.useQuery(
{ integrationId: integrationIds[0] ?? "" },
{ enabled: Boolean(integrationIds[0]) },
@@ -106,6 +107,14 @@ export default function BazarrWidget({
{visibleStatKeys.map((statKey) => {
const Icon = statIcons[statKey];
const value = statValues[statKey];
let label: string;
if (statKey === "sonarrSignalr") {
label = `${getIntegrationName("sonarr")} SignalR`;
} else if (statKey === "radarrSignalr") {
label = `${getIntegrationName("radarr")} SignalR`;
} else {
label = t(statKey);
}
const isWarning =
typeof value === "number" &&
(statKey === "providers" || statKey === "status" || statKey === "announcements") &&
@@ -117,8 +126,8 @@ export default function BazarrWidget({
<span className={`${classes.statValue} ${isWarning ? classes.statValueWarning : ""}`}>
{typeof value === "string" && value.trim() === "" ? "—" : value}
</span>
<span className={classes.statLabel} title={t(statKey)}>
{t(statKey)}
<span className={classes.statLabel} title={label}>
{label}
</span>
</div>
);
@@ -23,7 +23,7 @@ import type { LucideIcon } from "lucide-react";
import { Activity, Battery, Cpu, HardDrive, MemoryStick, Monitor, Network, Server, Thermometer } from "lucide-react";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import { IntegrationErrorIndicator } from "../common/integration-error-indicator";
@@ -58,7 +58,7 @@ export default function BeszelAlertsWidget({
displayMode,
widgetRuntimeRef,
}: WidgetComponentProps<"beszelAlerts">) {
const t = useScopedI18n("widget.beszelAlerts");
const t = useI18n("widget.beszelAlerts");
const isAdvanced = displayMode === "advanced";
const alertsInput = useMemo(
() =>
+1 -1
View File
@@ -31,7 +31,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelAle
errors: {
INTERNAL_SERVER_ERROR: {
icon: IconServerOff,
message: (t) => t("widget.beszelAlerts.error.internalServerError"),
message: (t) => t("widget.beszel.error.internalServerError"),
},
},
}).withDynamicImport(() => import("./component"));
@@ -1,7 +1,19 @@
"use client";
import type { MantineSize } from "@mantine/core";
import { Badge, Box, Card, Center, Group, Loader, Progress, SimpleGrid, Stack, Text, UnstyledButton } from "@mantine/core";
import {
Badge,
Box,
Card,
Center,
Group,
Loader,
Progress,
SimpleGrid,
Stack,
Text,
UnstyledButton,
} from "@mantine/core";
import {
Activity,
Battery,
@@ -20,8 +32,9 @@ import { IconServerOff } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { formatBytes } from "@homarr/common";
import { invariantTechnicalLabels } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import classes from "./component.module.css";
@@ -168,7 +181,8 @@ const MetricRow = ({ icon, label, value, progress, size }: MetricRowProps) => (
interface SystemCardProps {
system: BeszelSystemRow & { rowKey: string };
options: WidgetComponentProps<"beszelSystemGrid">["options"];
t: ReturnType<typeof useScopedI18n<"widget.beszelSystemGrid">>;
t: ReturnType<typeof useI18n<"widget.beszel">>;
tCommon: ReturnType<typeof useI18n<"common">>;
size: SizeConfig;
maxMetrics: number;
itemRadius: MantineSize;
@@ -177,14 +191,25 @@ interface SystemCardProps {
onClick?: () => void;
}
const metricRenderers = [
type BeszelMetricRenderer = {
key: string;
render: (
system: BeszelSystemRow,
t: SystemCardProps["t"],
size: SizeConfig,
tCommon: SystemCardProps["tCommon"],
) => React.ReactNode;
visible: (system: BeszelSystemRow, options: SystemCardProps["options"], advanced: boolean) => boolean;
};
const metricRenderers: BeszelMetricRenderer[] = [
{
key: "showCpu",
render: (s: BeszelSystemRow, t: SystemCardProps["t"], sz: SizeConfig) => (
<MetricRow
key="cpu"
icon={<Cpu size={sz.iconSize} />}
label={t("metric.cpu")}
label={invariantTechnicalLabels.cpu}
value={formatPercent(s.cpu)}
progress={{ value: s.cpu, color: thresholdColor(s.cpu) }}
size={sz}
@@ -228,7 +253,7 @@ const metricRenderers = [
<MetricRow
key="gpu"
icon={<Monitor size={sz.iconSize} />}
label={t("metric.gpu")}
label={invariantTechnicalLabels.gpu}
value={formatPercent(s.gpu)}
progress={{ value: s.gpu, color: thresholdColor(s.gpu) }}
size={sz}
@@ -299,11 +324,11 @@ const metricRenderers = [
},
{
key: "showServices",
render: (s: BeszelSystemRow, t: SystemCardProps["t"], sz: SizeConfig) => (
render: (s: BeszelSystemRow, _t: SystemCardProps["t"], sz: SizeConfig, tCommon: SystemCardProps["tCommon"]) => (
<MetricRow
key="svc"
icon={<Server size={sz.iconSize} />}
label={t("metric.services")}
label={tCommon("services")}
value={String(s.services)}
size={sz}
/>
@@ -345,6 +370,7 @@ const SystemCard = ({
system,
options,
t,
tCommon,
size,
maxMetrics,
itemRadius,
@@ -375,12 +401,7 @@ const SystemCard = ({
}}
>
{onClick && (
<UnstyledButton
type="button"
className={classes.cardAction}
aria-label={system.name}
onClick={onClick}
/>
<UnstyledButton type="button" className={classes.cardAction} aria-label={system.name} onClick={onClick} />
)}
<Group gap="xs" mb={2}>
<Badge
@@ -395,20 +416,20 @@ const SystemCard = ({
{isAdvanced && (
<SimpleGrid cols={2} spacing={4} verticalSpacing={2} mb={4}>
<SystemMetadata label={t("metadata.hostname")} value={system.hostname || "—"} />
<SystemMetadata label={t("metadata.os")} value={system.osName || "—"} />
<SystemMetadata label={t("metadata.cpuModel")} value={system.cpuModel || "—"} />
<SystemMetadata label={t("metadata.cores")} value={String(system.cores)} />
<SystemMetadata label={t("metric.hostname")} value={system.hostname || "—"} />
<SystemMetadata label={invariantTechnicalLabels.os} value={system.osName || "—"} />
<SystemMetadata label={t("metric.cpuModel")} value={system.cpuModel || "—"} />
<SystemMetadata label={t("metric.cores")} value={String(system.cores)} />
<SystemMetadata
label={t("metadata.memoryTotal")}
label={t("metric.memoryTotal")}
value={system.memoryTotal > 0 ? formatBytes(system.memoryTotal) : "—"}
/>
<SystemMetadata label={t("metadata.source")} value={integrationName} />
<SystemMetadata label={t("metric.source")} value={integrationName} />
</SimpleGrid>
)}
<Stack gap={0} style={{ flex: 1 }} justify="space-evenly">
{visibleMetrics.map((m) => m.render(system, t, size))}
{visibleMetrics.map((m) => m.render(system, t, size, tCommon))}
</Stack>
{hiddenMetricCount > 0 && (
<Text size="xs" c="dimmed" ta="right">
@@ -438,7 +459,9 @@ export default function BeszelSystemGridWidget({
height,
displayMode,
}: WidgetComponentProps<"beszelSystemGrid">) {
const t = useScopedI18n("widget.beszelSystemGrid");
const t = useI18n("widget.beszel");
const tFeature = useI18n("widget.beszelSystemGrid");
const tCommon = useI18n("common");
const board = useRequiredBoard();
const { openModal } = useModalAction(BeszelSystemStatsModal);
@@ -462,7 +485,7 @@ export default function BeszelSystemGridWidget({
return (
<Box h="100%" pos="relative" style={{ pointerEvents: isEditMode ? "none" : undefined }}>
<Group pos="absolute" top={4} right={8} gap={0} style={{ zIndex: 1 }}>
<WidgetQueryErrorIndicator error={systemsQuery.error} label={t("name")} />
<WidgetQueryErrorIndicator error={systemsQuery.error} label={tFeature("name")} />
<IntegrationErrorIndicator results={results} />
</Group>
<Center h="100%">
@@ -491,7 +514,7 @@ export default function BeszelSystemGridWidget({
return (
<Box h="100%" pos="relative" style={{ pointerEvents: isEditMode ? "none" : undefined }}>
<Group pos="absolute" top={4} right={8} gap={0} style={{ zIndex: 1 }}>
<WidgetQueryErrorIndicator error={systemsQuery.error} label={t("name")} />
<WidgetQueryErrorIndicator error={systemsQuery.error} label={tFeature("name")} />
<IntegrationErrorIndicator results={results} />
</Group>
<Box
@@ -516,6 +539,7 @@ export default function BeszelSystemGridWidget({
system={system}
options={options}
t={t}
tCommon={tCommon}
size={size}
maxMetrics={maxMetrics}
itemRadius={board.itemRadius}
@@ -31,7 +31,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
errors: {
INTERNAL_SERVER_ERROR: {
icon: IconServerOff,
message: (t) => t("widget.beszelSystemGrid.error.internalServerError"),
message: (t) => t("widget.beszel.error.internalServerError"),
},
},
}).withDynamicImport(() => import("./component"));
@@ -10,7 +10,7 @@ import { useSession } from "@homarr/auth/client";
import { constructBoardPermissions } from "@homarr/auth/shared";
import { useOptionalBoard } from "@homarr/boards/context";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import classes from "./component.module.css";
@@ -33,7 +33,8 @@ export default function BeszelSystemStatsWidget({
setOptions,
widgetRuntimeRef,
}: WidgetComponentProps<"beszelSystemStats">) {
const t = useScopedI18n("widget.beszelSystemStats");
const t = useI18n("widget.beszelSystemStats");
const tBeszel = useI18n("widget.beszel");
const board = useOptionalBoard();
const { data: session } = useSession();
const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;
@@ -150,7 +151,7 @@ export default function BeszelSystemStatsWidget({
<Stack align="center" gap="xs">
<IconServerOff size={28} opacity={0.5} />
<Text size="sm" c="dimmed">
{t("empty.noSystems")}
{tBeszel("empty.noSystems")}
</Text>
</Stack>
</Center>
@@ -74,7 +74,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
errors: {
INTERNAL_SERVER_ERROR: {
icon: IconServerOff,
message: (t) => t("widget.beszelSystemStats.error.internalServerError"),
message: (t) => t("widget.beszel.error.internalServerError"),
},
},
}).withDynamicImport(() => import("./component"));
@@ -21,9 +21,10 @@ import { useSession } from "@homarr/auth/client";
import { constructBoardPermissions } from "@homarr/auth/shared";
import { useOptionalBoard } from "@homarr/boards/context";
import { formatBytes } from "@homarr/common";
import { invariantTechnicalLabels } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import { HomarrDataTable } from "../common/homarr-data-table";
@@ -124,7 +125,9 @@ export default function BeszelSystemTableWidget({
setOptions,
displayMode,
}: WidgetComponentProps<"beszelSystemTable">) {
const t = useScopedI18n("widget.beszelSystemTable");
const t = useI18n("widget.beszelSystemTable");
const tBeszel = useI18n("widget.beszel");
const tCommon = useI18n("common");
const { openModal } = useModalAction(BeszelSystemStatsModal);
const board = useOptionalBoard();
const { data: session } = useSession();
@@ -201,7 +204,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Server size={size.iconSize} />
<Text inherit>{t("column.system")}</Text>
<Text inherit>{tBeszel("metric.system")}</Text>
</Group>
),
sortable: true,
@@ -218,7 +221,7 @@ export default function BeszelSystemTableWidget({
accessor: "integrationName",
width: 140,
ellipsis: true,
title: t("column.source"),
title: tBeszel("metric.source"),
sortable: true,
render: (record) => <Text size={size.fontSize}>{record.integrationName}</Text>,
},
@@ -226,7 +229,7 @@ export default function BeszelSystemTableWidget({
accessor: "hostname",
width: 150,
ellipsis: true,
title: t("column.hostname"),
title: tBeszel("metric.hostname"),
sortable: true,
render: (record) => <Text size={size.fontSize}>{record.hostname || "—"}</Text>,
},
@@ -234,7 +237,7 @@ export default function BeszelSystemTableWidget({
accessor: "osName",
width: 160,
ellipsis: true,
title: t("column.os"),
title: invariantTechnicalLabels.os,
sortable: true,
render: (record) => <Text size={size.fontSize}>{record.osName || "—"}</Text>,
},
@@ -242,21 +245,21 @@ export default function BeszelSystemTableWidget({
accessor: "cpuModel",
width: 220,
ellipsis: true,
title: t("column.cpuModel"),
title: tBeszel("metric.cpuModel"),
sortable: true,
render: (record) => <Text size={size.fontSize}>{record.cpuModel || "—"}</Text>,
},
isAdvanced && {
accessor: "cores",
width: 80,
title: t("column.cores"),
title: tBeszel("metric.cores"),
sortable: true,
render: (record) => <Text size={size.fontSize}>{record.cores}</Text>,
},
isAdvanced && {
accessor: "memoryTotal",
width: 120,
title: t("column.memoryTotal"),
title: tBeszel("metric.memoryTotal"),
sortable: true,
render: (record) => (
<Text size={size.fontSize}>{record.memoryTotal > 0 ? formatBytes(record.memoryTotal) : "—"}</Text>
@@ -268,7 +271,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Cpu size={size.iconSize} />
<Text inherit>{t("column.cpu")}</Text>
<Text inherit>{invariantTechnicalLabels.cpu}</Text>
</Group>
),
sortable: true,
@@ -280,7 +283,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<MemoryStick size={size.iconSize} />
<Text inherit>{t("column.memory")}</Text>
<Text inherit>{tBeszel("metric.memory")}</Text>
</Group>
),
sortable: true,
@@ -292,7 +295,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<HardDrive size={size.iconSize} />
<Text inherit>{t("column.disk")}</Text>
<Text inherit>{tBeszel("metric.disk")}</Text>
</Group>
),
sortable: true,
@@ -312,7 +315,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Monitor size={size.iconSize} />
<Text inherit>{t("column.gpu")}</Text>
<Text inherit>{invariantTechnicalLabels.gpu}</Text>
</Group>
),
sortable: true,
@@ -324,7 +327,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Activity size={size.iconSize} />
<Text inherit>{t("column.loadAvg")}</Text>
<Text inherit>{tBeszel("metric.loadAvg")}</Text>
</Group>
),
sortable: true,
@@ -346,7 +349,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Network size={size.iconSize} />
<Text inherit>{t("column.net")}</Text>
<Text inherit>{tBeszel("metric.net")}</Text>
</Group>
),
sortable: true,
@@ -362,7 +365,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Thermometer size={size.iconSize} />
<Text inherit>{t("column.temp")}</Text>
<Text inherit>{tBeszel("metric.temp")}</Text>
</Group>
),
sortable: true,
@@ -374,7 +377,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Battery size={size.iconSize} />
<Text inherit>{t("column.battery")}</Text>
<Text inherit>{tBeszel("metric.battery")}</Text>
</Group>
),
render: (record) => <Text size={size.fontSize}>{record.battery ? `${record.battery[0]}%` : "—"}</Text>,
@@ -385,7 +388,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Server size={size.iconSize} />
<Text inherit>{t("column.services")}</Text>
<Text inherit>{tCommon("services")}</Text>
</Group>
),
sortable: true,
@@ -397,7 +400,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Activity size={size.iconSize} />
<Text inherit>{t("column.uptime")}</Text>
<Text inherit>{tBeszel("metric.uptime")}</Text>
</Group>
),
sortable: true,
@@ -409,7 +412,7 @@ export default function BeszelSystemTableWidget({
title: (
<Group gap={4} wrap="nowrap">
<Wifi size={size.iconSize} />
<Text inherit>{t("column.agent")}</Text>
<Text inherit>{tBeszel("metric.agent")}</Text>
</Group>
),
sortable: true,
@@ -418,7 +421,7 @@ export default function BeszelSystemTableWidget({
];
return cols.filter(Boolean) as DataTableColumn<SystemRowWithKey>[];
}, [t, size, visibleMetricKeys, isAdvanced]);
}, [tBeszel, tCommon, size, visibleMetricKeys, isAdvanced]);
const { effectiveColumns, storeKey } = usePersistedTableLayout({
columns,
@@ -462,7 +465,7 @@ export default function BeszelSystemTableWidget({
columns={effectiveColumns}
sortStatus={sortStatus}
onSortStatusChange={setSortStatus}
noRecordsText={t("noRecords")}
noRecordsText={tBeszel("empty.noSystems")}
idAccessor="rowKey"
storeColumnsKey={storeKey}
onRowClick={isEditMode ? undefined : handleRowClick}
@@ -1,22 +1,25 @@
import { IconServerOff, IconTable } from "@tabler/icons-react";
import { invariantTechnicalLabels } from "@homarr/definitions";
import { createWidgetDefinition, matchesWidgetRuntimeQuery, widgetQueryInputMatches } from "../definition";
import type { SelectOption } from "../_inputs/widget-select-input";
import { statusOptions } from "../beszel/_shared/options";
import { optionsBuilder } from "../options";
const sortOptions = [
{ value: "name", label: "System" },
{ value: "cpu", label: "CPU" },
{ value: "memory", label: "Memory" },
{ value: "disk", label: "Disk" },
{ value: "gpu", label: "GPU" },
{ value: "loadAvg", label: "Load Avg" },
{ value: "netBytes", label: "Net" },
{ value: "temp", label: "Temp" },
{ value: "services", label: "Services" },
{ value: "uptime", label: "Uptime" },
{ value: "agentVersion", label: "Agent" },
];
{ value: "name", label: (t) => t("widget.beszel.metric.system") },
{ value: "cpu", label: invariantTechnicalLabels.cpu },
{ value: "memory", label: (t) => t("widget.beszel.metric.memory") },
{ value: "disk", label: (t) => t("widget.beszel.metric.disk") },
{ value: "gpu", label: invariantTechnicalLabels.gpu },
{ value: "loadAvg", label: (t) => t("widget.beszel.metric.loadAvg") },
{ value: "netBytes", label: (t) => t("widget.beszel.metric.net") },
{ value: "temp", label: (t) => t("widget.beszel.metric.temp") },
{ value: "services", label: (t) => t("common.services") },
{ value: "uptime", label: (t) => t("widget.beszel.metric.uptime") },
{ value: "agentVersion", label: (t) => t("widget.beszel.metric.agent") },
] satisfies SelectOption[];
const sortDirectionOptions = [
{ value: "asc", label: "Ascending" },
@@ -67,7 +70,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
errors: {
INTERNAL_SERVER_ERROR: {
icon: IconServerOff,
message: (t) => t("widget.beszelSystemTable.error.internalServerError"),
message: (t) => t("widget.beszel.error.internalServerError"),
},
},
}).withDynamicImport(() => import("./component"));
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { Box, Group, Popover, Progress, Stack, Text, UnstyledButton } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { BeszelSystemRow } from "./types";
import { thresholdColor } from "./colors";
@@ -21,7 +21,7 @@ const mountLabel = (path: string) =>
const severityColor = (value: number) => `var(--mantine-color-${thresholdColor(value)}-6)`;
export const DiskUsage = ({ system, fontSize, progressSize, valueMiw, valueGap = 6 }: DiskUsageProps) => {
const t = useScopedI18n("common");
const t = useI18n("common");
const [opened, setOpened] = useState(false);
const filesystems = Object.entries(system.extraFilesystems).filter(([path]) => path !== "/");
const filesystemUsageLabel = t("filesystemUsage", { count: filesystems.length + 1 });
@@ -5,8 +5,9 @@ import { Button, Center, Group, SimpleGrid, Skeleton, Stack, Text } from "@manti
import { IconPlugConnectedX, IconServerOff } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { invariantTechnicalLabels } from "@homarr/definitions";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { getUsableWidgetQueryData } from "../../common/query-state";
import { containerColors } from "./colors";
@@ -73,7 +74,8 @@ export function BeszelStatsView({
columns,
onSwitchToHistorical,
}: BeszelStatsViewProps) {
const t = useScopedI18n("widget.beszelSystemStats");
const t = useI18n("widget.beszelSystemStats");
const tBeszel = useI18n("widget.beszel");
const locale = useCurrentIntlLocale();
const showDocker = visibility.dockerCpu || visibility.dockerMemory || visibility.dockerNetwork;
const isLive = timePeriod === "1m";
@@ -91,7 +93,7 @@ export function BeszelStatsView({
const mappers = useMemo(
() => ({
cpu: (s: { cpu: number }) => ({ [t("chart.cpu.series")]: s.cpu }),
cpu: (s: { cpu: number }) => ({ [invariantTechnicalLabels.cpu]: s.cpu }),
memory: (s: { mu: number; mb: number }) => ({
[t("chart.memory.series")]: s.mu,
[t("chart.memory.cache")]: s.mb ?? 0,
@@ -110,7 +112,7 @@ export function BeszelStatsView({
const series = useMemo(
() => ({
cpu: [{ name: t("chart.cpu.series"), color: "teal.6" }],
cpu: [{ name: invariantTechnicalLabels.cpu, color: "teal.6" }],
memory: [
{ name: t("chart.memory.series"), color: "teal.5" },
{ name: t("chart.memory.cache"), color: "teal.8" },
@@ -238,7 +240,7 @@ export function BeszelStatsView({
<Stack align="center" gap="xs">
<IconServerOff size={24} opacity={0.5} />
<Text size="sm" c="dimmed">
{t("error.internalServerError")}
{tBeszel("error.internalServerError")}
</Text>
</Stack>
</Center>
@@ -1,7 +1,7 @@
"use client";
import type { CSSProperties } from "react";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { formatLocalizedDate } from "../../common/locale";
@@ -54,7 +54,7 @@ interface BeszelTooltipProps {
const BeszelTooltipContent = ({ active, label, payload, formatter, showTotal }: BeszelTooltipProps) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("common");
const t = useI18n("common");
const isActive = active && (payload?.length ?? 0) > 0;
if (!isActive) return null;
@@ -6,7 +6,7 @@ import { IconCheck } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { SortableItemListInput } from "../options";
@@ -17,9 +17,9 @@ export const BookmarkAddButton: SortableItemListInput<SelectableApp, string>["Ad
removeItem,
values,
}) => {
const t = useScopedI18n("widget.bookmarks.option.items.apps");
const tCommon = useScopedI18n("common");
const tSelect = useScopedI18n("app.action.select");
const t = useI18n("widget.bookmarks.option.items.apps");
const tCommon = useI18n("common");
const tSelect = useI18n("app.action.select");
const { data: apps = [], isPending, error } = clientApi.app.selectable.useQuery();
const appsById = new Map(apps.map((app) => [app.id, app]));
+6 -1
View File
@@ -20,7 +20,12 @@ export const { definition, componentLoader } = createWidgetDefinition("bookmarks
layout: factory.select({
options: (["grid", "gridHorizontal", "row", "column"] as const).map((value) => ({
value,
label: (t) => t(`widget.bookmarks.option.layout.option.${value}.label`),
label: (t) => {
if (value === "grid") return t("widget.common.layout.option.grid");
if (value === "row") return t("widget.common.layout.option.horizontal");
if (value === "column") return t("widget.common.layout.option.vertical");
return t("widget.bookmarks.option.layout.option.gridHorizontal.label");
},
})),
defaultValue: "column",
}),
@@ -95,7 +95,7 @@ const CalendarEventRows = ({
advanced,
}: Pick<CalendarEventListProps, "events" | "advanced"> & { locale: string }) => {
const { colorScheme } = useMantineColorScheme();
const t = useI18n();
const t = useI18n("widget.calendar");
return (
<>
{events.map((event, eventIndex) => (
@@ -145,7 +145,7 @@ const CalendarEventRows = ({
{event.metadata?.type === "radarr" && (
<Group wrap="nowrap">
<Text c="dimmed" size="sm">
{t(`widget.calendar.option.releaseType.options.${event.metadata.releaseType}`)}
{t(`option.releaseType.options.${event.metadata.releaseType}`)}
</Text>
</Group>
)}
@@ -154,7 +154,7 @@ const CalendarEventRows = ({
<IconClock opacity={0.7} size={"1rem"} />
{isAllDay(event) ? (
<Text c={"dimmed"} size={"sm"}>
{t("widget.calendar.duration.allDay")}
{t("duration.allDay")}
</Text>
) : (
<>
+5 -5
View File
@@ -11,7 +11,7 @@ import dayjs from "dayjs";
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { useSettings } from "@homarr/settings";
import { useCurrentIntlLocale, useI18n, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import actionTargetClasses from "../common/action-target.module.css";
import type { WidgetComponentProps } from "../definition";
@@ -138,7 +138,7 @@ const CalendarBase = ({
options,
displayMode,
}: CalendarBaseProps) => {
const t = useI18n();
const t = useI18n("widget.calendar");
const locale = useCurrentIntlLocale();
const { firstDayOfWeek } = useSettings();
const board = useRequiredBoard();
@@ -171,7 +171,7 @@ const CalendarBase = ({
failedIntegrations={failedIntegrations}
isPending={isPending}
queryError={queryError}
queryErrorLabel={t("widget.calendar.name")}
queryErrorLabel={t("name")}
isEditMode={isEditMode}
locale={locale}
month={month}
@@ -185,7 +185,7 @@ const CalendarBase = ({
{(failedIntegrations.length > 0 || Boolean(queryError)) && (
<Group px="xs" justify="flex-end">
<IntegrationErrorIndicator results={failedIntegrations} />
<WidgetQueryErrorIndicator error={queryError} label={t("widget.calendar.name")} />
<WidgetQueryErrorIndicator error={queryError} label={t("name")} />
</Group>
)}
<Calendar
@@ -287,7 +287,7 @@ const CalendarAgenda = ({
month,
setMonth,
}: CalendarAgendaProps) => {
const t = useScopedI18n("widget.calendar.advanced");
const t = useI18n("widget.calendar.advanced");
const monthLabel = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month);
return (
+9 -9
View File
@@ -15,7 +15,7 @@ import {
import { IconAlertTriangle, IconClock } from "@tabler/icons-react";
import type { Dayjs } from "dayjs";
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
import type { WidgetComponentProps } from "../definition";
@@ -47,7 +47,7 @@ export const AdvancedClockView = ({
primaryTimeZone,
primaryTimeZoneInvalid,
}: AdvancedClockViewProps) => {
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
const primaryLabel = getPrimaryLabel(options, t);
const primary: WorldClockTime = {
id: "primary",
@@ -95,7 +95,7 @@ interface ModeProps {
const PrimaryClock = ({ now, options, primary }: Pick<ModeProps, "now" | "options" | "primary">) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
const primaryTime = primary.zonedTime;
if (!primaryTime || primary.phase === null || primary.minuteOfDay === null) return null;
@@ -152,7 +152,7 @@ const PrimaryClock = ({ now, options, primary }: Pick<ModeProps, "now" | "option
};
const OverviewMode = ({ now, options, primary, cities }: ModeProps) => {
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
if (cities.length === 0) return <EmptyCities />;
return (
@@ -218,7 +218,7 @@ const ClockTime = ({
compact = false,
}: Omit<ClockEntryProps, "primaryOffset"> & { primary?: boolean; compact?: boolean }) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
if (!entry.zonedTime) return null;
let formattedTime = formatLocalizedTime(now, locale, {
hour12: clockTimeFormatUses12Hours(options.customTimeFormat, options.is24HourFormat),
@@ -257,7 +257,7 @@ const ClockTime = ({
const DayAndOffset = ({ entry, now, primaryOffset }: Pick<ClockEntryProps, "entry" | "now" | "primaryOffset">) => {
const locale = useCurrentIntlLocale();
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
if (entry.dayDifference === null || entry.utcOffset === null) return null;
const dayRelation = getDayRelation(entry.dayDifference, t);
const date = formatLocalizedDate(now, locale, {
@@ -280,7 +280,7 @@ const DayAndOffset = ({ entry, now, primaryOffset }: Pick<ClockEntryProps, "entr
};
const InvalidTimeZone = ({ entry }: { entry: WorldClockTime }) => {
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
return (
<Paper component="li" withBorder radius="md" p="md">
<Group gap="xs" wrap="nowrap">
@@ -297,7 +297,7 @@ const InvalidTimeZone = ({ entry }: { entry: WorldClockTime }) => {
};
const EmptyCities = () => {
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
return (
<Paper withBorder radius="md" p="xl">
<Text c="dimmed" ta="center">
@@ -307,7 +307,7 @@ const EmptyCities = () => {
);
};
type ScopedClockTranslator = ReturnType<typeof useScopedI18n<"widget.clock">>;
type ScopedClockTranslator = ReturnType<typeof useI18n<"widget.clock">>;
const getDayRelation = (difference: number, t: ScopedClockTranslator) => {
if (difference < 0) return t("worldClock.yesterday");
@@ -1,6 +1,6 @@
import { Badge, Box, Group, Progress, Stack, Text } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import type { TimeOfDayPhase } from "./world-clock";
@@ -36,7 +36,7 @@ export const TimeOfDayBar = ({
showTicks = false,
label,
}: TimeOfDayBarProps) => {
const t = useScopedI18n("widget.clock");
const t = useI18n("widget.clock");
const progress = Math.max(0, Math.min(100, (minuteOfDay / 1440) * 100));
const remainingMinutes = Math.max(0, 1440 - Math.floor(minuteOfDay));
const remainingHours = Math.floor(remainingMinutes / 60);
@@ -1,7 +1,7 @@
import { Box, Group, Loader, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
import { isInitialWidgetQueryPending } from "../common/query-state";
import { WidgetQueryErrorIndicator } from "../common/query-state-indicator";
@@ -26,7 +26,7 @@ export const ClockWeatherSummary = ({
detailed,
}: ClockWeatherSummaryProps) => {
const t = useI18n();
const tCommon = useScopedI18n("common");
const tCommon = useI18n("common");
const weatherQuery = clientApi.widget.weather.atLocation.useQuery({ latitude, longitude });
const weather = weatherQuery.data;
+2 -2
View File
@@ -3,12 +3,12 @@ import { Center, Text } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
export const WidgetEmptyState = () => {
const t = useI18n();
const t = useI18n("widget.common.error");
return (
<Center h="100%" w="100%" p="sm">
<Text c="dimmed" size="sm" ta="center">
{t("widget.common.error.noData")}
{t("noData")}
</Text>
</Center>
);
@@ -3,7 +3,7 @@
import { ActionIcon, Tooltip } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { useI18n } from "@homarr/translation/client";
interface IntegrationResult {
integrationId: string;
@@ -16,7 +16,7 @@ interface IntegrationErrorIndicatorProps {
}
export function IntegrationErrorIndicator({ results }: IntegrationErrorIndicatorProps) {
const t = useScopedI18n("common");
const t = useI18n("common");
const failed = results.filter((result) => Boolean(result.error));
if (failed.length === 0) return null;
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff. Show more