fix: refine dashboard interactions and widget options (#6597)
* fix: refine dashboard item interactions * fix board interactions and widget options * feat: improve bookmark selection * fix: address dashboard review feedback
This commit is contained in:
1 parent
b491d45fdc
commit
4505ce96c9
37 files changed
+824
-503
No files matched your search
@@ -6,7 +6,7 @@ import type { WidgetOptionOfType, WidgetOptionType } from "../options";
|
||||
export interface CommonWidgetInputProps<TKey extends WidgetOptionType> {
|
||||
kind: WidgetKind;
|
||||
property: string;
|
||||
options: Omit<WidgetOptionOfType<TKey>, "defaultValue" | "type">;
|
||||
options: Omit<WidgetOptionOfType<TKey>, "type">;
|
||||
initialOptions: Record<string, unknown>;
|
||||
itemId?: string;
|
||||
boardId?: string;
|
||||
|
||||
@@ -114,7 +114,7 @@ async function renderInput() {
|
||||
<WidgetCustomWidgetSelectInput
|
||||
kind="customApi"
|
||||
property="definitionId"
|
||||
options={{ withDescription: false }}
|
||||
options={{ defaultValue: "", withDescription: false }}
|
||||
initialOptions={{}}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { WidgetLocationInput } from "./widget-location-input";
|
||||
|
||||
const defaultLocation = { name: "Paris", latitude: 48.8566, longitude: 2.3522 };
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
values: {} as Record<string, unknown>,
|
||||
setFieldValue: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@mantine/core", () => {
|
||||
const Container = ({ children }: { children?: ReactNode }) => <div>{children}</div>;
|
||||
const Input = ({ label, value }: { label?: ReactNode; value?: string | number }) => (
|
||||
<label>
|
||||
{label}
|
||||
<input value={value ?? ""} readOnly />
|
||||
</label>
|
||||
);
|
||||
|
||||
return {
|
||||
Button: Container,
|
||||
Fieldset: Container,
|
||||
Group: Container,
|
||||
NumberInput: Input,
|
||||
Stack: Container,
|
||||
TextInput: Input,
|
||||
Tooltip: Container,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@homarr/modals", () => ({
|
||||
createModal: () => ({ withOptions: () => null }),
|
||||
useModalAction: () => ({ openModal: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/translation/client", () => ({
|
||||
useCurrentIntlLocale: () => "en",
|
||||
useScopedI18n: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
vi.mock("./common", async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
useWidgetInputTranslation: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
vi.mock("./form", () => ({
|
||||
useFormContext: () => ({
|
||||
getInputProps: (path: string) => ({ value: mocks.values[path], onChange: vi.fn() }),
|
||||
setFieldValue: mocks.setFieldValue,
|
||||
clearFieldError: vi.fn(),
|
||||
watch: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
mocks.values = {};
|
||||
mocks.setFieldValue.mockReset();
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
const renderInput = async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<WidgetLocationInput
|
||||
kind="weather"
|
||||
property="location"
|
||||
options={{ defaultValue: defaultLocation }}
|
||||
initialOptions={{}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
describe("location input initialization", () => {
|
||||
it("hydrates a missing location with the default value", async () => {
|
||||
await renderInput();
|
||||
|
||||
expect(mocks.setFieldValue).toHaveBeenCalledOnce();
|
||||
expect(mocks.setFieldValue).toHaveBeenCalledWith("options.location", defaultLocation);
|
||||
});
|
||||
|
||||
it("does not reset a transient empty coordinate after initialization", async () => {
|
||||
mocks.values = {
|
||||
"options.location": defaultLocation,
|
||||
"options.location.name": defaultLocation.name,
|
||||
"options.location.latitude": defaultLocation.latitude,
|
||||
"options.location.longitude": defaultLocation.longitude,
|
||||
};
|
||||
await renderInput();
|
||||
|
||||
mocks.values = {
|
||||
...mocks.values,
|
||||
"options.location": { ...defaultLocation, latitude: "" },
|
||||
"options.location.latitude": "",
|
||||
};
|
||||
await renderInput();
|
||||
|
||||
expect(mocks.setFieldValue).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
@@ -29,14 +29,26 @@ import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetLocationInput = ({ property, kind }: CommonWidgetInputProps<"location">) => {
|
||||
export const WidgetLocationInput = ({ property, kind, options }: CommonWidgetInputProps<"location">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const tLocation = useScopedI18n("widget.common.location");
|
||||
const form = useFormContext();
|
||||
const { openModal } = useModalAction(LocationSearchModal);
|
||||
const inputProps = form.getInputProps(`options.${property}`);
|
||||
const value = inputProps.value as OptionLocation;
|
||||
const fieldPath = `options.${property}`;
|
||||
const inputProps = form.getInputProps(fieldPath);
|
||||
const value = isOptionLocation(inputProps.value) ? inputProps.value : options.defaultValue;
|
||||
const nameInputProps = form.getInputProps(`options.${property}.name`);
|
||||
const latitudeInputProps = form.getInputProps(`options.${property}.latitude`);
|
||||
const longitudeInputProps = form.getInputProps(`options.${property}.longitude`);
|
||||
const selectionEnabled = value.name.length > 1;
|
||||
const initializedFieldPathRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (initializedFieldPathRef.current === fieldPath) return;
|
||||
initializedFieldPathRef.current = fieldPath;
|
||||
if (isOptionLocation(inputProps.value)) return;
|
||||
form.setFieldValue(fieldPath, options.defaultValue);
|
||||
}, [fieldPath, form, inputProps.value, options.defaultValue]);
|
||||
|
||||
const handleChange = inputProps.onChange as LocationOnChange;
|
||||
const unknownLocation = tLocation("unknownLocation");
|
||||
@@ -73,7 +85,12 @@ export const WidgetLocationInput = ({ property, kind }: CommonWidgetInputProps<"
|
||||
<Fieldset legend={t("label")}>
|
||||
<Stack gap="xs">
|
||||
<Group wrap="nowrap" align="end">
|
||||
<TextInput w="100%" label={tLocation("query")} {...form.getInputProps(`options.${property}.name`)} />
|
||||
<TextInput
|
||||
w="100%"
|
||||
label={tLocation("query")}
|
||||
{...nameInputProps}
|
||||
value={nameInputProps.value ?? value.name}
|
||||
/>
|
||||
<Tooltip hidden={selectionEnabled} label={tLocation("disabledTooltip")}>
|
||||
<div>
|
||||
<Button
|
||||
@@ -93,13 +110,15 @@ export const WidgetLocationInput = ({ property, kind }: CommonWidgetInputProps<"
|
||||
decimalScale={5}
|
||||
label={tLocation("latitude")}
|
||||
hideControls
|
||||
{...form.getInputProps(`options.${property}.latitude`)}
|
||||
{...latitudeInputProps}
|
||||
value={latitudeInputProps.value ?? value.latitude}
|
||||
/>
|
||||
<NumberInput
|
||||
decimalScale={5}
|
||||
label={tLocation("longitude")}
|
||||
hideControls
|
||||
{...form.getInputProps(`options.${property}.longitude`)}
|
||||
{...longitudeInputProps}
|
||||
value={longitudeInputProps.value ?? value.longitude}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
@@ -107,6 +126,16 @@ export const WidgetLocationInput = ({ property, kind }: CommonWidgetInputProps<"
|
||||
);
|
||||
};
|
||||
|
||||
const isOptionLocation = (value: unknown): value is OptionLocation =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"name" in value &&
|
||||
typeof value.name === "string" &&
|
||||
"latitude" in value &&
|
||||
typeof value.latitude === "number" &&
|
||||
"longitude" in value &&
|
||||
typeof value.longitude === "number";
|
||||
|
||||
type LocationOnChange = (
|
||||
location: Pick<OptionLocation, "name"> & {
|
||||
latitude: OptionLocation["latitude"] | "";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Combobox, Pill, PillsInput, useCombobox } from "@mantine/core";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
@@ -18,10 +18,16 @@ export const WidgetMultiTextInput = ({ property, kind, options }: CommonWidgetIn
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const form = useFormContext();
|
||||
const inputProps = form.getInputProps(`options.${property}`);
|
||||
const values = inputProps.value as string[];
|
||||
const fieldPath = `options.${property}`;
|
||||
const inputProps = form.getInputProps(fieldPath);
|
||||
const values = Array.isArray(inputProps.value) ? (inputProps.value as string[]) : options.defaultValue;
|
||||
const onChange = inputProps.onChange as (values: string[]) => void;
|
||||
|
||||
useEffect(() => {
|
||||
if (Array.isArray(inputProps.value)) return;
|
||||
form.setFieldValue(fieldPath, options.defaultValue);
|
||||
}, [fieldPath, form, inputProps.value, options.defaultValue]);
|
||||
|
||||
const handleRemove = (optionIndex: number) => {
|
||||
onChange(values.filter((_, index) => index !== optionIndex));
|
||||
};
|
||||
|
||||
@@ -31,8 +31,14 @@ export const WidgetSortedItemListInput = <TItem, TOptionValue extends UniqueIden
|
||||
}: CommonWidgetInputProps<"sortableItemList">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
const initialValues = useMemo(() => initialOptions[property] as TOptionValue[], [initialOptions, property]);
|
||||
const values = form.values.options[property] as TOptionValue[];
|
||||
const fieldPath = `options.${property}`;
|
||||
const initialValues = useMemo(
|
||||
() =>
|
||||
Array.isArray(initialOptions[property]) ? (initialOptions[property] as TOptionValue[]) : options.defaultValue,
|
||||
[initialOptions, options.defaultValue, property],
|
||||
);
|
||||
const currentValue = form.values.options[property];
|
||||
const values = Array.isArray(currentValue) ? (currentValue as TOptionValue[]) : options.defaultValue;
|
||||
const { data, isLoading, error } = options.useData(initialValues);
|
||||
const dataMap = useMemo(
|
||||
() => new Map(data?.map((item) => [options.uniqueIdentifier(item), item as TItem])),
|
||||
@@ -52,6 +58,11 @@ export const WidgetSortedItemListInput = <TItem, TOptionValue extends UniqueIden
|
||||
const getIndex = (id: TOptionValue) => values.indexOf(id);
|
||||
const activeIndex = activeId ? getIndex(activeId) : -1;
|
||||
|
||||
useEffect(() => {
|
||||
if (Array.isArray(currentValue)) return;
|
||||
form.setFieldValue(fieldPath, options.defaultValue);
|
||||
}, [currentValue, fieldPath, form, options.defaultValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeId) {
|
||||
isFirstAnnouncement.current = true;
|
||||
@@ -69,22 +80,39 @@ export const WidgetSortedItemListInput = <TItem, TOptionValue extends UniqueIden
|
||||
[tempMap, dataMap],
|
||||
);
|
||||
|
||||
const updateItems = (callback: (prev: TOptionValue[]) => TOptionValue[]) => {
|
||||
form.setFieldValue(`options.${property}`, callback);
|
||||
};
|
||||
const updateItems = useCallback(
|
||||
(callback: (prev: TOptionValue[]) => TOptionValue[]) => {
|
||||
form.setFieldValue(fieldPath, callback);
|
||||
},
|
||||
[fieldPath, form],
|
||||
);
|
||||
|
||||
const addItem = (item: TItem) => {
|
||||
setTempMap((prev) => {
|
||||
prev.set(options.uniqueIdentifier(item) as TOptionValue, item);
|
||||
return prev;
|
||||
const next = new Map(prev);
|
||||
next.set(options.uniqueIdentifier(item) as TOptionValue, item);
|
||||
return next;
|
||||
});
|
||||
updateItems((values) => [...values, options.uniqueIdentifier(item) as TOptionValue]);
|
||||
updateItems((currentValues) => [...currentValues, options.uniqueIdentifier(item) as TOptionValue]);
|
||||
};
|
||||
|
||||
const removeItem = useCallback(
|
||||
(value: TOptionValue) => {
|
||||
updateItems((currentValues) => currentValues.filter((candidate) => candidate !== value));
|
||||
setTempMap((previous) => {
|
||||
if (!previous.has(value)) return previous;
|
||||
const next = new Map(previous);
|
||||
next.delete(value);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[updateItems],
|
||||
);
|
||||
|
||||
return (
|
||||
<Fieldset legend={t("label")}>
|
||||
<Stack>
|
||||
<options.addButton addItem={addItem} values={values} />
|
||||
<options.addButton addItem={addItem} removeItem={removeItem} values={values} />
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
@@ -114,19 +142,6 @@ export const WidgetSortedItemListInput = <TItem, TOptionValue extends UniqueIden
|
||||
<React.Fragment>
|
||||
{values.map((value, index) => {
|
||||
const item = getItem(value);
|
||||
const removeItem = () => {
|
||||
form.setValues((previous) => {
|
||||
const previousValues = previous.options?.[property] as TOptionValue[];
|
||||
return {
|
||||
...previous,
|
||||
options: {
|
||||
...previous.options,
|
||||
[property]: previousValues.filter((id) => id !== value),
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
@@ -137,7 +152,7 @@ export const WidgetSortedItemListInput = <TItem, TOptionValue extends UniqueIden
|
||||
id={value}
|
||||
index={index}
|
||||
item={item}
|
||||
removeItem={removeItem}
|
||||
removeItem={() => removeItem(value)}
|
||||
options={options}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
.clickableCard {
|
||||
position: relative;
|
||||
transition: background-color 150ms;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.clickableCard:hover,
|
||||
.clickableCard:focus-visible {
|
||||
.clickableCard:focus-within {
|
||||
background-color: color-mix(in srgb, var(--mantine-color-default-hover) 40%, transparent) !important;
|
||||
}
|
||||
|
||||
.clickableCard:focus-visible {
|
||||
.clickableCard:focus-within {
|
||||
outline: 2px solid var(--mantine-primary-color-filled);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.cardAction {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.clickableCard {
|
||||
transition: none;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import type { MantineSize } from "@mantine/core";
|
||||
import { Badge, Box, Card, Center, Group, Loader, Progress, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { Badge, Box, Card, Center, Group, Loader, Progress, SimpleGrid, Stack, Text, UnstyledButton } from "@mantine/core";
|
||||
import {
|
||||
Activity,
|
||||
Battery,
|
||||
@@ -365,14 +365,10 @@ const SystemCard = ({
|
||||
|
||||
return (
|
||||
<Card
|
||||
component="button"
|
||||
type="button"
|
||||
disabled={!onClick}
|
||||
padding={size.cardPadding}
|
||||
radius={itemRadius}
|
||||
bg="transparent"
|
||||
h="100%"
|
||||
onClick={onClick}
|
||||
className={onClick ? classes.clickableCard : undefined}
|
||||
style={{
|
||||
overflow: "hidden",
|
||||
@@ -385,6 +381,14 @@ const SystemCard = ({
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{onClick && (
|
||||
<UnstyledButton
|
||||
type="button"
|
||||
className={classes.cardAction}
|
||||
aria-label={system.name}
|
||||
onClick={onClick}
|
||||
/>
|
||||
)}
|
||||
<Group gap="xs" mb={2}>
|
||||
<Badge
|
||||
size={size.badgeSize}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
.target {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
@@ -1,30 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@mantine/core";
|
||||
import type { MultiSelectProps } from "@mantine/core";
|
||||
import { Group, Loader, MultiSelect } from "@mantine/core";
|
||||
import { IconCheck } from "@tabler/icons-react";
|
||||
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { SortableItemListInput } from "../options";
|
||||
import { AppSelectModal } from "./app-select-modal";
|
||||
|
||||
export const BookmarkAddButton: SortableItemListInput<
|
||||
{
|
||||
name: string;
|
||||
description: string | null;
|
||||
id: string;
|
||||
iconUrl: string;
|
||||
href: string | null;
|
||||
pingUrl: string | null;
|
||||
},
|
||||
string
|
||||
>["AddButton"] = ({ addItem, values }) => {
|
||||
const { openModal } = useModalAction(AppSelectModal);
|
||||
const t = useI18n();
|
||||
type SelectableApp = RouterOutputs["app"]["selectable"][number];
|
||||
|
||||
export const BookmarkAddButton: SortableItemListInput<SelectableApp, string>["AddButton"] = ({
|
||||
addItem,
|
||||
removeItem,
|
||||
values,
|
||||
}) => {
|
||||
const t = useScopedI18n("widget.bookmarks.option.items.apps");
|
||||
const tCommon = useScopedI18n("common");
|
||||
const tSelect = useScopedI18n("app.action.select");
|
||||
const { data: apps = [], isPending, error } = clientApi.app.selectable.useQuery();
|
||||
const appsById = new Map(apps.map((app) => [app.id, app]));
|
||||
|
||||
const handleChange = (nextValues: string[]) => {
|
||||
const nextIds = new Set(nextValues);
|
||||
for (const value of values) {
|
||||
if (!nextIds.has(value)) removeItem(value);
|
||||
}
|
||||
|
||||
const currentIds = new Set(values);
|
||||
for (const value of nextValues) {
|
||||
if (currentIds.has(value)) continue;
|
||||
const app = appsById.get(value);
|
||||
if (app) addItem(app);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button onClick={() => openModal({ onSelect: addItem, presentAppIds: values })}>
|
||||
{t("widget.bookmarks.option.items.add")}
|
||||
</Button>
|
||||
<MultiSelect
|
||||
label={t("label")}
|
||||
placeholder={t("placeholder")}
|
||||
value={values}
|
||||
onChange={handleChange}
|
||||
searchable
|
||||
clearable
|
||||
clearSearchOnChange
|
||||
hidePickedOptions
|
||||
disabled={isPending || Boolean(error)}
|
||||
error={error ? tCommon("error") : undefined}
|
||||
rightSection={isPending ? <Loader size="xs" /> : undefined}
|
||||
nothingFoundMessage={tSelect("notFound")}
|
||||
renderOption={renderAppOption}
|
||||
data={apps.map((app) => ({
|
||||
value: app.id,
|
||||
label: app.name,
|
||||
iconUrl: app.iconUrl,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const iconProps = {
|
||||
stroke: 1.5,
|
||||
color: "currentColor",
|
||||
opacity: 0.6,
|
||||
size: 18,
|
||||
};
|
||||
|
||||
const renderAppOption: MultiSelectProps["renderOption"] = ({ option, checked }) => (
|
||||
<Group flex="1" gap="xs">
|
||||
{"iconUrl" in option && typeof option.iconUrl === "string" ? (
|
||||
<img width={20} height={20} src={option.iconUrl} alt="" />
|
||||
) : null}
|
||||
{option.label}
|
||||
{checked && <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />}
|
||||
</Group>
|
||||
);
|
||||
@@ -1,109 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useState } from "react";
|
||||
import type { SelectProps } from "@mantine/core";
|
||||
import { Group, Loader, Select, Stack } from "@mantine/core";
|
||||
import { IconCheck } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useForm } from "@homarr/form";
|
||||
import { createModal, ModalFormFooter, modalSizeForm } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
interface InnerProps {
|
||||
presentAppIds: string[];
|
||||
onSelect: (props: RouterOutputs["app"]["selectable"][number]) => void | Promise<void>;
|
||||
confirmLabel?: string;
|
||||
}
|
||||
|
||||
interface AppSelectFormType {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export const AppSelectModal = createModal<InnerProps>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const { data: apps, isPending } = clientApi.app.selectable.useQuery();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const form = useForm<AppSelectFormType>();
|
||||
const handleSubmitAsync = async (values: AppSelectFormType) => {
|
||||
const currentApp = apps?.find((app) => app.id === values.id);
|
||||
if (!currentApp) return;
|
||||
setLoading(true);
|
||||
await innerProps.onSelect(currentApp);
|
||||
|
||||
setLoading(false);
|
||||
actions.closeModal();
|
||||
};
|
||||
|
||||
const confirmLabel = innerProps.confirmLabel ?? t("common.action.add");
|
||||
const currentApp = apps?.find((app) => app.id === form.values.id);
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}>
|
||||
<Stack>
|
||||
<Select
|
||||
{...form.getInputProps("id")}
|
||||
label={t("app.action.select.label")}
|
||||
searchable
|
||||
clearable
|
||||
data-autofocus
|
||||
leftSection={<MemoizedLeftSection isPending={isPending} currentApp={currentApp} />}
|
||||
nothingFoundMessage={t("app.action.select.notFound")}
|
||||
renderOption={renderSelectOption}
|
||||
limit={5}
|
||||
data={
|
||||
apps
|
||||
?.filter((app) => !innerProps.presentAppIds.includes(app.id))
|
||||
.map((app) => ({
|
||||
label: app.name,
|
||||
value: app.id,
|
||||
iconUrl: app.iconUrl,
|
||||
})) ?? []
|
||||
}
|
||||
/>
|
||||
<ModalFormFooter onCancel={actions.closeModal} submitLabel={confirmLabel} loading={loading} />
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
}).withOptions({
|
||||
defaultTitle: (t) => t("app.action.select.label"),
|
||||
size: modalSizeForm,
|
||||
});
|
||||
|
||||
const iconProps = {
|
||||
stroke: 1.5,
|
||||
color: "currentColor",
|
||||
opacity: 0.6,
|
||||
size: 18,
|
||||
};
|
||||
|
||||
const renderSelectOption: SelectProps["renderOption"] = ({ option, checked }) => (
|
||||
<Group flex="1" gap="xs">
|
||||
{"iconUrl" in option && typeof option.iconUrl === "string" ? (
|
||||
<img width={20} height={20} src={option.iconUrl} alt={option.label} />
|
||||
) : null}
|
||||
{option.label}
|
||||
{checked && <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />}
|
||||
</Group>
|
||||
);
|
||||
|
||||
interface LeftSectionProps {
|
||||
isPending: boolean;
|
||||
currentApp: RouterOutputs["app"]["selectable"][number] | undefined;
|
||||
}
|
||||
|
||||
const size = 20;
|
||||
const LeftSection = ({ isPending, currentApp }: LeftSectionProps) => {
|
||||
if (isPending) {
|
||||
return <Loader size={size} />;
|
||||
}
|
||||
|
||||
if (currentApp) {
|
||||
return <img width={size} height={size} src={currentApp.iconUrl} alt={currentApp.name} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const MemoizedLeftSection = memo(LeftSection);
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { CSSProperties } from "react";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Anchor,
|
||||
@@ -14,9 +15,9 @@ import {
|
||||
Title,
|
||||
UnstyledButton,
|
||||
} from "@mantine/core";
|
||||
import { IconLink } from "@tabler/icons-react";
|
||||
import combineClasses from "clsx";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { useRegisterSpotlightContextResults } from "@homarr/spotlight";
|
||||
@@ -29,6 +30,14 @@ import classes from "./bookmark.module.css";
|
||||
|
||||
type BookmarkLayout = WidgetComponentProps<"bookmarks">["options"]["layout"];
|
||||
|
||||
export interface BookmarkDisplayItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
iconUrl?: string;
|
||||
href: string | null;
|
||||
}
|
||||
|
||||
export interface CompactBookmarkLayout {
|
||||
columns: number;
|
||||
hideHostname: boolean;
|
||||
@@ -67,14 +76,19 @@ export default function BookmarksWidget({
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"bookmarks">) {
|
||||
const board = useRequiredBoard();
|
||||
const data =
|
||||
const apps =
|
||||
getUsableWidgetQueryData(
|
||||
clientApi.app.byIds.useQuery(options.items, {
|
||||
select(apps) {
|
||||
return apps.toSorted((appA, appB) => options.items.indexOf(appA.id) - options.items.indexOf(appB.id));
|
||||
select(selectedApps) {
|
||||
return selectedApps.toSorted((appA, appB) => options.items.indexOf(appA.id) - options.items.indexOf(appB.id));
|
||||
},
|
||||
}),
|
||||
) ?? [];
|
||||
const customLinks = useMemo(
|
||||
() => options.customUrls.flatMap((url) => createCustomBookmark(url) ?? []),
|
||||
[options.customUrls],
|
||||
);
|
||||
const data: BookmarkDisplayItem[] = [...apps, ...customLinks];
|
||||
|
||||
useRegisterSpotlightContextResults(
|
||||
`bookmark-${itemId}`,
|
||||
@@ -85,7 +99,7 @@ export default function BookmarksWidget({
|
||||
{
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
icon: app.iconUrl,
|
||||
icon: app.iconUrl ?? IconLink,
|
||||
interaction() {
|
||||
return {
|
||||
type: "link",
|
||||
@@ -161,7 +175,7 @@ export default function BookmarksWidget({
|
||||
}
|
||||
|
||||
interface FlexLayoutProps {
|
||||
data: RouterOutputs["app"]["byIds"];
|
||||
data: BookmarkDisplayItem[];
|
||||
direction: "row" | "column";
|
||||
hideTitle: boolean;
|
||||
hideIcon: boolean;
|
||||
@@ -235,7 +249,7 @@ const FlexLayout = ({
|
||||
};
|
||||
|
||||
interface AdvancedBookmarksLayoutProps {
|
||||
data: RouterOutputs["app"]["byIds"];
|
||||
data: BookmarkDisplayItem[];
|
||||
width: number;
|
||||
openNewTab: boolean;
|
||||
withBorder: boolean;
|
||||
@@ -250,6 +264,19 @@ export const getBookmarkHostname = (href: string | null): string | undefined =>
|
||||
return safeHref ? new URL(safeHref).hostname : undefined;
|
||||
};
|
||||
|
||||
export const createCustomBookmark = (url: string): BookmarkDisplayItem | null => {
|
||||
const normalizedUrl = url.trim();
|
||||
const href = getSafeAppHref(normalizedUrl);
|
||||
if (!href) return null;
|
||||
|
||||
return {
|
||||
id: `custom-link:${normalizedUrl}`,
|
||||
name: getBookmarkHostname(href) ?? normalizedUrl,
|
||||
description: null,
|
||||
href,
|
||||
};
|
||||
};
|
||||
|
||||
const AdvancedBookmarksLayout = ({
|
||||
data,
|
||||
width,
|
||||
@@ -275,10 +302,9 @@ const AdvancedBookmarksLayout = ({
|
||||
>
|
||||
<Card radius={board.itemRadius} className={classes.card} withBorder={withBorder} p="md" h="100%">
|
||||
<Group align="flex-start" wrap="nowrap">
|
||||
<MaskedOrNormalImage
|
||||
imageUrl={app.iconUrl}
|
||||
<BookmarkIcon
|
||||
app={app}
|
||||
hasColor={hasIconColor}
|
||||
alt={app.name}
|
||||
className={classes.bookmarkIcon}
|
||||
style={{ width: 40, height: 40, flex: "0 0 auto" }}
|
||||
/>
|
||||
@@ -306,7 +332,7 @@ const AdvancedBookmarksLayout = ({
|
||||
};
|
||||
|
||||
interface GridLayoutProps {
|
||||
data: RouterOutputs["app"]["byIds"];
|
||||
data: BookmarkDisplayItem[];
|
||||
hideTitle: boolean;
|
||||
hideIcon: boolean;
|
||||
hideHostname: boolean;
|
||||
@@ -392,7 +418,7 @@ const VerticalItem = ({
|
||||
hideHostname,
|
||||
hasIconColor,
|
||||
}: {
|
||||
app: RouterOutputs["app"]["byIds"][number];
|
||||
app: BookmarkDisplayItem;
|
||||
hideTitle: boolean;
|
||||
hideIcon: boolean;
|
||||
hideHostname: boolean;
|
||||
@@ -406,10 +432,9 @@ const VerticalItem = ({
|
||||
</Text>
|
||||
)}
|
||||
{!hideIcon && (
|
||||
<MaskedOrNormalImage
|
||||
imageUrl={app.iconUrl}
|
||||
<BookmarkIcon
|
||||
app={app}
|
||||
hasColor={hasIconColor}
|
||||
alt={app.name}
|
||||
className={classes.bookmarkIcon}
|
||||
style={{
|
||||
width: hideHostname && hideTitle ? "min(max(100%, 16px), 40px)" : 40,
|
||||
@@ -437,7 +462,7 @@ const HorizontalItem = ({
|
||||
hideHostname,
|
||||
hasIconColor,
|
||||
}: {
|
||||
app: RouterOutputs["app"]["byIds"][number];
|
||||
app: BookmarkDisplayItem;
|
||||
hideTitle: boolean;
|
||||
hideIcon: boolean;
|
||||
hideHostname: boolean;
|
||||
@@ -446,10 +471,9 @@ const HorizontalItem = ({
|
||||
return (
|
||||
<Group wrap="nowrap" gap="xs" h="100%" justify="start">
|
||||
{!hideIcon && (
|
||||
<MaskedOrNormalImage
|
||||
imageUrl={app.iconUrl}
|
||||
<BookmarkIcon
|
||||
app={app}
|
||||
hasColor={hasIconColor}
|
||||
alt={app.name}
|
||||
className={classes.bookmarkIcon}
|
||||
style={{
|
||||
overflow: "auto",
|
||||
@@ -479,3 +503,23 @@ const HorizontalItem = ({
|
||||
</Group>
|
||||
);
|
||||
};
|
||||
|
||||
interface BookmarkIconProps {
|
||||
app: BookmarkDisplayItem;
|
||||
hasColor: boolean;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
|
||||
const BookmarkIcon = ({ app, hasColor, className, style }: BookmarkIconProps) =>
|
||||
app.iconUrl ? (
|
||||
<MaskedOrNormalImage
|
||||
imageUrl={app.iconUrl}
|
||||
hasColor={hasColor}
|
||||
alt={app.name}
|
||||
className={className}
|
||||
style={style}
|
||||
/>
|
||||
) : (
|
||||
<IconLink aria-label={app.name} className={className} style={style} />
|
||||
);
|
||||
@@ -1,9 +1,11 @@
|
||||
import { ActionIcon, Avatar, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconBookmark, IconX } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
|
||||
import { getSafeAppHref } from "../common/application-url";
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
import { BookmarkAddButton } from "./add-button";
|
||||
@@ -27,7 +29,11 @@ export const { definition, componentLoader } = createWidgetDefinition("bookmarks
|
||||
hideHostname: factory.switch({ defaultValue: false }),
|
||||
openNewTab: factory.switch({ defaultValue: true }),
|
||||
withBorder: factory.switch({ defaultValue: false }),
|
||||
items: factory.sortableItemList<RouterOutputs["app"]["all"][number], string>({
|
||||
customUrls: factory.multiText({
|
||||
validate: z.string().refine((value) => getSafeAppHref(value) !== undefined),
|
||||
withDescription: true,
|
||||
}),
|
||||
items: factory.sortableItemList<RouterOutputs["app"]["selectable"][number], string>({
|
||||
ItemComponent: ({ item, handle, removeItem, rootAttributes }) => {
|
||||
return (
|
||||
<Group {...rootAttributes} tabIndex={0} justify="space-between" wrap="nowrap">
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { getAdvancedBookmarkColumns, getBookmarkHostname, getCompactBookmarkLayout } from "./component";
|
||||
import {
|
||||
createCustomBookmark,
|
||||
getAdvancedBookmarkColumns,
|
||||
getBookmarkHostname,
|
||||
getCompactBookmarkLayout,
|
||||
} from "./component";
|
||||
|
||||
describe("bookmark display helpers", () => {
|
||||
test("uses bounded advanced columns", () => {
|
||||
@@ -30,4 +35,20 @@ describe("bookmark display helpers", () => {
|
||||
expect(getBookmarkHostname("not a URL")).toBeUndefined();
|
||||
expect(getBookmarkHostname(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("creates standalone bookmarks without app records", () => {
|
||||
expect(createCustomBookmark("https://homarr.dev/docs")).toEqual({
|
||||
id: "custom-link:https://homarr.dev/docs",
|
||||
name: "homarr.dev",
|
||||
description: null,
|
||||
href: "https://homarr.dev/docs",
|
||||
});
|
||||
expect(createCustomBookmark(" https://homarr.dev/docs ")).toEqual({
|
||||
id: "custom-link:https://homarr.dev/docs",
|
||||
name: "homarr.dev",
|
||||
description: null,
|
||||
href: "https://homarr.dev/docs",
|
||||
});
|
||||
expect(createCustomBookmark("javascript:alert(1)")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -755,7 +755,7 @@ export default function DownloadClientsWidget({
|
||||
<Stack gap={0} h="100%" style={{ overflow: "hidden" }}>
|
||||
{statsDisplay.visible && (
|
||||
<GlobalStatsBar
|
||||
key={displayMode}
|
||||
key={`stats-${displayMode}`}
|
||||
queueStats={queueStats}
|
||||
totalSpeed={totalSpeed}
|
||||
totalUpSpeed={totalUpSpeed}
|
||||
@@ -803,7 +803,7 @@ export default function DownloadClientsWidget({
|
||||
|
||||
{(isAdvanced || height >= 96) && (
|
||||
<WidgetFooter
|
||||
key={displayMode}
|
||||
key={`footer-${displayMode}`}
|
||||
clients={clients}
|
||||
totalSpeed={totalSpeed}
|
||||
totalUpSpeed={totalUpSpeed}
|
||||
|
||||
@@ -32,7 +32,11 @@ export interface SortableItemListInput<TItem, TOptionValue extends UniqueIdentif
|
||||
CommonInput<TOptionValue[]>,
|
||||
"withDescription"
|
||||
> {
|
||||
AddButton: (props: { addItem: (item: TItem) => void; values: TOptionValue[] }) => React.ReactNode;
|
||||
AddButton: (props: {
|
||||
addItem: (item: TItem) => void;
|
||||
removeItem: (value: TOptionValue) => void;
|
||||
values: TOptionValue[];
|
||||
}) => React.ReactNode;
|
||||
ItemComponent: (props: {
|
||||
item: TItem;
|
||||
removeItem: () => void;
|
||||
|
||||
Reference in new issue
Block a user