feat(ui): add situational tips system (#6648)
This commit is contained in:
1 parent
3c2f95d529
commit
f0f9539466
20 files changed
+694
-493
No files matched your search
@@ -1,438 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { AppSelectModal } from "./app-select-modal";
|
||||
|
||||
const AppSelectModalComponent = AppSelectModal.component;
|
||||
|
||||
const sampleApps = [
|
||||
{
|
||||
id: "app-1",
|
||||
name: "Sonarr",
|
||||
description: "Manage TV series downloads",
|
||||
iconUrl: "https://example.com/sonarr.png",
|
||||
href: "http://sonarr.local",
|
||||
},
|
||||
{
|
||||
id: "app-2",
|
||||
name: "Radarr",
|
||||
description: "Manage movie collections",
|
||||
iconUrl: "https://example.com/radarr.png",
|
||||
href: "http://radarr.local",
|
||||
},
|
||||
{
|
||||
id: "app-3",
|
||||
name: "Plex",
|
||||
description: "Stream your media collection",
|
||||
iconUrl: "https://example.com/plex.png",
|
||||
href: "http://plex.local",
|
||||
},
|
||||
];
|
||||
|
||||
const mockUseQuery = vi.fn(() => ({
|
||||
data: sampleApps,
|
||||
isPending: false,
|
||||
}));
|
||||
|
||||
const mockOpenQuickAddAppModal = vi.fn();
|
||||
|
||||
vi.mock("@homarr/api/client", () => ({
|
||||
clientApi: {
|
||||
app: {
|
||||
selectable: {
|
||||
useQuery: () => mockUseQuery(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/modals", async () => {
|
||||
const actual = await vi.importActual<Record<string, unknown>>("@homarr/modals");
|
||||
return {
|
||||
...actual,
|
||||
useModalAction: () => ({
|
||||
openModal: mockOpenQuickAddAppModal,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@homarr/translation/client", () => ({
|
||||
useI18n: () => (key: string, values?: { count?: number }) => {
|
||||
const count = values?.count ?? 0;
|
||||
const translations: Record<string, string> = {
|
||||
"app.action.select.search": "Search apps",
|
||||
"app.action.select.title": "Select application",
|
||||
"app.action.select.selected": "Selected",
|
||||
"app.action.select.toggle": "Click to select",
|
||||
"app.action.select.noResults": "No apps found",
|
||||
"app.action.select.multiSelectTip": "Hold Ctrl or Command to select multiple apps",
|
||||
"app.action.select.selectedCount": `${count} selected`,
|
||||
"app.action.select.appsSelected": `${count} ${count === 1 ? "app" : "apps"} selected`,
|
||||
"app.action.select.customApplication": "Custom application",
|
||||
"app.action.select.application": "Application",
|
||||
"app.action.create.title": "Add custom app",
|
||||
"app.action.create.description": "Configure custom URL and icon",
|
||||
"common.action.discard": "Discard",
|
||||
"common.action.add": "Add",
|
||||
};
|
||||
return translations[key] ?? key;
|
||||
},
|
||||
}));
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
window.matchMedia = vi.fn().mockImplementation(() => ({
|
||||
matches: false,
|
||||
media: "",
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
vi.clearAllMocks();
|
||||
mockUseQuery.mockReturnValue({
|
||||
data: sampleApps,
|
||||
isPending: false,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
describe("AppSelectModal", () => {
|
||||
describe("single selection mode", () => {
|
||||
it("renders app cards with name, description, and icon", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(host.textContent).toContain("Sonarr");
|
||||
expect(host.textContent).toContain("Radarr");
|
||||
expect(host.textContent).toContain("Plex");
|
||||
expect(host.textContent).toContain("Manage TV series downloads");
|
||||
});
|
||||
|
||||
it("selects an app and closes modal when card is clicked", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const sonarrCard = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Sonarr"));
|
||||
expect(sonarrCard).toBeDefined();
|
||||
|
||||
await act(async () => {
|
||||
sonarrCard?.click();
|
||||
});
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(sampleApps[0]);
|
||||
expect(closeModal).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("multi selection mode", () => {
|
||||
it("toggles multiple app selections and submits batch on button click", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelectMany = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelectMany, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const sonarrCard = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Sonarr"));
|
||||
const radarrCard = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Radarr"));
|
||||
|
||||
// Select Sonarr
|
||||
await act(async () => {
|
||||
sonarrCard?.click();
|
||||
});
|
||||
|
||||
// Modal stays open, 1 app selected
|
||||
expect(closeModal).not.toHaveBeenCalled();
|
||||
expect(host.textContent).toContain("1 app selected");
|
||||
|
||||
// Select Radarr
|
||||
await act(async () => {
|
||||
radarrCard?.click();
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("2 apps selected");
|
||||
|
||||
// Submit multi select
|
||||
const submitBtn = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Add (2)"));
|
||||
expect(submitBtn).toBeDefined();
|
||||
|
||||
await act(async () => {
|
||||
submitBtn?.click();
|
||||
});
|
||||
|
||||
expect(onSelectMany).toHaveBeenCalledWith([sampleApps[0], sampleApps[1]]);
|
||||
expect(closeModal).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("unselects an app when clicked a second time", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelectMany = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelectMany, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const sonarrCard = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Sonarr"));
|
||||
|
||||
// Select Sonarr
|
||||
await act(async () => {
|
||||
sonarrCard?.click();
|
||||
});
|
||||
expect(host.textContent).toContain("1 app selected");
|
||||
|
||||
// Unselect Sonarr
|
||||
await act(async () => {
|
||||
sonarrCard?.click();
|
||||
});
|
||||
expect(host.textContent).not.toContain("1 app selected");
|
||||
});
|
||||
|
||||
it("clears selection when Discard button is clicked", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelectMany = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelectMany, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const sonarrCard = Array.from(host.querySelectorAll("button")).find((btn) => btn.textContent?.includes("Sonarr"));
|
||||
await act(async () => {
|
||||
sonarrCard?.click();
|
||||
});
|
||||
expect(host.textContent).toContain("1 app selected");
|
||||
|
||||
const discardBtn = Array.from(host.querySelectorAll("button")).find((btn) =>
|
||||
btn.textContent?.includes("Discard"),
|
||||
);
|
||||
await act(async () => {
|
||||
discardBtn?.click();
|
||||
});
|
||||
|
||||
expect(host.textContent).not.toContain("app selected");
|
||||
});
|
||||
});
|
||||
|
||||
describe("search and filtering", () => {
|
||||
it("filters apps in real-time by search query (case-insensitive)", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const searchInput = host.querySelector("input");
|
||||
expect(searchInput).not.toBeNull();
|
||||
|
||||
// Type "plex"
|
||||
await act(async () => {
|
||||
if (searchInput) {
|
||||
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
nativeInputValueSetter?.call(searchInput, "plex");
|
||||
searchInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
searchInput.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("Plex");
|
||||
expect(host.textContent).not.toContain("Sonarr");
|
||||
expect(host.textContent).not.toContain("Radarr");
|
||||
});
|
||||
|
||||
it("selects the single matching app when Enter key is pressed in search input", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const searchInput = host.querySelector("input");
|
||||
await act(async () => {
|
||||
if (searchInput) {
|
||||
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
nativeInputValueSetter?.call(searchInput, "sonarr");
|
||||
searchInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
searchInput.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
searchInput?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(sampleApps[0]);
|
||||
expect(closeModal).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("displays empty state message when search yields no results", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const searchInput = host.querySelector("input");
|
||||
await act(async () => {
|
||||
if (searchInput) {
|
||||
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
nativeInputValueSetter?.call(searchInput, "non-matching-query");
|
||||
searchInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
searchInput.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
}
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("No apps found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("custom app creation card", () => {
|
||||
it("renders custom app creation card when withCreate is true", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: true }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(host.textContent).toContain("Add custom app");
|
||||
expect(host.textContent).toContain("Configure custom URL and icon");
|
||||
});
|
||||
|
||||
it("omits custom app creation card when withCreate is false", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: false }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(host.textContent).not.toContain("Add custom app");
|
||||
});
|
||||
|
||||
it("opens QuickAddAppModal when custom app creation card is clicked in single select mode", async () => {
|
||||
const closeModal = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<AppSelectModalComponent actions={{ closeModal }} innerProps={{ onSelect, withCreate: true }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const createCard = Array.from(host.querySelectorAll("button")).find((btn) =>
|
||||
btn.textContent?.includes("Add custom app"),
|
||||
);
|
||||
expect(createCard).toBeDefined();
|
||||
|
||||
await act(async () => {
|
||||
createCard?.click();
|
||||
});
|
||||
|
||||
expect(mockOpenQuickAddAppModal).toHaveBeenCalledOnce();
|
||||
|
||||
// Trigger the onClose callback passed to QuickAddAppModal
|
||||
const options = mockOpenQuickAddAppModal.mock.calls[0]?.[0] as { onClose: (app: (typeof sampleApps)[0]) => void };
|
||||
const newCustomApp = {
|
||||
id: "custom-app-1",
|
||||
name: "Custom Home Assistant",
|
||||
description: "Local instance",
|
||||
iconUrl: "https://example.com/ha.png",
|
||||
href: "http://ha.local",
|
||||
};
|
||||
|
||||
await act(async () => {
|
||||
options.onClose(newCustomApp);
|
||||
});
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(newCustomApp);
|
||||
expect(closeModal).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -13,13 +13,13 @@ import {
|
||||
Text,
|
||||
ThemeIcon,
|
||||
} from "@mantine/core";
|
||||
import { IconPlus, IconSearch } from "@tabler/icons-react";
|
||||
import { IconBulb, IconPlus, IconSearch } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { createModal, modalSizeSelect, useModalAction } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { selectGridCols, SelectableCard } from "@homarr/ui";
|
||||
import { FloatingTip, selectGridCols, SelectableCard } from "@homarr/ui";
|
||||
|
||||
import { QuickAddAppModal } from "./quick-add-app/quick-add-app-modal";
|
||||
|
||||
@@ -88,7 +88,18 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{/* Top Search Input & Multi-Select Tip */}
|
||||
<FloatingTip
|
||||
opened={multiSelect}
|
||||
showDelay={2_000}
|
||||
dismissAfter={3_000}
|
||||
transitionDuration={200}
|
||||
closable={false}
|
||||
alertProps={{ color: "primaryColor", icon: <IconBulb size={18} />, variant: "light" }}
|
||||
>
|
||||
{t("tips.multiSelectApps")}
|
||||
</FloatingTip>
|
||||
|
||||
{/* Top Search Input */}
|
||||
<Stack gap={6}>
|
||||
<Input
|
||||
value={search}
|
||||
@@ -103,18 +114,6 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{multiSelect && (
|
||||
<Group justify="space-between" px={2}>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("app.action.select.multiSelectTip")}
|
||||
</Text>
|
||||
{selectedAppIds.size > 0 && (
|
||||
<Badge variant="light" color="primaryColor" size="xs">
|
||||
{t("app.action.select.selectedCount", { count: selectedAppIds.size })}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
{/* Scrollable Container with App Cards */}
|
||||
@@ -207,13 +206,6 @@ const AppCard = ({
|
||||
selected={isSelected}
|
||||
icon={<Image src={app.iconUrl} alt={app.name} w={28} h={28} fit="contain" style={{ flexShrink: 0 }} />}
|
||||
title={app.name}
|
||||
topRight={
|
||||
isSelected ? (
|
||||
<Badge variant="dot" color="primaryColor" size="xs">
|
||||
{t("app.action.select.selected")}
|
||||
</Badge>
|
||||
) : null
|
||||
}
|
||||
description={app.description}
|
||||
footerLeft={
|
||||
<Text size="xs" c="dimmed">
|
||||
|
||||
@@ -822,7 +822,6 @@
|
||||
"toggle": "Click to select",
|
||||
"selected": "Selected",
|
||||
"multiple": "Add {count}",
|
||||
"multiSelectTip": "Tip: Hold Ctrl / ⌘ to select multiple apps at once",
|
||||
"selectedCount": "{count, plural, one {# selected} other {# selected}}",
|
||||
"appsSelected": "{count, plural, one {# app selected} other {# apps selected}}",
|
||||
"customApplication": "Custom application",
|
||||
@@ -836,6 +835,10 @@
|
||||
"add": "Add an app"
|
||||
}
|
||||
},
|
||||
"tips": {
|
||||
"dismiss": "Dismiss tip",
|
||||
"multiSelectApps": "Tip: Hold Ctrl / ⌘ to select multiple apps at once"
|
||||
},
|
||||
"customWidget": {
|
||||
"betaBanner": {
|
||||
"title": "Custom Widgets are in Beta",
|
||||
@@ -2786,6 +2789,15 @@
|
||||
"selection": {
|
||||
"summary": "{count, plural, one {# selected item} other {# selected items}}",
|
||||
"selected": "{count, plural, one {# selected} other {# selected}}",
|
||||
"copy": "Copy",
|
||||
"copied": "{count, plural, one {# item copied to the clipboard} other {# items copied to the clipboard}}",
|
||||
"copyError": "The selected items could not be copied. Your browser may not allow clipboard access.",
|
||||
"paste": "Paste",
|
||||
"pasteShortcut": "Paste copied items here (Ctrl / ⌘ + V)",
|
||||
"pasted": "{count, plural, one {# item pasted} other {# items pasted}}",
|
||||
"pasteError": "The clipboard could not be read. Your browser may not allow clipboard access.",
|
||||
"pasteInvalid": "The clipboard does not contain valid Homarr board items.",
|
||||
"pasteUnavailable": "The copied items do not fit on this board.",
|
||||
"removed": "{count, plural, one {# item removed} other {# items removed}}",
|
||||
"move": "Move",
|
||||
"moveTo": "Move selected items",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
.root {
|
||||
position: fixed;
|
||||
inset-inline: var(--mantine-spacing-md);
|
||||
bottom: var(--floating-tip-bottom);
|
||||
z-index: var(--floating-tip-z-index);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.alert {
|
||||
width: fit-content;
|
||||
max-width: min(var(--floating-tip-max-width), calc(100vw - 2 * var(--mantine-spacing-md)));
|
||||
pointer-events: auto;
|
||||
box-shadow: var(--mantine-shadow-xl);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
declare const classes: {
|
||||
readonly root: string;
|
||||
readonly alert: string;
|
||||
};
|
||||
export default classes;
|
||||
@@ -0,0 +1,96 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FloatingTip } from "./floating-tip";
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
window.localStorage.clear();
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
window.matchMedia = vi.fn().mockImplementation(() => ({
|
||||
matches: false,
|
||||
media: "",
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
document.body.querySelectorAll("[data-portal]").forEach((portal) => portal.remove());
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("FloatingTip", () => {
|
||||
it("shows after the configured delay and auto-dismisses", async () => {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<FloatingTip opened showDelay={2_000} dismissAfter={3_000} transitionDuration={0}>
|
||||
Select several apps
|
||||
</FloatingTip>
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(document.body.textContent).not.toContain("Select several apps");
|
||||
|
||||
await act(async () => vi.advanceTimersByTime(2_000));
|
||||
expect(document.body.textContent).toContain("Select several apps");
|
||||
|
||||
await act(async () => vi.advanceTimersByTime(3_000));
|
||||
expect(document.body.textContent).not.toContain("Select several apps");
|
||||
});
|
||||
|
||||
it("provides an accessible close button and remembers dismissal", async () => {
|
||||
const onDismiss = vi.fn();
|
||||
const renderTip = (opened: boolean) =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<FloatingTip
|
||||
opened={opened}
|
||||
showDelay={0}
|
||||
transitionDuration={0}
|
||||
closable
|
||||
closeButtonLabel="Dismiss tip"
|
||||
rememberDismissal
|
||||
storageKey="selection"
|
||||
onDismiss={onDismiss}
|
||||
>
|
||||
Select several apps
|
||||
</FloatingTip>
|
||||
</MantineProvider>,
|
||||
);
|
||||
|
||||
await act(async () => renderTip(true));
|
||||
await act(async () => vi.advanceTimersByTime(0));
|
||||
|
||||
const closeButton = document.body.querySelector<HTMLButtonElement>('button[aria-label="Dismiss tip"]');
|
||||
expect(closeButton).not.toBeNull();
|
||||
await act(async () => closeButton?.click());
|
||||
|
||||
expect(onDismiss).toHaveBeenCalledOnce();
|
||||
expect(window.localStorage.getItem("homarr:floating-tip:selection")).toBe("dismissed");
|
||||
|
||||
await act(async () => renderTip(false));
|
||||
await act(async () => renderTip(true));
|
||||
await act(async () => vi.advanceTimersByTime(0));
|
||||
expect(document.body.textContent).not.toContain("Select several apps");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Box, createVarsResolver, factory, Portal, rem, Transition, useProps, useStyles } from "@mantine/core";
|
||||
import type { AlertProps, BoxProps, ElementProps, Factory, MantineTransition, StylesApiProps } from "@mantine/core";
|
||||
|
||||
import classes from "./floating-tip.module.css";
|
||||
|
||||
export type FloatingTipStylesNames = "root" | "alert";
|
||||
export type FloatingTipCssVariables = {
|
||||
root: "--floating-tip-bottom" | "--floating-tip-max-width" | "--floating-tip-z-index";
|
||||
};
|
||||
|
||||
interface FloatingTipBaseProps
|
||||
extends BoxProps, StylesApiProps<FloatingTipFactory>, Omit<ElementProps<"div">, "title"> {
|
||||
/** Controls whether this tip cycle should run. */
|
||||
opened: boolean;
|
||||
/** Delay before the tip appears, in milliseconds. */
|
||||
showDelay?: number;
|
||||
/** Time the tip remains visible, in milliseconds. Set to `null` to keep it open. */
|
||||
dismissAfter?: number | null;
|
||||
/** Enter and exit animation duration, in milliseconds. */
|
||||
transitionDuration?: number;
|
||||
/** Mantine transition used to show and hide the tip. */
|
||||
transition?: MantineTransition;
|
||||
/** Distance from the bottom edge of the viewport. */
|
||||
bottomOffset?: number | string;
|
||||
/** Maximum width of the alert. */
|
||||
maxWidth?: number | string;
|
||||
/** Stack order of the floating tip. */
|
||||
zIndex?: number;
|
||||
/** Props forwarded to the underlying Mantine Alert. */
|
||||
alertProps?: Omit<
|
||||
AlertProps,
|
||||
"children" | "classNames" | "closeButtonLabel" | "onClose" | "styles" | "withCloseButton"
|
||||
>;
|
||||
/** Called when the user closes the tip. */
|
||||
onDismiss?: () => void;
|
||||
}
|
||||
|
||||
type FloatingTipCloseProps =
|
||||
| { closable: true; closeButtonLabel: string }
|
||||
| { closable?: false; closeButtonLabel?: never };
|
||||
|
||||
type FloatingTipPersistenceProps =
|
||||
| { rememberDismissal: true; storageKey: string }
|
||||
| { rememberDismissal?: false; storageKey?: never };
|
||||
|
||||
export type FloatingTipProps = FloatingTipBaseProps & FloatingTipCloseProps & FloatingTipPersistenceProps;
|
||||
|
||||
export type FloatingTipFactory = Factory<{
|
||||
props: FloatingTipProps;
|
||||
ref: HTMLDivElement;
|
||||
stylesNames: FloatingTipStylesNames;
|
||||
vars: FloatingTipCssVariables;
|
||||
}>;
|
||||
|
||||
const defaultProps = {
|
||||
showDelay: 0,
|
||||
dismissAfter: null,
|
||||
transitionDuration: 200,
|
||||
transition: "slide-up",
|
||||
bottomOffset: 24,
|
||||
maxWidth: 520,
|
||||
zIndex: 1000,
|
||||
closable: false,
|
||||
rememberDismissal: false,
|
||||
} satisfies Partial<FloatingTipProps>;
|
||||
|
||||
const toCssSize = (value: number | string | undefined) => (typeof value === "number" ? rem(value) : value);
|
||||
|
||||
const varsResolver = createVarsResolver<FloatingTipFactory>((_theme, { bottomOffset, maxWidth, zIndex }) => ({
|
||||
root: {
|
||||
"--floating-tip-bottom": toCssSize(bottomOffset),
|
||||
"--floating-tip-max-width": toCssSize(maxWidth),
|
||||
"--floating-tip-z-index": zIndex?.toString(),
|
||||
},
|
||||
}));
|
||||
|
||||
const getDismissalStorageKey = (storageKey: string) => `homarr:floating-tip:${storageKey}`;
|
||||
|
||||
export const FloatingTip = factory<FloatingTipFactory>((_props) => {
|
||||
const props = useProps("FloatingTip", defaultProps, _props);
|
||||
const {
|
||||
ref,
|
||||
classNames,
|
||||
className,
|
||||
style,
|
||||
styles,
|
||||
unstyled,
|
||||
vars,
|
||||
attributes,
|
||||
opened,
|
||||
showDelay,
|
||||
dismissAfter,
|
||||
transitionDuration,
|
||||
transition,
|
||||
bottomOffset: _bottomOffset,
|
||||
maxWidth: _maxWidth,
|
||||
zIndex: _zIndex,
|
||||
closable,
|
||||
closeButtonLabel,
|
||||
rememberDismissal,
|
||||
storageKey,
|
||||
alertProps,
|
||||
onDismiss,
|
||||
children,
|
||||
...others
|
||||
} = props;
|
||||
const [visible, setVisible] = useState(false);
|
||||
const showTimerRef = useRef<number | null>(null);
|
||||
const dismissTimerRef = useRef<number | null>(null);
|
||||
|
||||
const clearTimers = useCallback(() => {
|
||||
if (showTimerRef.current !== null) window.clearTimeout(showTimerRef.current);
|
||||
if (dismissTimerRef.current !== null) window.clearTimeout(dismissTimerRef.current);
|
||||
showTimerRef.current = null;
|
||||
dismissTimerRef.current = null;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
clearTimers();
|
||||
setVisible(false);
|
||||
|
||||
if (!opened) return;
|
||||
|
||||
if (rememberDismissal) {
|
||||
try {
|
||||
if (window.localStorage.getItem(getDismissalStorageKey(storageKey)) === "dismissed") return;
|
||||
} catch {
|
||||
// Storage can be unavailable in private browsing or hardened environments.
|
||||
}
|
||||
}
|
||||
|
||||
showTimerRef.current = window.setTimeout(() => {
|
||||
setVisible(true);
|
||||
showTimerRef.current = null;
|
||||
|
||||
if (dismissAfter !== null) {
|
||||
dismissTimerRef.current = window.setTimeout(() => {
|
||||
setVisible(false);
|
||||
dismissTimerRef.current = null;
|
||||
}, dismissAfter);
|
||||
}
|
||||
}, showDelay);
|
||||
|
||||
return clearTimers;
|
||||
}, [clearTimers, dismissAfter, opened, rememberDismissal, showDelay, storageKey]);
|
||||
|
||||
const handleDismiss = () => {
|
||||
clearTimers();
|
||||
setVisible(false);
|
||||
|
||||
if (rememberDismissal) {
|
||||
try {
|
||||
window.localStorage.setItem(getDismissalStorageKey(storageKey), "dismissed");
|
||||
} catch {
|
||||
// The tip still closes for this render even when persistence is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
onDismiss?.();
|
||||
};
|
||||
|
||||
const getStyles = useStyles<FloatingTipFactory>({
|
||||
name: "FloatingTip",
|
||||
classes,
|
||||
props,
|
||||
className,
|
||||
style,
|
||||
classNames,
|
||||
styles,
|
||||
unstyled,
|
||||
vars,
|
||||
attributes,
|
||||
varsResolver,
|
||||
});
|
||||
|
||||
return (
|
||||
<Portal>
|
||||
<Transition mounted={visible} transition={transition} duration={transitionDuration} timingFunction="ease">
|
||||
{(transitionStyle) => {
|
||||
const rootStyles = getStyles("root");
|
||||
|
||||
return (
|
||||
<Box ref={ref} {...others} {...rootStyles} style={[rootStyles.style, transitionStyle]}>
|
||||
<Alert
|
||||
{...alertProps}
|
||||
{...getStyles("alert")}
|
||||
withCloseButton={closable}
|
||||
closeButtonLabel={closeButtonLabel}
|
||||
onClose={handleDismiss}
|
||||
>
|
||||
{children}
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
}}
|
||||
</Transition>
|
||||
</Portal>
|
||||
);
|
||||
});
|
||||
|
||||
FloatingTip.displayName = "@homarr/ui/FloatingTip";
|
||||
FloatingTip.classes = classes;
|
||||
@@ -0,0 +1,7 @@
|
||||
export { FloatingTip } from "./floating-tip";
|
||||
export type {
|
||||
FloatingTipCssVariables,
|
||||
FloatingTipFactory,
|
||||
FloatingTipProps,
|
||||
FloatingTipStylesNames,
|
||||
} from "./floating-tip";
|
||||
@@ -20,6 +20,7 @@ export type {
|
||||
SelectableCardCssVariables,
|
||||
SelectableCardFactory,
|
||||
} from "./selectable-card";
|
||||
export * from "./floating-tip";
|
||||
export { MaskedImage } from "./masked-image";
|
||||
export { MaskedOrNormalImage } from "./masked-or-normal-image";
|
||||
export { LanguageIcon } from "./language-icon";
|
||||
|
||||
Reference in new issue
Block a user