Compare commits

..
Author SHA1 Message Date
Thomas Camlong cb0222c04d fix: keep HTTP methods untranslated 2026-08-10 10:02:01 +02:00
homarr-crowdin[bot]andThomas 06c489bd48 chore(lang): updated translations from crowdin (#6548)
Co-authored-by: Thomas <thomas@ajnart.fr>
2026-08-10 09:06:56 +02:00
55 changed files with 869 additions and 1797 deletions

No files matched your search

+9 -18
View File
@@ -9,19 +9,17 @@ tags:
--- ---
## Icon picker ## Icon picker
Icons in Homarr are automatically requested from multiple sources: Icons in Homarr are automatically requested from multiple sources:
- [Dashboard Icons](https://dashboardicons.com/) - Our recommended source with over 1888+ curated, high-quality icons
- [Dashboard Icons](https://dashboardicons.com/) - Our recommended source with more than 1,888 curated, high-quality icons - [selfh.st icons](https://github.com/selfhst/icons)
- [selfh.st icons](https://github.com/selfhst/icons) - [Simple icons](https://github.com/simple-icons/simple-icons)
- [Simple icons](https://github.com/simple-icons/simple-icons) - [Tabler icons](https://tabler-icons.io/)
- [Tabler icons](https://tabler-icons.io/) - [Papirus icons](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme)
- [Papirus icons](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) - [Homelab Svg assets](https://github.com/loganmarchione/homelab-svg-assets)
- [Homelab Svg assets](https://github.com/loganmarchione/homelab-svg-assets) - **Local icons**: automatically fetched from the [medias feature](/docs/management/media/)
- **Local icons**: automatically fetched from the [medias feature](/docs/management/media/)
Using these icon sources, Homarr provides a total collection of over 11,000 icons at your fingertips. Using these icon sources, Homarr provides a total collection of over 11,000 icons at your fingertips.
The image picker searches this collection after a short typing delay. When a name is available, such as an app or search engine name, the picker uses it as the initial search. Results show your locally uploaded images first, followed by SVG icons and then other image formats. The icon picker is a fast searcher that helps you to find your desired icon simply by entering a search term.
### Finding Missing Icons ### Finding Missing Icons
@@ -31,13 +29,6 @@ If you can't find the icon you're looking for in Homarr's built-in picker, we st
Icons that are high quality and printable ([SVG](https://wikipedia.org/wiki/Scalable_Vector_Graphics)) are marked with a red badge "SVG" at the top right. Icons that are high quality and printable ([SVG](https://wikipedia.org/wiki/Scalable_Vector_Graphics)) are marked with a red badge "SVG" at the top right.
You can clear the selected image with the clear button or the usual keyboard shortcut for deleting a line (Command+Backspace on macOS or Control+Backspace on other platforms). Clearing the field does not restore the previous image.
### Using external icons ### Using external icons
If you don't find the icon you're looking for on Dashboard Icons or wish to use a different source, you can simply enter a URL that points to an icon. If you don't find the icon you're looking for on Dashboard Icons or wish to use a different source, you can simply enter a URL that points to an icon.
Direct HTTP(S) image URLs are used as entered instead of being searched in the built-in repositories. The picker previews the image and shows whether it loaded successfully. It is important that the URL directly points to the file without any advertisements or elements around it. Direct HTTP(S) image URLs are used as entered instead of being searched in the built-in repositories. It is important that the URL directly points to the file without any advertisements or elements around it.
### Uploading a local image
Users with media upload permission can select **Upload image** next to the field. After the upload finishes, the new local image is selected immediately and is available at the top of future searches.
+1 -1
View File
@@ -28,7 +28,7 @@ The name must be at least one character long and can be chosen freely.
### Icon URL ### Icon URL
This is the URL to the icon that will be displayed on the app widget. This is the URL to the icon that will be displayed on the app widget.
You can paste a direct HTTP(S) URL to an image, search the included icon repositories by name, or upload a local file through the upload button. The app name is pre-filled as the initial library search when no image is selected. Local images appear first, followed by SVG icons and other formats. Direct image URLs are previewed, used as entered, and are not searched in the icon repositories. You can paste a direct HTTP(S) URL to an image, search the included icon repositories by name, or upload a local file through the upload button. Direct image URLs are used as entered and are not searched in the icon repositories.
![Icon URL](./img/app-icon-url.png) ![Icon URL](./img/app-icon-url.png)
@@ -697,11 +697,7 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
<Stack gap="sm"> <Stack gap="sm">
<TextInput label={t("field.name")} required {...form.getInputProps("name")} /> <TextInput label={t("field.name")} required {...form.getInputProps("name")} />
<Textarea label={t("field.description")} {...form.getInputProps("description")} /> <Textarea label={t("field.description")} {...form.getInputProps("description")} />
<IconPicker <IconPicker withAsterisk={false} {...form.getInputProps("iconUrl")} />
withAsterisk={false}
suggestedSearch={mode === "create" ? form.values.name : undefined}
{...form.getInputProps("iconUrl")}
/>
</Stack> </Stack>
</Fieldset> </Fieldset>
@@ -57,10 +57,7 @@ export const SearchEngineForm = (props: SearchEngineFormProps) => {
/> />
</Grid.Col> </Grid.Col>
</Grid> </Grid>
<IconPicker <IconPicker {...form.getInputProps("iconUrl")} />
{...form.getInputProps("iconUrl")}
suggestedSearch={initialValues === undefined ? form.values.name : undefined}
/>
<Fieldset legend={t("search.engine.page.edit.configControl")}> <Fieldset legend={t("search.engine.page.edit.configControl")}>
<SegmentedControl <SegmentedControl
+1 -4
View File
@@ -45,10 +45,7 @@ describe("Custom JSX custom widgets", () => {
await page.goto(`${baseUrl}/auth/login`); await page.goto(`${baseUrl}/auth/login`);
await page.getByLabel("Username").fill(adminCredentials.username); await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password); await page.locator("#password").fill(adminCredentials.password);
const loginNavigation = page.waitForURL((url) => url.origin === baseUrl && url.pathname !== "/auth/login", { const loginNavigation = page.waitForURL(baseUrl, { timeout: 15_000, waitUntil: "commit" });
timeout: 60_000,
waitUntil: "commit",
});
await page.locator("css=button[type='submit']").click(); await page.locator("css=button[type='submit']").click();
await loginNavigation; await loginNavigation;
+31 -34
View File
@@ -1,4 +1,4 @@
import { getImageMatchRank, normalizeImageName } from "@homarr/common"; import { and, like } from "@homarr/db";
import { icons } from "@homarr/db/schema"; import { icons } from "@homarr/db/schema";
import { iconsFindSchema } from "@homarr/validation/icons"; import { iconsFindSchema } from "@homarr/validation/icons";
@@ -15,41 +15,38 @@ export const iconsRouter = createTRPCRouter({
}) })
.input(iconsFindSchema) .input(iconsFindSchema)
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
const term = normalizeImageName(input.searchText ?? ""); const term = input.searchText?.toLowerCase().trim() ?? "";
const repositories = await ctx.db.query.iconRepositories.findMany({ const keywords = (input.searchText ?? "").split(" ").filter((keyword) => keyword.length > 0);
orderBy: (table, { asc, sql }) => [sql`CASE WHEN ${table.slug} = 'local' THEN 0 ELSE 1 END`, asc(table.slug)],
with: { let whereCondition = undefined;
icons: { if (term.length > 0) {
columns: { id: true, name: true, url: true }, whereCondition = and(...keywords.map((keyword) => like(icons.name, `%${keyword}%`)));
orderBy: (table, { asc, sql }) => [ }
sql`CASE WHEN ${table.name} LIKE '%.svg' THEN 0 ELSE 1 END`,
asc(table.name),
],
limit: term.length === 0 ? input.limitPerGroup : undefined,
},
},
});
return { return {
icons: icons: await ctx.db.query.iconRepositories.findMany({
term.length === 0 with: {
? repositories icons: {
: repositories.map((repository) => ({ columns: { id: true, name: true, url: true },
...repository, where: whereCondition,
icons: repository.icons orderBy: (table, { asc, sql }) => {
.flatMap((icon) => { const svgFirst = sql`CASE WHEN ${table.name} LIKE '%.svg' THEN 0 ELSE 1 END`;
const rank = getImageMatchRank(term, icon.name || icon.url); const nameAsc = asc(table.name);
return rank === null ? [] : [{ icon, rank }]; if (term.length === 0) {
}) return [svgFirst, nameAsc];
.toSorted((a, b) => }
a.rank !== b.rank const tier = sql`CASE
? a.rank - b.rank WHEN LOWER(${table.name}) = ${term} THEN 0
: Number(b.icon.name.toLowerCase().endsWith(".svg")) - WHEN LOWER(${table.name}) LIKE ${term + "%"} THEN 1
Number(a.icon.name.toLowerCase().endsWith(".svg")) || a.icon.name.localeCompare(b.icon.name), WHEN LOWER(${table.name}) LIKE ${`%${term}%`} THEN 2
) ELSE 3
.slice(0, input.limitPerGroup) END`;
.map(({ icon }) => icon), return [tier, svgFirst, nameAsc];
})), },
limit: input.limitPerGroup,
},
},
}),
countIcons: await ctx.db.$count(icons), countIcons: await ctx.db.$count(icons),
}; };
}), }),
@@ -1,44 +0,0 @@
import { describe, expect, test } from "vitest";
import { iconRepositories, icons } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import { iconsRouter } from "../icons";
describe("findIcons", () => {
test.each(["homeassistant", "home_assistant", "home assistant.png"])(
"matches normalized search %s before applying the group limit",
async (searchText) => {
const db = createDb();
const caller = iconsRouter.createCaller({ db, deviceType: undefined, session: null });
await db.insert(iconRepositories).values({ id: "repository", slug: "dashboard-icons" });
await db.insert(icons).values([
{
id: "irrelevant",
name: "000-unrelated.svg",
url: "https://example.com/000-unrelated.svg",
checksum: "irrelevant",
iconRepositoryId: "repository",
},
{
id: "home-assistant",
name: "home-assistant.svg",
url: "https://example.com/home-assistant.svg",
checksum: "home-assistant",
iconRepositoryId: "repository",
},
]);
const result = await caller.findIcons({ searchText, limitPerGroup: 1 });
expect(result.icons[0]?.icons).toEqual([
{
id: "home-assistant",
name: "home-assistant.svg",
url: "https://example.com/home-assistant.svg",
},
]);
},
);
});
-31
View File
@@ -28,34 +28,3 @@ export const bestMatch = <TItem extends Record<string, unknown>>(
return best; return best;
}, null); }, null);
}; };
export const normalizeImageName = (value: string) => {
const fileName = value.split(/[?#]/, 1)[0]?.split("/").pop() ?? value;
const withoutExtension = fileName.replace(/\.(?:avif|gif|jpe?g|png|svg|webp)$/i, "");
return withoutExtension
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/&/g, " and ")
.replace(/[^\p{L}\p{M}\p{N}]+/gu, " ")
.trim()
.toLowerCase();
};
export const getImageMatchRank = (normalizedSearch: string, candidateValue: string): number | null => {
const candidate = normalizeImageName(candidateValue);
if (!candidate) return null;
const compactSearch = normalizedSearch.replaceAll(" ", "");
const compactCandidate = candidate.replaceAll(" ", "");
if (candidate === normalizedSearch) return 0;
if (compactCandidate === compactSearch) return 1;
if (candidate.startsWith(`${normalizedSearch} `)) return 2;
const searchTokens = normalizedSearch.split(" ");
const candidateTokens = candidate.split(" ");
if (searchTokens.every((term) => candidateTokens.some((token) => token === term))) return 3;
if (searchTokens.every((term) => candidateTokens.some((token) => token.startsWith(term)))) return 4;
if (candidate.includes(normalizedSearch)) return 5;
return null;
};
+1 -25
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { bestMatch, capitalize, getImageMatchRank, normalizeImageName } from "../string"; import { bestMatch, capitalize } from "../string";
const capitalizeTestCases = [ const capitalizeTestCases = [
["hello", "Hello"], ["hello", "Hello"],
@@ -54,27 +54,3 @@ describe("bestMatch should find the best match in an array of options", () => {
expect(result).toBeNull(); expect(result).toBeNull();
}); });
}); });
describe("image name matching", () => {
test.each([
["home-assistant.svg", "home assistant"],
["https://example.com/Home_Assistant.PNG?v=1", "home assistant"],
["jelly.fin.webp", "jelly fin"],
["Caf\u00e9.svg", "cafe"],
["\u6771\u4eac.svg", "\u6771\u4eac"],
["\u0939\u093f\u0928\u094d\u0926\u0940.svg", "\u0939\u093f\u0928\u094d\u0926\u0940"],
])("normalizes %s", (value, expected) => {
expect(normalizeImageName(value)).toBe(expected);
});
test.each([
["homeassistant", "home-assistant.svg", 1],
["home assistant", "home_assistant.png", 0],
["home assistant", "Home Assistant.webp", 0],
["\u6771\u4eac", "\u6771\u4eac.svg", 0],
["\u0939\u093f\u0928\u094d\u0926\u0940", "\u0939\u093f\u0928\u094d\u0926\u0940.png", 0],
["home assistant", "unrelated.svg", null],
])("ranks %s against %s", (search, candidate, expected) => {
expect(getImageMatchRank(normalizeImageName(search), candidate)).toBe(expected);
});
});
@@ -210,7 +210,6 @@ export type HomarrDocumentationPath =
| "/docs/integrations/unifi-controller" | "/docs/integrations/unifi-controller"
| "/docs/integrations/unraid" | "/docs/integrations/unraid"
| "/docs/integrations/uptime-kuma" | "/docs/integrations/uptime-kuma"
| "/docs/integrations/whats-up-docker"
| "/docs/management/api" | "/docs/management/api"
| "/docs/management/apps" | "/docs/management/apps"
| "/docs/management/backup" | "/docs/management/backup"
@@ -277,7 +276,6 @@ export type HomarrDocumentationPath =
| "/docs/widgets/video" | "/docs/widgets/video"
| "/docs/widgets/vpn" | "/docs/widgets/vpn"
| "/docs/widgets/weather" | "/docs/widgets/weather"
| "/docs/widgets/whats-up-docker"
| "" | ""
| "/sitemap.xml" | "/sitemap.xml"
| "/docs/integrations/sabnzbd" | "/docs/integrations/sabnzbd"
@@ -1,89 +1,3 @@
.dropdown { [data-combobox-selected="true"] .iconCard {
min-width: min(32rem, calc(100vw - 2rem));
}
.options {
max-height: min(28rem, 60vh);
overflow-y: auto;
overscroll-behavior: contain;
}
.iconGrid {
grid-template-columns: repeat(auto-fill, minmax(3.25rem, 1fr));
}
.iconOption {
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
height: 3.25rem;
padding: var(--mantine-spacing-xs);
border: 1px solid var(--mantine-color-default-border);
border-radius: var(--mantine-radius-md);
background: var(--mantine-color-body);
transition:
border-color 160ms ease,
background-color 160ms ease,
transform 160ms ease;
}
.iconOption:hover,
.iconOption[data-combobox-selected="true"] {
border-color: var(--mantine-primary-color-6); border-color: var(--mantine-primary-color-6);
background: var(--mantine-primary-color-light);
}
.iconOption:active {
transform: scale(0.96);
}
.formatBadge,
.sectionBadge {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: var(--mantine-radius-xs);
background: var(--mantine-color-red-9);
color: var(--mantine-color-white);
font-size: 0.625rem;
font-weight: 700;
line-height: 1;
}
.formatBadge {
position: absolute;
top: 0.2rem;
right: 0.2rem;
padding: 0.15rem 0.2rem;
}
.sectionBadge {
padding: 0.2rem 0.3rem;
}
.urlPreview {
background: var(--mantine-color-default-hover);
}
.previewFrame {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 3rem;
height: 3rem;
flex: 0 0 3rem;
}
.previewLoader {
position: absolute;
z-index: 1;
}
@media (prefers-reduced-motion: reduce) {
.iconOption {
transition: none;
}
} }
@@ -4,84 +4,31 @@ import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vi
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import type { Root } from "react-dom/client"; import type { Root } from "react-dom/client";
import type { IconGroup } from "./icon-picker.utils";
const { findIconsQuery, refetch, uploadSelection, sessionPermissions } = vi.hoisted(() => ({ const { findIconsQuery } = vi.hoisted(() => ({
findIconsQuery: vi.fn(), findIconsQuery: vi.fn((_query: { searchText: string }) => ({
refetch: vi.fn(), data: { icons: [], countIcons: 0 },
uploadSelection: vi.fn(), isLoading: false,
sessionPermissions: { current: [] as string[] }, isError: false,
refetch: vi.fn(),
})),
})); }));
interface QueryData {
icons: IconGroup[];
countIcons: number;
}
const emptyResult: QueryData = { icons: [], countIcons: 11_000 };
let queryResult: {
data?: QueryData;
isLoading: boolean;
isFetching: boolean;
isError: boolean;
};
vi.mock("@homarr/api/client", () => ({ vi.mock("@homarr/api/client", () => ({
clientApi: { clientApi: { icon: { findIcons: { useQuery: findIconsQuery } } },
icon: {
findIcons: {
useQuery: (input: { searchText: string; limitPerGroup: number }, options: { enabled: boolean }) => {
findIconsQuery(input, options);
return { ...queryResult, refetch };
},
},
},
},
})); }));
vi.mock("@homarr/auth/client", () => ({ vi.mock("@homarr/auth/client", () => ({
useSession: () => ({ data: { user: { permissions: sessionPermissions.current } } }), useSession: () => ({ data: { user: { permissions: [] } } }),
})); }));
vi.mock("@homarr/translation", () => ({ supportedLanguages: [] })); vi.mock("@homarr/translation", () => ({ supportedLanguages: [] }));
vi.mock("@homarr/translation/client", () => ({ vi.mock("@homarr/translation/client", () => ({
useScopedI18n: () => (key: string, params?: Record<string, string>) => useScopedI18n: () => (key: string) => key,
params ? `${key}:${Object.values(params).join(",")}` : key,
}));
vi.mock("../upload-media/upload-media", () => ({
UploadMedia: ({
children,
onSuccess,
}: {
children: (props: object) => unknown;
onSuccess: (medias: unknown) => void;
}) =>
children({
loading: false,
onClick: () => {
uploadSelection();
onSuccess([{ id: "uploaded", url: "/api/user-medias/uploaded" }]);
},
}),
})); }));
vi.mock("../upload-media/upload-media", () => ({ UploadMedia: () => null }));
import { IconPicker } from "./icon-picker"; import { IconPicker } from "./icon-picker";
const directImageUrl = "https://cdn.example.com/shopify.svg"; const directIconUrl = "https://cdn.example.com/shopify.svg";
const iconGroups = [
{
id: "remote",
slug: "dashboard-icons",
icons: [
{ id: "png", name: "shopify.png", url: "https://cdn.example.com/shopify.png" },
{ id: "svg", name: "shopify.svg", url: "https://cdn.example.com/shopify.svg" },
],
},
{
id: "local",
slug: "local",
icons: [{ id: "local-icon", name: "my-shop.png", url: "/api/user-medias/local-icon" }],
},
];
const setInputValue = (input: HTMLInputElement, value: string) => { const setInputValue = (input: HTMLInputElement, value: string) => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
@@ -90,18 +37,6 @@ const setInputValue = (input: HTMLInputElement, value: string) => {
input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("input", { bubbles: true }));
}; };
const pressKey = (input: HTMLInputElement, key: string, init?: KeyboardEventInit) => {
input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));
};
const focusInput = async (input: HTMLInputElement) => {
await act(async () => input.focus());
};
const advanceDebounce = async () => {
await act(async () => vi.advanceTimersByTimeAsync(300));
};
describe("IconPicker", () => { describe("IconPicker", () => {
let container: HTMLDivElement; let container: HTMLDivElement;
let root: Root; let root: Root;
@@ -110,9 +45,9 @@ describe("IconPicker", () => {
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { value: true, writable: true }); Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { value: true, writable: true });
Object.defineProperty(window, "matchMedia", { Object.defineProperty(window, "matchMedia", {
writable: true, writable: true,
value: (media: string) => ({ value: (query: string) => ({
matches: false, matches: false,
media, media: query,
onchange: null, onchange: null,
addListener: () => undefined, addListener: () => undefined,
removeListener: () => undefined, removeListener: () => undefined,
@@ -121,186 +56,54 @@ describe("IconPicker", () => {
dispatchEvent: () => false, dispatchEvent: () => false,
}), }),
}); });
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { value: () => undefined, writable: true });
}); });
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers();
findIconsQuery.mockClear(); findIconsQuery.mockClear();
refetch.mockClear();
uploadSelection.mockClear();
sessionPermissions.current = [];
queryResult = { data: emptyResult, isLoading: false, isFetching: false, isError: false };
}); });
afterEach(() => { afterEach(() => {
act(() => root.unmount()); root.unmount();
container.remove(); container.remove();
document.querySelectorAll("[data-combobox-dropdown]").forEach((element) => element.remove());
vi.useRealTimers();
}); });
const renderPicker = async ( const renderPicker = async (onChange: (value: string) => void) => {
onChange: (value: string) => void,
props: Partial<React.ComponentProps<typeof IconPicker>> = {},
) => {
container = document.createElement("div"); container = document.createElement("div");
document.body.appendChild(container); document.body.appendChild(container);
root = createRoot(container); root = createRoot(container);
await act(async () => { await act(async () => {
root.render(createElement(MantineProvider, null, createElement(IconPicker, { value: "", onChange, ...props }))); root.render(createElement(MantineProvider, null, createElement(IconPicker, { value: "", onChange })));
}); });
const input = container.querySelector("input"); const input = container.querySelector("input");
if (!input) throw new Error("Icon picker input was not rendered"); if (!input) throw new Error("Icon picker input was not rendered");
return input; return input;
}; };
test("clears an existing value without restoring it", async () => { test("keeps a direct URL visible without searching the icon repositories", async () => {
const onChange = vi.fn(); const onChange = vi.fn();
const input = await renderPicker(onChange, { value: directImageUrl }); const input = await renderPicker(onChange);
await act(async () => setInputValue(input, "")); await act(async () => {
setInputValue(input, directIconUrl);
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(onChange).toHaveBeenCalledWith(""); expect(onChange).toHaveBeenCalledWith(directIconUrl);
expect(input.value).toBe(""); expect(input.value).toBe(directIconUrl);
expect(findIconsQuery.mock.calls.some(([query]) => query.searchText === directIconUrl)).toBe(false);
}); });
test.each([{ metaKey: true }, { ctrlKey: true }])( test("keeps icon names in repository search mode", async () => {
"clears the entire value with a line-delete shortcut", const onChange = vi.fn();
async (modifier) => { const input = await renderPicker(onChange);
const onChange = vi.fn();
const input = await renderPicker(onChange, { value: directImageUrl });
await act(async () => pressKey(input, "Backspace", modifier)); await act(async () => {
setInputValue(input, "shopify");
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(onChange).toHaveBeenCalledWith(""); expect(onChange).not.toHaveBeenCalled();
expect(input.value).toBe(""); expect(input.value).toBe("shopify");
},
);
test("debounces repository searches", async () => {
const input = await renderPicker(vi.fn());
findIconsQuery.mockClear();
await act(async () => setInputValue(input, "shopify"));
expect(findIconsQuery.mock.calls.some(([query]) => query.searchText === "shopify")).toBe(false);
await advanceDebounce();
expect(findIconsQuery.mock.calls.some(([query]) => query.searchText === "shopify")).toBe(true); expect(findIconsQuery.mock.calls.some(([query]) => query.searchText === "shopify")).toBe(true);
}); });
test("pre-searches the suggested app name when opened", async () => {
const input = await renderPicker(vi.fn(), { suggestedSearch: "Jellyfin" });
await focusInput(input);
expect(input.value).toBe("Jellyfin");
await advanceDebounce();
expect(findIconsQuery.mock.calls.some(([query]) => query.searchText === "Jellyfin")).toBe(true);
});
test("shows local images before SVG and raster library images", async () => {
queryResult = { data: { icons: iconGroups, countIcons: 3 }, isLoading: false, isFetching: false, isError: false };
const input = await renderPicker(vi.fn());
await focusInput(input);
const content = document.body.textContent ?? "";
expect(document.body.querySelector('[role="listbox"]')?.getAttribute("aria-label")).toBe("iconPicker.results");
expect(content.indexOf("iconPicker.localImages")).toBeLessThan(content.indexOf("iconPicker.svgIcons"));
expect(content.indexOf("iconPicker.svgIcons")).toBeLessThan(content.indexOf("iconPicker.otherImages"));
});
test("selects a library image with a pointer", async () => {
queryResult = { data: { icons: iconGroups, countIcons: 3 }, isLoading: false, isFetching: false, isError: false };
const onChange = vi.fn();
const input = await renderPicker(onChange);
await focusInput(input);
const option = document.body.querySelector<HTMLElement>(
'[data-combobox-option][value="/api/user-medias/local-icon"]',
);
if (!option) throw new Error("Local image option was not rendered");
await act(async () => option.click());
expect(onChange).toHaveBeenCalledWith("/api/user-medias/local-icon");
expect(input.value).toBe("/api/user-medias/local-icon");
});
test("selects a library image with the keyboard", async () => {
queryResult = { data: { icons: iconGroups, countIcons: 3 }, isLoading: false, isFetching: false, isError: false };
const onChange = vi.fn();
const input = await renderPicker(onChange);
await focusInput(input);
await act(async () => pressKey(input, "ArrowDown"));
await act(async () => pressKey(input, "Enter"));
expect(onChange).toHaveBeenCalledWith("/api/user-medias/local-icon");
});
test("keeps a direct URL visible and reports a successful preview", async () => {
const onChange = vi.fn();
const input = await renderPicker(onChange);
await act(async () => setInputValue(input, directImageUrl));
expect(onChange).toHaveBeenCalledWith(directImageUrl);
expect(input.value).toBe(directImageUrl);
expect(findIconsQuery.mock.calls.at(-1)?.[1]).toMatchObject({ enabled: false });
expect(document.body.textContent).toContain("iconPicker.urlLoading");
const preview = document.body.querySelector('[data-testid="direct-url-preview"]');
if (!preview) throw new Error("Direct URL preview was not rendered");
await act(async () => preview.dispatchEvent(new Event("load")));
expect(document.body.textContent).toContain("iconPicker.urlReady");
});
test("keeps a failed direct URL editable and shows an error", async () => {
const input = await renderPicker(vi.fn());
await act(async () => setInputValue(input, "https://invalid.example/image.png"));
const preview = document.body.querySelector('[data-testid="direct-url-preview"]');
if (!preview) throw new Error("Direct URL preview was not rendered");
await act(async () => preview.dispatchEvent(new Event("error")));
expect(input.value).toBe("https://invalid.example/image.png");
expect(document.body.textContent).toContain("iconPicker.urlError");
});
test("restores the committed value when an unfinished search is cancelled", async () => {
const input = await renderPicker(vi.fn(), { value: directImageUrl });
await act(async () => setInputValue(input, "unfinished search"));
await act(async () => pressKey(input, "Escape"));
expect(input.value).toBe(directImageUrl);
});
test("offers retry when the repository search fails", async () => {
queryResult = { data: undefined, isLoading: false, isFetching: false, isError: true };
const input = await renderPicker(vi.fn());
await focusInput(input);
const retry = Array.from(document.body.querySelectorAll("button")).find(
(button) => button.textContent === "action.tryAgain",
);
if (!retry) throw new Error("Retry button was not rendered");
await act(async () => retry.click());
expect(refetch).toHaveBeenCalledOnce();
});
test("selects an uploaded local image when the user has permission", async () => {
sessionPermissions.current = ["media-upload"];
const onChange = vi.fn();
await renderPicker(onChange);
const upload = container.querySelector<HTMLButtonElement>('[aria-label="iconPicker.uploadImage"]');
if (!upload) throw new Error("Upload button was not rendered");
await act(async () => upload.click());
expect(uploadSelection).toHaveBeenCalledOnce();
expect(onChange).toHaveBeenCalledWith("/api/user-medias/uploaded");
});
}); });
@@ -1,36 +1,27 @@
"use client"; "use client";
import type { FocusEventHandler, KeyboardEventHandler } from "react"; import type { FocusEventHandler } from "react";
import { startTransition, useEffect, useMemo, useState } from "react"; import { startTransition, useEffect, useState } from "react";
import { import {
ActionIcon, ActionIcon,
Box, Box,
Button, Button,
CloseButton, Card,
Combobox, Combobox,
Flex,
Group, Group,
Image, Image,
Indicator,
InputBase, InputBase,
Loader,
Paper, Paper,
SimpleGrid,
Skeleton, Skeleton,
Stack, Stack,
Text, Text,
ThemeIcon, UnstyledButton,
Tooltip,
useCombobox, useCombobox,
} from "@mantine/core"; } from "@mantine/core";
import { useDebouncedValue, useUncontrolled } from "@mantine/hooks"; import { useDebouncedValue, useUncontrolled } from "@mantine/hooks";
import { import { IconMoodEmpty, IconSearchOff, IconUpload } from "@tabler/icons-react";
IconCheck,
IconCloud,
IconMoodEmpty,
IconPhoto,
IconPhotoOff,
IconSearchOff,
IconUpload,
} from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client"; import { useSession } from "@homarr/auth/client";
@@ -38,7 +29,6 @@ import { supportedLanguages } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { UploadMedia } from "../upload-media/upload-media"; import { UploadMedia } from "../upload-media/upload-media";
import { arrangeIconPickerSections, isDirectImageUrl, isImageSource, isSvgImage } from "./icon-picker.utils";
import classes from "./icon-picker.module.css"; import classes from "./icon-picker.module.css";
interface IconPickerProps { interface IconPickerProps {
@@ -49,12 +39,9 @@ interface IconPickerProps {
onBlur?: FocusEventHandler; onBlur?: FocusEventHandler;
label?: string; label?: string;
placeholder?: string; placeholder?: string;
suggestedSearch?: string | null;
withAsterisk?: boolean; withAsterisk?: boolean;
} }
type PreviewState = "idle" | "loading" | "ready" | "error";
export const IconPicker = ({ export const IconPicker = ({
value: propsValue, value: propsValue,
onChange, onChange,
@@ -64,403 +51,188 @@ export const IconPicker = ({
withAsterisk = true, withAsterisk = true,
label, label,
placeholder, placeholder,
suggestedSearch,
}: IconPickerProps) => { }: IconPickerProps) => {
const [value, setValue] = useUncontrolled({ value: propsValue, onChange, defaultValue: "" }); const [value, setValue] = useUncontrolled({ value: propsValue, onChange });
const [draft, setDraft] = useState(propsValue ?? ""); const [query, setQuery] = useState("");
const [hasEdited, setHasEdited] = useState(false);
const [keyboardIndex, setKeyboardIndex] = useState(-1); useEffect(() => {
const [previewState, setPreviewState] = useState<PreviewState>("idle"); setQuery("");
}, [value]);
const { data: session } = useSession(); const { data: session } = useSession();
const tCommon = useScopedI18n("common"); const tCommon = useScopedI18n("common");
const [debouncedDraft] = useDebouncedValue(draft, 250); const [debouncedQuery] = useDebouncedValue(query, 100);
const directUrl = isDirectImageUrl(draft) ? draft.trim() : null; const searchText = !isDirectIconUrl(debouncedQuery) && debouncedQuery !== (value ?? "") ? debouncedQuery : "";
const isCommittedValueDraft = debouncedDraft === (value ?? "");
const searchText = directUrl !== null || isCommittedValueDraft ? "" : debouncedDraft.trim();
const canUpload = session?.user.permissions.includes("media-upload") ?? false;
const query = clientApi.icon.findIcons.useQuery( const { data, isLoading, isError, refetch } = clientApi.icon.findIcons.useQuery(
{ searchText, limitPerGroup: 24 }, { searchText },
{ enabled: directUrl === null, placeholderData: (previous) => previous }, { placeholderData: (prev) => prev },
); );
const combobox = useCombobox({ const combobox = useCombobox({
onDropdownClose: () => combobox.resetSelectedOption(), onDropdownClose: () => combobox.resetSelectedOption(),
onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"),
}); });
useEffect(() => { const totalOptions = data?.icons.reduce((acc, group) => acc + group.icons.length, 0) ?? 0;
setDraft(value ?? ""); const groups = data?.icons.map((group) => {
setHasEdited(false); const options = group.icons.map((item) => (
}, [value]); <Combobox.Option
key={item.id}
useEffect(() => { value={item.url}
setPreviewState(directUrl ? "loading" : "idle"); p={0}
}, [directUrl]); h="calc(2*var(--mantine-spacing-sm)+25px)"
w="calc(2*var(--mantine-spacing-sm)+25px)"
const sections = useMemo( >
() => arrangeIconPickerSections(query.data?.icons ?? [], searchText), <UnstyledButton
[query.data?.icons, searchText], onClick={() => {
); startTransition(() => {
const orderedOptions = useMemo( setValue(item.url);
() => [...sections.local, ...sections.svg, ...sections.other], setQuery("");
[sections.local, sections.svg, sections.other], combobox.closeDropdown();
); });
const totalOptions = sections.local.length + sections.svg.length + sections.other.length; }}
>
const commitValue = (nextValue: string) => { <Indicator label="SVG" disabled={!item.url.endsWith(".svg")} size={16}>
startTransition(() => { <Card p="sm" pos="relative" style={{ overflow: "visible", cursor: "pointer" }} className={classes.iconCard}>
setValue(nextValue); <Box w={25} h={25}>
setDraft(nextValue); <Image src={item.url} w={25} h={25} />
setHasEdited(false); </Box>
setKeyboardIndex(-1); </Card>
}); </Indicator>
}; </UnstyledButton>
</Combobox.Option>
const clearValue = () => { ));
commitValue("");
combobox.openDropdown("keyboard");
};
const openWithSuggestedSearch = () => {
if (!draft && !value && !hasEdited && suggestedSearch?.trim()) {
setDraft(suggestedSearch.trim());
}
combobox.openDropdown();
};
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "Backspace") {
event.preventDefault();
clearValue();
return;
}
if (event.key === "Escape") {
setDraft(value ?? "");
setHasEdited(false);
combobox.closeDropdown("keyboard");
return;
}
if (!directUrl && orderedOptions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
event.preventDefault();
combobox.openDropdown("keyboard");
setKeyboardIndex((current) => {
const next =
event.key === "ArrowDown"
? current >= orderedOptions.length - 1
? 0
: current + 1
: current <= 0
? orderedOptions.length - 1
: current - 1;
combobox.selectOption(next);
return next;
});
return;
}
if (event.key === "Enter") {
if (keyboardIndex >= 0 && orderedOptions[keyboardIndex]) {
event.preventDefault();
commitValue(orderedOptions[keyboardIndex].url);
combobox.closeDropdown("keyboard");
} else if (isImageSource(draft)) {
event.preventDefault();
commitValue(draft.trim());
combobox.closeDropdown("keyboard");
}
}
};
const renderIconOptions = (icons: typeof sections.local, offset: number) => (
<SimpleGrid className={classes.iconGrid} spacing={6} verticalSpacing={6}>
{icons.map((icon, index) => (
<Tooltip key={icon.id} label={`${icon.name} · ${icon.repositorySlug}`} openDelay={500}>
<Combobox.Option
value={icon.url}
aria-label={icon.name}
active={icon.url === value || keyboardIndex === offset + index}
className={classes.iconOption}
>
<Image src={icon.url} alt="" w={30} h={30} fit="contain" fallbackSrc="/logo/logo.png" />
{isSvgImage(icon.url) && <span className={classes.formatBadge}>SVG</span>}
</Combobox.Option>
</Tooltip>
))}
</SimpleGrid>
);
const renderSearchResults = () => {
if (query.isError) {
return (
<PickerMessage
icon={<IconSearchOff size={22} />}
title={tCommon("iconPicker.error")}
action={
<Button size="xs" variant="default" onClick={() => query.refetch()}>
{tCommon("action.tryAgain")}
</Button>
}
/>
);
}
if (query.isLoading) {
return (
<SimpleGrid className={classes.iconGrid} spacing={6} verticalSpacing={6} p="xs">
{Array.from({ length: 12 }, (_, index) => (
<Skeleton key={index} height={52} radius="md" />
))}
</SimpleGrid>
);
}
if (totalOptions === 0) {
return (
<PickerMessage
icon={<IconMoodEmpty size={22} />}
title={tCommon("iconPicker.noResults", { search: debouncedDraft.trim() })}
/>
);
}
return ( return (
<Stack gap="sm" p="xs"> <Paper p="xs" key={group.slug} pt={2}>
{sections.local.length > 0 && ( <Text mb={8} size="sm" fw="bold">
<PickerSection icon={<IconPhoto size={15} />} label={tCommon("iconPicker.localImages")}> {group.slug}
{renderIconOptions(sections.local, 0)} </Text>
</PickerSection> <Flex gap={8} wrap={"wrap"}>
)} {options}
{sections.svg.length > 0 && ( </Flex>
<PickerSection label={tCommon("iconPicker.svgIcons")} badge="SVG"> </Paper>
{renderIconOptions(sections.svg, sections.local.length)} );
</PickerSection> });
)}
{sections.other.length > 0 && ( const inputValue = query || value || "";
<PickerSection icon={<IconCloud size={15} />} label={tCommon("iconPicker.otherImages")}> const leftSection = shouldShowPreview(value) && <img src={value} alt="" style={{ width: 20, height: 20 }} />;
{renderIconOptions(sections.other, sections.local.length + sections.svg.length)} const placeholderText =
</PickerSection> placeholder ||
)} (data && tCommon("iconPicker.header", { countIcons: String(data.countIcons) })) ||
tCommon("iconPicker.headerLoading");
const renderDropdown = () => {
if (isError) {
return (
<Stack align="center" gap="xs" p="md">
<IconSearchOff size={32} stroke={1.5} />
<Text size="sm">{tCommon("iconPicker.error")}</Text>
<Button size="xs" variant="default" onClick={() => refetch()}>
{tCommon("action.tryAgain")}
</Button>
</Stack>
);
}
if (isLoading) {
return Array(15)
.fill(0)
.map((_, index) => (
<Combobox.Option value={`skeleton-${index}`} key={index} disabled>
<Skeleton height={25} visible />
</Combobox.Option>
));
}
if (totalOptions > 0) {
return <Stack gap={4}>{groups}</Stack>;
}
return (
<Stack align="center" gap="xs" p="md">
<IconMoodEmpty size={32} stroke={1.5} />
<Text size="sm">{tCommon("iconPicker.noResults", { search: debouncedQuery })}</Text>
</Stack> </Stack>
); );
}; };
const leftSection = (() => {
if (directUrl && previewState === "loading") return <Loader size={15} />;
if (directUrl && previewState === "error") return <IconPhotoOff size={17} color="var(--mantine-color-red-6)" />;
if (shouldShowPreview(value)) {
return (
<Image
src={value}
alt=""
w={22}
h={22}
fit="contain"
onLoad={() => directUrl && setPreviewState("ready")}
onError={() => directUrl && setPreviewState("error")}
/>
);
}
return <IconPhoto size={17} stroke={1.5} />;
})();
const placeholderText =
placeholder ??
(query.data
? tCommon("iconPicker.header", { countIcons: String(query.data.countIcons) })
: tCommon("iconPicker.headerLoading"));
return ( return (
<Combobox <Combobox store={combobox} withinPortal>
store={combobox} <Combobox.Target>
withinPortal <Group wrap="nowrap" gap="xs" w="100%" align="start">
resetSelectionOnOptionHover <InputBase
onOptionSubmit={(url) => { flex={1}
commitValue(url); rightSection={<Combobox.Chevron />}
combobox.closeDropdown(); leftSection={leftSection}
}} value={inputValue}
> onChange={(event) => {
<Combobox.Target withExpandedAttribute> const nextValue = event.currentTarget.value;
<InputBase const trimmedValue = nextValue.trim();
flex={1} setQuery(nextValue);
leftSection={leftSection} if (isDirectIconUrl(trimmedValue)) {
rightSection={ setValue(trimmedValue);
<Group gap={2} wrap="nowrap"> combobox.closeDropdown();
{canUpload && ( } else {
<UploadMedia combobox.openDropdown();
onSuccess={(medias) => { }
const first = medias.at(0); }}
if (!first) return; onClick={() => combobox.openDropdown()}
commitValue(first.url); onFocus={(event) => {
combobox.closeDropdown(); onFocus?.(event);
}} combobox.openDropdown();
> }}
{({ onClick, loading }) => ( onBlur={(event) => {
<Tooltip label={tCommon("iconPicker.uploadImage")}> onBlur?.(event);
<ActionIcon combobox.closeDropdown();
onClick={(event) => { setQuery("");
event.stopPropagation(); }}
onClick(); rightSectionPointerEvents="none"
}} withAsterisk={withAsterisk}
loading={loading} error={error}
size="sm" label={label ?? tCommon("iconPicker.label")}
variant="subtle" placeholder={placeholderText}
aria-label={tCommon("iconPicker.uploadImage")} />
> {session?.user.permissions.includes("media-upload") && (
<IconUpload size={16} stroke={1.5} /> <UploadMedia
</ActionIcon> onSuccess={(medias) => {
</Tooltip> const first = medias.at(0);
)} if (!first) return;
</UploadMedia> startTransition(() => {
setValue(first.url);
});
}}
>
{({ onClick, loading }) => (
<ActionIcon onClick={onClick} loading={loading} mt={24} size={36} variant="default">
<IconUpload size={16} stroke={1.5} />
</ActionIcon>
)} )}
{(draft || value) && ( </UploadMedia>
<CloseButton )}
size="sm" </Group>
aria-label={tCommon("iconPicker.clear")}
onMouseDown={(event) => event.preventDefault()}
onClick={clearValue}
/>
)}
{query.isFetching && !directUrl ? <Loader size={14} /> : <Combobox.Chevron />}
</Group>
}
rightSectionWidth={canUpload ? 86 : 56}
rightSectionPointerEvents="all"
value={draft}
onChange={(event) => {
const nextValue = event.currentTarget.value;
setDraft(nextValue);
setHasEdited(true);
setKeyboardIndex(-1);
combobox.openDropdown("keyboard");
combobox.updateSelectedOptionIndex();
if (!nextValue) {
setValue("");
} else if (isImageSource(nextValue)) {
setValue(nextValue.trim());
}
}}
onKeyDown={handleKeyDown}
onClick={openWithSuggestedSearch}
onFocus={(event) => {
onFocus?.(event);
openWithSuggestedSearch();
}}
onBlur={(event) => {
onBlur?.(event);
combobox.closeDropdown();
setDraft(value ?? "");
setHasEdited(false);
}}
withAsterisk={withAsterisk}
error={error}
label={label ?? tCommon("iconPicker.label")}
description={tCommon("iconPicker.description")}
styles={{
description: { color: "var(--mantine-color-text)" },
input: { color: "var(--mantine-color-text)" },
error: { color: "light-dark(var(--mantine-color-red-9), var(--mantine-color-red-2))" },
}}
placeholder={placeholderText}
autoComplete="off"
spellCheck={false}
/>
</Combobox.Target> </Combobox.Target>
<Combobox.Dropdown className={classes.dropdown}> <Combobox.Dropdown>
<Combobox.Options className={classes.options} aria-label={tCommon("iconPicker.results")}> <Combobox.Options mah={350} style={{ overflowY: "auto" }}>
{directUrl ? ( {renderDropdown()}
<Paper p="sm" m="xs" className={classes.urlPreview}>
<Group wrap="nowrap" align="center">
<Box className={classes.previewFrame}>
{previewState === "loading" && <Loader size={18} className={classes.previewLoader} />}
{previewState === "error" ? (
<ThemeIcon variant="light" color="red" size={40}>
<IconPhotoOff size={21} />
</ThemeIcon>
) : (
<Image
src={directUrl}
alt=""
w={40}
h={40}
fit="contain"
data-testid="direct-url-preview"
onLoad={() => setPreviewState("ready")}
onError={() => setPreviewState("error")}
/>
)}
</Box>
<Box flex={1} miw={0}>
<Text size="sm" fw={600}>
{previewState === "error"
? tCommon("iconPicker.urlError")
: previewState === "ready"
? tCommon("iconPicker.urlReady")
: tCommon("iconPicker.urlLoading")}
</Text>
<Text size="xs" truncate>
{directUrl}
</Text>
</Box>
{previewState === "ready" && (
<ThemeIcon variant="light" color="green" size="sm" aria-hidden>
<IconCheck size={14} />
</ThemeIcon>
)}
</Group>
</Paper>
) : (
renderSearchResults()
)}
</Combobox.Options> </Combobox.Options>
</Combobox.Dropdown> </Combobox.Dropdown>
</Combobox> </Combobox>
); );
}; };
interface PickerSectionProps { // This regex is used to prevent loading a preview like en or /en which would trigger a language change
label: string; // See https://github.com/homarr-labs/homarr/issues/3070
icon?: React.ReactNode;
badge?: string;
children: React.ReactNode;
}
const PickerSection = ({ label, icon, badge, children }: PickerSectionProps) => (
<Stack gap={6}>
<Group gap={6} px={2}>
{icon}
<Text size="xs" fw={600}>
{label}
</Text>
{badge && <span className={classes.sectionBadge}>{badge}</span>}
</Group>
{children}
</Stack>
);
interface PickerMessageProps {
icon: React.ReactNode;
title: string;
action?: React.ReactNode;
}
const PickerMessage = ({ icon, title, action }: PickerMessageProps) => (
<Stack align="center" gap="xs" p="lg" ta="center">
<ThemeIcon variant="light" color="gray" size="lg">
{icon}
</ThemeIcon>
<Text size="sm">{title}</Text>
{action}
</Stack>
);
const localizationPathRegex = new RegExp(`^/?(${supportedLanguages.join("|")})(/.*)?$`, "i"); const localizationPathRegex = new RegExp(`^/?(${supportedLanguages.join("|")})(/.*)?$`, "i");
const shouldShowPreview = (value: string | null | undefined): value is string => { const shouldShowPreview = (value: string | null | undefined): value is string => {
if (!value) return false; if (!value) return false;
return !localizationPathRegex.test(value); return !localizationPathRegex.test(value);
}; };
const isDirectIconUrl = (value: string) => {
try {
const url = new URL(value.trim());
return (url.protocol === "http:" || url.protocol === "https:") && Boolean(url.hostname);
} catch {
return false;
}
};
@@ -1,50 +0,0 @@
import { describe, expect, test } from "vitest";
import type { IconGroup } from "./icon-picker.utils";
import { arrangeIconPickerSections, isDirectImageUrl, isImageSource, isSvgImage } from "./icon-picker.utils";
const groups = [
{
id: "remote",
slug: "dashboard-icons",
icons: [
{ id: "long", name: "home-assistant-alt.svg", url: "https://cdn.example.com/home-assistant-alt.svg" },
{ id: "raster", name: "Home Assistant.png", url: "https://cdn.example.com/home-assistant.png" },
{ id: "svg", name: "home-assistant.svg", url: "https://cdn.example.com/home-assistant.svg?v=1" },
],
},
{
id: "local",
slug: "local",
icons: [{ id: "local", name: "Home Assistant.png", url: "/api/user-medias/home-assistant" }],
},
] as IconGroup[];
describe("icon picker utilities", () => {
test("arranges local images before remote SVG and raster images", () => {
const result = arrangeIconPickerSections(groups, "home assistant");
expect(result.local.map((icon) => icon.id)).toEqual(["local"]);
expect(result.svg.map((icon) => icon.id)).toEqual(["svg", "long"]);
expect(result.other.map((icon) => icon.id)).toEqual(["raster"]);
});
test.each([
["https://example.com/icon.png", true],
["http://localhost:3000/icon", true],
["ftp://example.com/icon.png", false],
["javascript:alert(1)", false],
["example.com/icon.png", false],
])("validates direct image URLs", (value, expected) => {
expect(isDirectImageUrl(value)).toBe(expected);
});
test("accepts internal image paths without treating search text as a source", () => {
expect(isImageSource("/api/user-medias/123")).toBe(true);
expect(isImageSource("shopify")).toBe(false);
});
test("recognizes SVG URLs with query strings case-insensitively", () => {
expect(isSvgImage("https://example.com/ICON.SVG?raw=1")).toBe(true);
});
});
@@ -1,67 +0,0 @@
import type { inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "@homarr/api";
import { getImageMatchRank, normalizeImageName } from "@homarr/common";
type RouterOutput = inferRouterOutputs<AppRouter>;
export type IconGroup = RouterOutput["icon"]["findIcons"]["icons"][number];
export type PickerIcon = IconGroup["icons"][number] & { repositorySlug: string };
export interface IconPickerSections {
local: PickerIcon[];
svg: PickerIcon[];
other: PickerIcon[];
}
export const arrangeIconPickerSections = (iconGroups: IconGroup[], searchTerm = ""): IconPickerSections => {
const sections: IconPickerSections = { local: [], svg: [], other: [] };
for (const group of iconGroups) {
for (const icon of group.icons) {
const pickerIcon = { ...icon, repositorySlug: group.slug };
if (group.slug === "local") {
sections.local.push(pickerIcon);
} else if (isSvgImage(icon.url)) {
sections.svg.push(pickerIcon);
} else {
sections.other.push(pickerIcon);
}
}
}
const normalizedSearch = normalizeImageName(searchTerm);
if (normalizedSearch) {
const compareMatches = (a: PickerIcon, b: PickerIcon) => {
const aRank = getImageMatchRank(normalizedSearch, a.name || a.url) ?? Number.MAX_SAFE_INTEGER;
const bRank = getImageMatchRank(normalizedSearch, b.name || b.url) ?? Number.MAX_SAFE_INTEGER;
return aRank - bRank || a.name.localeCompare(b.name);
};
return {
local: sections.local.toSorted(compareMatches),
svg: sections.svg.toSorted(compareMatches),
other: sections.other.toSorted(compareMatches),
};
}
return sections;
};
export const isDirectImageUrl = (value: string) => {
try {
const url = new URL(value.trim());
return (url.protocol === "http:" || url.protocol === "https:") && Boolean(url.hostname);
} catch {
return false;
}
};
export const isImageSource = (value: string) => isDirectImageUrl(value) || value.trim().startsWith("/");
export const isSvgImage = (value: string) => {
try {
const url = new URL(value, "http://homarr.local");
return url.pathname.toLowerCase().endsWith(".svg");
} catch {
return value.toLowerCase().split(/[?#]/, 1)[0]?.endsWith(".svg") ?? false;
}
};
+1
View File
@@ -2,6 +2,7 @@ export * from "./new-app/_app-new-form";
export * from "./new-app/_form"; export * from "./new-app/_form";
export * from "./icon-picker/icon-picker"; export * from "./icon-picker/icon-picker";
export * from "./new-app/icon-matcher";
export * from "./upload-media/upload-media"; export * from "./upload-media/upload-media";
@@ -3,15 +3,17 @@
import type { ChangeEventHandler } from "react"; import type { ChangeEventHandler } from "react";
import { useEffect, useImperativeHandle, useRef } from "react"; import { useEffect, useImperativeHandle, useRef } from "react";
import { Button, Checkbox, Collapse, Group, Stack, Textarea, TextInput } from "@mantine/core"; import { Button, Checkbox, Collapse, Group, Stack, Textarea, TextInput } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks"; import { useDebouncedValue, useDisclosure } from "@mantine/hooks";
import type { z } from "zod/v4"; import type { z } from "zod/v4";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui"; import { Link } from "@homarr/ui";
import { appManageSchema } from "@homarr/validation/app"; import { appManageSchema } from "@homarr/validation/app";
import { IconPicker } from "../icon-picker/icon-picker"; import { IconPicker } from "../icon-picker/icon-picker";
import { findBestIconMatch } from "./icon-matcher";
type FormType = z.infer<typeof appManageSchema>; type FormType = z.infer<typeof appManageSchema>;
@@ -79,6 +81,9 @@ export const AppForm = ({
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValuesKey]); }, [initialValuesKey]);
// Debounce the name value with 200ms delay
const [debouncedName] = useDebouncedValue(form.values.name, 200);
const shouldCreateAnother = useRef(false); const shouldCreateAnother = useRef(false);
const handleSubmit = (values: FormType) => { const handleSubmit = (values: FormType) => {
const redirect = !shouldCreateAnother.current; const redirect = !shouldCreateAnother.current;
@@ -125,13 +130,29 @@ export const AppForm = ({
} }
}; };
// Auto-select icon based on app name with debounced search
const { data: iconsData } = clientApi.icon.findIcons.useQuery(
{
searchText: debouncedName,
},
{
enabled: debouncedName.length > 3,
},
);
useEffect(() => {
if (debouncedName && !form.values.iconUrl && iconsData?.icons) {
const bestMatch = findBestIconMatch(debouncedName, iconsData.icons);
if (bestMatch) {
form.setFieldValue("iconUrl", bestMatch);
}
}
}, [debouncedName, iconsData]);
const formFields = ( const formFields = (
<Stack> <Stack>
<TextInput {...form.getInputProps("name")} withAsterisk label={t("app.field.name.label")} /> <TextInput {...form.getInputProps("name")} withAsterisk label={t("app.field.name.label")} />
<IconPicker <IconPicker {...form.getInputProps("iconUrl")} />
{...form.getInputProps("iconUrl")}
suggestedSearch={initialValues === undefined ? form.values.name : undefined}
/>
<Textarea <Textarea
{...form.getInputProps("description")} {...form.getInputProps("description")}
label={t("app.field.description.label")} label={t("app.field.description.label")}
@@ -0,0 +1,30 @@
import type { inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "@homarr/api";
type RouterOutput = inferRouterOutputs<AppRouter>;
type IconGroupsOutput = RouterOutput["icon"]["findIcons"]["icons"];
export const findBestIconMatch = (searchTerm: string, iconGroups: IconGroupsOutput): string | null => {
const nameLower = searchTerm.toLowerCase();
const allIcons = iconGroups.flatMap((group) => group.icons);
const getIconPriority = (iconUrl: string) => {
const fileName = iconUrl.toLowerCase().split("/").pop()?.split(".")[0];
if (!fileName) return -1;
const isSvg = iconUrl.endsWith(".svg");
const isExactMatch = fileName === nameLower;
if (isExactMatch) return isSvg ? 0 : 1;
if (fileName.includes(nameLower)) return isSvg ? 2 : 3;
return -1;
};
for (let priority = 0; priority <= 3; priority++) {
const match = allIcons.find((icon) => getIconPriority(icon.url) === priority);
if (match) return match.url;
}
return null;
};
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
File diff suppressed because it is too large. Load diff
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "crwdns5493:0crwdne5493:0", "actionButton": "crwdns5493:0crwdne5493:0",
"customJsx": "crwdns5495:0crwdne5495:0" "customJsx": "crwdns5495:0crwdne5495:0"
}, },
"method": {
"GET": "crwdns5497:0crwdne5497:0",
"POST": "crwdns5499:0crwdne5499:0",
"PUT": "crwdns5501:0crwdne5501:0",
"DELETE": "crwdns5503:0crwdne5503:0",
"PATCH": "crwdns5505:0crwdne5505:0"
},
"authType": { "authType": {
"none": "crwdns5507:0crwdne5507:0", "none": "crwdns5507:0crwdne5507:0",
"bearer": "crwdns5509:0crwdne5509:0", "bearer": "crwdns5509:0crwdne5509:0",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Eine Schaltfläche welche eine Anfrage auslöst wenn sie angeklickt wird", "actionButton": "Eine Schaltfläche welche eine Anfrage auslöst wenn sie angeklickt wird",
"customJsx": "Benutzerdefiniertes JSX-Layout mit Whitelist Mantine Komponenten und vollständiger API-Datenbindung" "customJsx": "Benutzerdefiniertes JSX-Layout mit Whitelist Mantine Komponenten und vollständiger API-Datenbindung"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Keine", "none": "Keine",
"bearer": "Bearer Token", "bearer": "Bearer Token",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "A button that triggers a request when clicked", "actionButton": "A button that triggers a request when clicked",
"customJsx": "Custom JSX layout using whitelisted Mantine components with full API data binding" "customJsx": "Custom JSX layout using whitelisted Mantine components with full API data binding"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "None", "none": "None",
"bearer": "Bearer Token", "bearer": "Bearer Token",
+2 -19
View File
@@ -824,13 +824,6 @@
"actionButton": "A button that triggers a request when clicked", "actionButton": "A button that triggers a request when clicked",
"customJsx": "Custom JSX layout using whitelisted Mantine components with full API data binding" "customJsx": "Custom JSX layout using whitelisted Mantine components with full API data binding"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "None", "none": "None",
"bearer": "Bearer Token", "bearer": "Bearer Token",
@@ -1437,18 +1430,8 @@
"here": "here", "here": "here",
"iconPicker": { "iconPicker": {
"label": "Icon URL", "label": "Icon URL",
"description": "Search the library, paste an image URL, or upload a file.", "header": "Type name or objects to filter for icons... Homarr will search through {countIcons} icons for you.",
"header": "Search {countIcons} images by name", "headerLoading": "Type to search icons…",
"headerLoading": "Search images by name",
"clear": "Clear image",
"uploadImage": "Upload image",
"results": "Image search results",
"localImages": "Your images",
"svgIcons": "SVG icons",
"otherImages": "Other images",
"urlLoading": "Checking image…",
"urlReady": "Image is ready to use",
"urlError": "This image could not be loaded. Check the URL and try again.",
"noResults": "No icons match \"{search}\".", "noResults": "No icons match \"{search}\".",
"error": "Couldn't load icons." "error": "Couldn't load icons."
}, },
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Painike, joka laukaisee pyynnön napsautettaessa", "actionButton": "Painike, joka laukaisee pyynnön napsautettaessa",
"customJsx": "Mukautettu JSX-asettelu käyttäen sallittuja Mantine-komponentteja täydellä API-tietojen sidonnalla" "customJsx": "Mukautettu JSX-asettelu käyttäen sallittuja Mantine-komponentteja täydellä API-tietojen sidonnalla"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Ei mitään", "none": "Ei mitään",
"bearer": "Bearer-tunniste", "bearer": "Bearer-tunniste",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Un bouton qui déclenche une requête lorsqu'elle est cliquée", "actionButton": "Un bouton qui déclenche une requête lorsqu'elle est cliquée",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Aucun", "none": "Aucun",
"bearer": "Jeton Bearer", "bearer": "Jeton Bearer",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Egy gomb, ami kérés végrehajtását váltja ki kattintásra", "actionButton": "Egy gomb, ami kérés végrehajtását váltja ki kattintásra",
"customJsx": "Egyéni JSX elrendezés engedélyezett Mantine komponensekkel és teljes API adatkötéssel" "customJsx": "Egyéni JSX elrendezés engedélyezett Mantine komponensekkel és teljes API adatkötéssel"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Nincs", "none": "Nincs",
"bearer": "Bearer token", "bearer": "Bearer token",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Un pulsante che attiva una richiesta al clic", "actionButton": "Un pulsante che attiva una richiesta al clic",
"customJsx": "Layout JSX personalizzato che usa componenti Mantine consentiti con binding completo dei dati API" "customJsx": "Layout JSX personalizzato che usa componenti Mantine consentiti con binding completo dei dati API"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Nessuno", "none": "Nessuno",
"bearer": "Token Bearer", "bearer": "Token Bearer",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "클릭 시 요청을 트리거하는 버튼", "actionButton": "클릭 시 요청을 트리거하는 버튼",
"customJsx": "전체 API 데이터 바인딩과 함께 허용된 Mantine 구성 요소를 사용하는 사용자 정의 JSX 레이아웃" "customJsx": "전체 API 데이터 바인딩과 함께 허용된 Mantine 구성 요소를 사용하는 사용자 정의 JSX 레이아웃"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "없음", "none": "없음",
"bearer": "Bearer 토큰", "bearer": "Bearer 토큰",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
+36 -43
View File
@@ -824,13 +824,6 @@
"actionButton": "Przycisk, który wywołuje zapytanie po kliknięciu", "actionButton": "Przycisk, który wywołuje zapytanie po kliknięciu",
"customJsx": "Własny układ JSX za pomocą komponentów Mantine z białej listy z pełnym powiązaniem danych API" "customJsx": "Własny układ JSX za pomocą komponentów Mantine z białej listy z pełnym powiązaniem danych API"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "None", "none": "None",
"bearer": "Bearer Token", "bearer": "Bearer Token",
@@ -2430,19 +2423,19 @@
"label": "Odwróć sortowanie" "label": "Odwróć sortowanie"
}, },
"columnOrder": { "columnOrder": {
"label": "" "label": "Kolejność kolumn"
}, },
"columnWidths": { "columnWidths": {
"label": "" "label": "Szerokości kolumn"
} }
}, },
"error": { "error": {
"internalServerError": "Nie udało się pobrać statystyk kontenerów", "internalServerError": "Nie udało się pobrać statystyk kontenerów",
"layoutSaveTitle": "", "layoutSaveTitle": "Nie zapisano układu tabeli",
"layoutSaveMessage": "" "layoutSaveMessage": "Nie można zapisać układu tabeli Dockera. Spróbuj ponownie przesunąć lub zmienić rozmiar kolumny."
}, },
"empty": { "empty": {
"noContainers": "" "noContainers": "Nie znaleziono kontenerów"
} }
}, },
"coolify": { "coolify": {
@@ -2738,17 +2731,17 @@
"description": "Wyłączenie tej opcji nie zadziała w przypadku Plex" "description": "Wyłączenie tej opcji nie zadziała w przypadku Plex"
}, },
"showBitrate": { "showBitrate": {
"label": "", "label": "Pokaż bitrate",
"description": "" "description": "Pokaż bieżącą przepływność odtwarzania obok lokalizacji"
}, },
"showLocation": { "showLocation": {
"label": "", "label": "Pokaż lokalizację",
"description": "" "description": "Pokaż, czy strumień jest w sieci LAN, czy WAN"
} }
}, },
"footer": { "footer": {
"streams": "", "streams": "{count, plural, one {# aktywny strumień} few {# aktywne strumienie} many {# aktywnych strumieni} other {# aktywnych strumieni}}",
"totalBitrate": "" "totalBitrate": "Łącznie: {bitrate}"
}, },
"items": { "items": {
"currentlyPlaying": "Obecnie odtwarzane", "currentlyPlaying": "Obecnie odtwarzane",
@@ -2757,9 +2750,9 @@
"id": "ID", "id": "ID",
"status": "Status", "status": "Status",
"directPlay": "Odtwarzanie bezpośrednie", "directPlay": "Odtwarzanie bezpośrednie",
"directStream": "", "directStream": "Bezpośredni strumień",
"transcodeVideo": "", "transcodeVideo": "Transkodowanie wideo",
"transcodeAudio": "", "transcodeAudio": "Transkodowanie audio",
"transcoding": "Transkodowanie", "transcoding": "Transkodowanie",
"paused": "Zatrzymane", "paused": "Zatrzymane",
"remaining": "{minutes} min pozostało", "remaining": "{minutes} min pozostało",
@@ -3107,18 +3100,18 @@
"description": "To ograniczy liczbę wyświetlanych elementów dla każdej integracji, a nie globalnie." "description": "To ograniczy liczbę wyświetlanych elementów dla każdej integracji, a nie globalnie."
}, },
"columnOrder": { "columnOrder": {
"label": "" "label": "Kolejność kolumn"
}, },
"columnWidths": { "columnWidths": {
"label": "" "label": "Szerokości kolumn"
} }
}, },
"errors": { "errors": {
"noColumns": "Wybierz kolumny w elementach", "noColumns": "Wybierz kolumny w elementach",
"noCommunications": "Nie można załadować danych z integracji", "noCommunications": "Nie można załadować danych z integracji",
"noItems": "", "noItems": "Nie znaleziono pobrań",
"actionFailed": "", "actionFailed": "Akcja nie powiodła się",
"actionFailedMessage": "" "actionFailedMessage": "Nie można ukończyć działania. Spróbuj ponownie."
}, },
"items": { "items": {
"actions": { "actions": {
@@ -3142,7 +3135,7 @@
}, },
"id": { "id": {
"columnTitle": "ID", "columnTitle": "ID",
"detailsTitle": "" "detailsTitle": "Identyfikator elementu"
}, },
"integration": { "integration": {
"columnTitle": "Integracja" "columnTitle": "Integracja"
@@ -3177,7 +3170,7 @@
"time": { "time": {
"columnTitle": "Czas zakończenia", "columnTitle": "Czas zakończenia",
"detailsTitle": "Czas od/do zakończenia", "detailsTitle": "Czas od/do zakończenia",
"eta": "" "eta": "Przewidywany czas"
}, },
"type": { "type": {
"columnTitle": "Typ", "columnTitle": "Typ",
@@ -3223,21 +3216,21 @@
}, },
"globalRatio": "Wskaźnik globalny", "globalRatio": "Wskaźnik globalny",
"contextMenu": { "contextMenu": {
"copyName": "", "copyName": "Kopiuj nazwę",
"copyId": "", "copyId": "Kopiuj ID",
"clearFilters": "" "clearFilters": "Wyczyść filtry"
}, },
"footer": { "footer": {
"filter": "" "filter": "Filtruj pobierania"
}, },
"stats": { "stats": {
"show": "", "show": "Pokaż globalne statystyki",
"hide": "", "hide": "Ukryj globalne statystyki",
"overallProgress": "", "overallProgress": "Ogólny postęp kolejki",
"totalSize": "", "totalSize": "Całkowity rozmiar kolejki",
"clients": "" "clients": "{count, plural, one {# klient} few {# klientów} many {# klientów} other {# klientów}}"
}, },
"disconnected": "" "disconnected": "(rozłączono)"
}, },
"mediaReleases": { "mediaReleases": {
"name": "Wydania mediów", "name": "Wydania mediów",
@@ -3968,17 +3961,17 @@
"label": "Pokaż wersję agenta" "label": "Pokaż wersję agenta"
}, },
"columnOrder": { "columnOrder": {
"label": "" "label": "Kolejność kolumn"
}, },
"columnWidths": { "columnWidths": {
"label": "" "label": "Szerokości kolumn"
} }
}, },
"noRecords": "Nie znaleziono systemów", "noRecords": "Nie znaleziono systemów",
"error": { "error": {
"internalServerError": "Nie można połączyć się z Beszel. Sprawdź ustawienia integracji.", "internalServerError": "Nie można połączyć się z Beszel. Sprawdź ustawienia integracji.",
"layoutSaveTitle": "", "layoutSaveTitle": "Nie można zapisać układu tabeli",
"layoutSaveMessage": "" "layoutSaveMessage": "Nie można zapisać kolejności kolumn ani ich szerokości. Spróbuj ponownie."
}, },
"column": { "column": {
"system": "System", "system": "System",
@@ -5376,7 +5369,7 @@
}, },
"remove": { "remove": {
"label": "Usuń", "label": "Usuń",
"confirm": "", "confirm": "Kliknij ponownie, aby trwale usunąć",
"notification": { "notification": {
"success": { "success": {
"title": "Usunięto kontenery", "title": "Usunięto kontenery",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Um botão que aciona uma solicitação quando clicado", "actionButton": "Um botão que aciona uma solicitação quando clicado",
"customJsx": "Layout JSX personalizado usando componentes Mantine na lista branca com ligação completa de dados de API" "customJsx": "Layout JSX personalizado usando componentes Mantine na lista branca com ligação completa de dados de API"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Nenhum", "none": "Nenhum",
"bearer": "Token Bearer", "bearer": "Token Bearer",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Tlačidlo, ktoré po kliknutí spustí požiadavku", "actionButton": "Tlačidlo, ktoré po kliknutí spustí požiadavku",
"customJsx": "Vlastné rozloženie JSX pomocou whitelistovaných komponentov Mantine s plnou väzbou API dát" "customJsx": "Vlastné rozloženie JSX pomocou whitelistovaných komponentov Mantine s plnou väzbou API dát"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Žiadna", "none": "Žiadna",
"bearer": "Bearer token", "bearer": "Bearer token",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Tıklandığında istek başlatan bir düğme", "actionButton": "Tıklandığında istek başlatan bir düğme",
"customJsx": "Tam API veri bağlamasıyla izin verilen Mantine bileşenlerini kullanan özel JSX düzeni" "customJsx": "Tam API veri bağlamasıyla izin verilen Mantine bileşenlerini kullanan özel JSX düzeni"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "Yok", "none": "Yok",
"bearer": "Bearer Token", "bearer": "Bearer Token",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "Кнопка яка виконує запит при натисканні", "actionButton": "Кнопка яка виконує запит при натисканні",
"customJsx": "Користувацький макет JSX з пов'язування повним API даних з білого списку" "customJsx": "Користувацький макет JSX з пов'язування повним API даних з білого списку"
}, },
"method": {
"GET": "ОТРИМАТИ",
"POST": "СТВОРИТИ",
"PUT": "Розміщення",
"DELETE": "ВИДАЛИТИ",
"PATCH": "ПАТЧ"
},
"authType": { "authType": {
"none": "Немає", "none": "Немає",
"bearer": "Пред'явити токен", "bearer": "Пред'явити токен",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "", "actionButton": "",
"customJsx": "" "customJsx": ""
}, },
"method": {
"GET": "",
"POST": "",
"PUT": "",
"DELETE": "",
"PATCH": ""
},
"authType": { "authType": {
"none": "", "none": "",
"bearer": "", "bearer": "",
-7
View File
@@ -824,13 +824,6 @@
"actionButton": "點擊時觸發請求的按鈕", "actionButton": "點擊時觸發請求的按鈕",
"customJsx": "使用白名單 Mantine 組件的自訂 JSX 佈局,具有完整的 API 資料綁定" "customJsx": "使用白名單 Mantine 組件的自訂 JSX 佈局,具有完整的 API 資料綁定"
}, },
"method": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"DELETE": "DELETE",
"PATCH": "PATCH"
},
"authType": { "authType": {
"none": "無", "none": "無",
"bearer": "Bearer 令牌", "bearer": "Bearer 令牌",
@@ -1,6 +1,6 @@
"use client"; "use client";
import React, { useCallback, useMemo, useState } from "react"; import React, { useCallback, useEffect, useMemo, useState } from "react";
import { import {
Accordion, Accordion,
ActionIcon, ActionIcon,
@@ -21,6 +21,7 @@ import {
Tooltip, Tooltip,
} from "@mantine/core"; } from "@mantine/core";
import type { FormErrors } from "@mantine/form"; import type { FormErrors } from "@mantine/form";
import { useDebouncedValue } from "@mantine/hooks";
import { import {
IconAlertTriangleFilled, IconAlertTriangleFilled,
IconBrandDocker, IconBrandDocker,
@@ -47,7 +48,7 @@ import {
normalizeReleaseProviderIdentifier, normalizeReleaseProviderIdentifier,
releaseProviderKinds, releaseProviderKinds,
} from "@homarr/definitions"; } from "@homarr/definitions";
import { IconPicker } from "@homarr/forms-collection"; import { findBestIconMatch, IconPicker } from "@homarr/forms-collection";
import { createModal, useModalAction } from "@homarr/modals"; import { createModal, useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications"; import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
@@ -416,6 +417,13 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [tempRepository, setTempRepository] = useState(() => ({ ...innerProps.repository })); const [tempRepository, setTempRepository] = useState(() => ({ ...innerProps.repository }));
const [formErrors, setFormErrors] = useState<FormErrors>({}); const [formErrors, setFormErrors] = useState<FormErrors>({});
// Allows user to not select an icon by removing the url from the input,
// will only try and get an icon if the name or identifier changes
const [autoSetIcon, setAutoSetIcon] = useState(false);
// Debounce the name value with 200ms delay
const [debouncedName] = useDebouncedValue(tempRepository.name, 800);
const handleConfirm = useCallback(() => { const handleConfirm = useCallback(() => {
setLoading(true); setLoading(true);
@@ -440,6 +448,25 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
setTempRepository((prev) => ({ ...prev, ...changedValue })); setTempRepository((prev) => ({ ...prev, ...changedValue }));
}, []); }, []);
// Auto-select icon based on identifier formatted name with debounced search
const { data: iconsData } = clientApi.icon.findIcons.useQuery(
{
searchText: debouncedName,
},
{
enabled: autoSetIcon && (debouncedName?.length ?? 0) > 3,
},
);
useEffect(() => {
if (autoSetIcon && debouncedName && !tempRepository.iconUrl && iconsData?.icons) {
const bestMatch = findBestIconMatch(debouncedName, iconsData.icons);
if (bestMatch) {
handleChange({ iconUrl: bestMatch });
}
}
}, [debouncedName, iconsData, tempRepository, handleChange, autoSetIcon]);
return ( return (
<Stack> <Stack>
<Group align="start" wrap="nowrap" grow preventGrowOverflow={false}> <Group align="start" wrap="nowrap" grow preventGrowOverflow={false}>
@@ -471,6 +498,8 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
identifier: event.currentTarget.value, identifier: event.currentTarget.value,
name, name,
}); });
if (event.currentTarget.value) setAutoSetIcon(true);
}} }}
error={formErrors[`${innerProps.fieldPath}.identifier`]} error={formErrors[`${innerProps.fieldPath}.identifier`]}
style={{ flex: 0.7 }} style={{ flex: 0.7 }}
@@ -491,7 +520,11 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
<TextInput <TextInput
label={tRepository("name.label")} label={tRepository("name.label")}
value={tempRepository.name ?? ""} value={tempRepository.name ?? ""}
onChange={(event) => handleChange({ name: event.currentTarget.value })} onChange={(event) => {
handleChange({ name: event.currentTarget.value });
if (event.currentTarget.value) setAutoSetIcon(true);
}}
error={formErrors[`${innerProps.fieldPath}.name`]} error={formErrors[`${innerProps.fieldPath}.name`]}
style={{ flex: 0.3 }} style={{ flex: 0.3 }}
/> />
@@ -500,9 +533,9 @@ const RepositoryEditModal = createModal<RepositoryEditProps>(({ innerProps, acti
<IconPicker <IconPicker
withAsterisk={false} withAsterisk={false}
value={tempRepository.iconUrl ?? ""} value={tempRepository.iconUrl ?? ""}
suggestedSearch={tempRepository.name || tempRepository.identifier}
onChange={(url) => { onChange={(url) => {
if (url === "") { if (url === "") {
setAutoSetIcon(false);
handleChange({ iconUrl: undefined }); handleChange({ iconUrl: undefined });
} else { } else {
handleChange({ iconUrl: url }); handleChange({ iconUrl: url });