feat: Add widget integration option (#14)

* wip: add widget integrations

* feat: Add integration option to widgets

* feat: Add translation for widget integration select

* fix: formatting issue

* chore: address pull request feedback
This commit is contained in:
Meier Lukas
2024-02-03 10:24:39 +01:00
committed by GitHub
parent 3a0f280984
commit 1740450648
22 changed files with 378 additions and 55 deletions

View File

@@ -2,5 +2,7 @@
import { createFormContext } from "@homarr/form";
import type { WidgetEditModalState } from "../modals/widget-edit-modal";
export const [FormProvider, useFormContext, useForm] =
createFormContext<Record<string, unknown>>();
createFormContext<WidgetEditModalState>();

View File

@@ -19,7 +19,7 @@ export const WidgetMultiSelectInput = ({
label={t("label")}
data={options.options as unknown as string[]}
description={options.withDescription ? t("description") : undefined}
{...form.getInputProps(property)}
{...form.getInputProps(`options.${property}`)}
/>
);
};

View File

@@ -21,7 +21,7 @@ export const WidgetNumberInput = ({
min={options.validate.minValue ?? undefined}
max={options.validate.maxValue ?? undefined}
step={options.step}
{...form.getInputProps(property)}
{...form.getInputProps(`options.${property}`)}
/>
);
};

View File

@@ -19,7 +19,7 @@ export const WidgetSelectInput = ({
label={t("label")}
data={options.options as unknown as string[]}
description={options.withDescription ? t("description") : undefined}
{...form.getInputProps(property)}
{...form.getInputProps(`options.${property}`)}
/>
);
};

View File

@@ -23,7 +23,7 @@ export const WidgetSliderInput = ({
min={options.validate.minValue ?? undefined}
max={options.validate.maxValue ?? undefined}
step={options.step}
{...form.getInputProps(property)}
{...form.getInputProps(`options.${property}`)}
/>
</InputWrapper>
);

View File

@@ -18,7 +18,7 @@ export const WidgetSwitchInput = ({
<Switch
label={t("label")}
description={options.withDescription ? t("description") : undefined}
{...form.getInputProps(property, { type: "checkbox" })}
{...form.getInputProps(`options.${property}`, { type: "checkbox" })}
/>
);
};

View File

@@ -18,7 +18,7 @@ export const WidgetTextInput = ({
<TextInput
label={t("label")}
description={options.withDescription ? t("description") : undefined}
{...form.getInputProps(property)}
{...form.getInputProps(`options.${property}`)}
/>
);
};

View File

@@ -1,7 +1,8 @@
import type { WidgetComponentProps } from "../definition";
export default function ClockWidget({
options,
options: _options,
integrations: _integrations,
}: WidgetComponentProps<"clock">) {
return <pre>{JSON.stringify(options)}</pre>;
return <div>CLOCK</div>;
}

View File

@@ -5,6 +5,7 @@ import { opt } from "../options";
export const { definition, componentLoader } = createWidgetDefinition("clock", {
icon: IconClock,
supportedIntegrations: ["adGuardHome", "piHole"],
options: opt.from(
(fac) => ({
is24HourFormat: fac.switch({

View File

@@ -1,5 +1,6 @@
import type { LoaderComponent } from "next/dynamic";
import type { IntegrationKind } from "@homarr/definitions";
import type { TablerIconsProps } from "@homarr/ui";
import type { WidgetImports, WidgetSort } from ".";
@@ -7,6 +8,7 @@ import type {
inferOptionsFromDefinition,
WidgetOptionsRecord,
} from "./options";
import type { IntegrationSelectOption } from "./widget-integration-select";
export const createWidgetDefinition = <
TSort extends WidgetSort,
@@ -28,12 +30,31 @@ export const createWidgetDefinition = <
interface Definition {
icon: (props: TablerIconsProps) => JSX.Element;
supportedIntegrations?: IntegrationKind[];
options: WidgetOptionsRecord;
}
export interface WidgetComponentProps<TSort extends WidgetSort> {
options: inferOptionsFromDefinition<WidgetOptionsRecordOf<TSort>>;
integrations: unknown[];
integrations: inferIntegrationsFromDefinition<
WidgetImports[TSort]["definition"]
>;
}
type inferIntegrationsFromDefinition<TDefinition extends Definition> =
TDefinition extends {
supportedIntegrations: infer TSupportedIntegrations;
} // check if definition has supportedIntegrations
? TSupportedIntegrations extends IntegrationKind[] // check if supportedIntegrations is an array of IntegrationKind
? IntegrationSelectOptionFor<TSupportedIntegrations[number]>[] // if so, return an array of IntegrationSelectOptionFor
: IntegrationSelectOption[] // otherwise, return an array of IntegrationSelectOption without specifying the kind
: IntegrationSelectOption[];
interface IntegrationSelectOptionFor<TIntegration extends IntegrationKind> {
id: string;
name: string;
url: string;
kind: TIntegration[number];
}
export type WidgetOptionsRecordOf<TSort extends WidgetSort> =

View File

@@ -8,7 +8,9 @@ import type { WidgetComponentProps } from "./definition";
import type { WidgetImportRecord } from "./import";
import * as weather from "./weather";
export { WidgetEditModal } from "./WidgetEditModal";
export { reduceWidgetOptionsWithDefaultValues } from "./options";
export { WidgetEditModal } from "./modals/widget-edit-modal";
export const widgetSorts = ["clock", "weather"] as const;

View File

@@ -3,27 +3,35 @@
import type { Dispatch, SetStateAction } from "react";
import type { ManagedModal } from "mantine-modal-manager";
import { useScopedI18n } from "@homarr/translation/client";
import { Button, Group, Stack } from "@homarr/ui";
import type { WidgetSort } from ".";
import { getInputForType } from "./_inputs";
import { FormProvider, useForm } from "./_inputs/form";
import type { WidgetOptionsRecordOf } from "./definition";
import type { WidgetOptionDefinition } from "./options";
import type { WidgetSort } from "..";
import { getInputForType } from "../_inputs";
import { FormProvider, useForm } from "../_inputs/form";
import type { WidgetOptionsRecordOf } from "../definition";
import type { WidgetOptionDefinition } from "../options";
import { WidgetIntegrationSelect } from "../widget-integration-select";
import type { IntegrationSelectOption } from "../widget-integration-select";
export interface WidgetEditModalState {
options: Record<string, unknown>;
integrations: string[];
}
interface ModalProps<TSort extends WidgetSort> {
sort: TSort;
state: [
Record<string, unknown>,
Dispatch<SetStateAction<Record<string, unknown>>>,
];
state: [WidgetEditModalState, Dispatch<SetStateAction<WidgetEditModalState>>];
definition: WidgetOptionsRecordOf<TSort>;
integrationData: IntegrationSelectOption[];
integrationSupport: boolean;
}
export const WidgetEditModal: ManagedModal<ModalProps<WidgetSort>> = ({
actions,
innerProps,
}) => {
const t = useScopedI18n("widget.editModal");
const [value, setValue] = innerProps.state;
const form = useForm({
initialValues: value,
@@ -38,6 +46,13 @@ export const WidgetEditModal: ManagedModal<ModalProps<WidgetSort>> = ({
>
<FormProvider form={form}>
<Stack>
{innerProps.integrationSupport && (
<WidgetIntegrationSelect
label={t("integrations.label")}
data={innerProps.integrationData}
{...form.getInputProps("integrations")}
/>
)}
{Object.entries(innerProps.definition).map(
([key, value]: [string, WidgetOptionDefinition]) => {
const Input = getInputForType(value.type);

View File

@@ -1,3 +1,4 @@
import { objectEntries } from "@homarr/common";
import type { z } from "@homarr/validation";
interface CommonInput<TType> {
@@ -140,3 +141,15 @@ const createOptions = <TOptions extends WidgetOptionsRecord>(
export const opt = {
from: createOptions,
};
export const reduceWidgetOptionsWithDefaultValues = (
optionsDefinition: Record<string, WidgetOptionDefinition>,
currentValue: Record<string, unknown> = {},
) =>
objectEntries(optionsDefinition).reduce(
(prev, [key, value]) => ({
...prev,
[key]: currentValue[key] ?? value.defaultValue,
}),
{} as Record<string, unknown>,
);

View File

@@ -1,7 +1,7 @@
import type { WidgetComponentProps } from "../definition";
export default function WeatherWidget({
options,
options: _options,
}: WidgetComponentProps<"weather">) {
return <pre>{JSON.stringify(options)}</pre>;
return <div>WEATHER</div>;
}

View File

@@ -0,0 +1,11 @@
.pill {
cursor: default;
background-color: light-dark(
var(--mantine-color-white),
var(--mantine-color-dark-7)
);
border: rem(1px) solid
light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-7));
padding-left: var(--mantine-spacing-xs);
border-radius: var(--mantine-radius-xl);
}

View File

@@ -0,0 +1,162 @@
"use client";
import type { FocusEventHandler } from "react";
import type { IntegrationKind } from "@homarr/definitions";
import { getIconUrl } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import {
Avatar,
CheckIcon,
CloseButton,
Combobox,
Group,
Input,
Pill,
PillsInput,
Stack,
Text,
useCombobox,
} from "@homarr/ui";
import classes from "./widget-integration-select.module.css";
interface WidgetIntegrationSelectProps {
label: string;
onChange: (value: string[]) => void;
value?: string[];
error?: string;
onFocus?: FocusEventHandler<HTMLInputElement>;
onBlur?: FocusEventHandler<HTMLInputElement>;
data: IntegrationSelectOption[];
}
export const WidgetIntegrationSelect = ({
data,
onChange,
value: valueProp,
...props
}: WidgetIntegrationSelectProps) => {
const t = useI18n();
const multiSelectValues = valueProp ?? [];
const combobox = useCombobox({
onDropdownClose: () => combobox.resetSelectedOption(),
onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"),
});
const handleValueSelect = (selectedValue: string) =>
onChange(
multiSelectValues.includes(selectedValue)
? multiSelectValues.filter((v) => v !== selectedValue)
: [...multiSelectValues, selectedValue],
);
const handleValueRemove = (val: string) =>
onChange(multiSelectValues.filter((v) => v !== val));
const values = multiSelectValues.map((item) => (
<IntegrationPill
key={item}
option={data.find((i) => i.id === item)!}
onRemove={() => handleValueRemove(item)}
/>
));
const options = data.map((item) => {
return (
<Combobox.Option
value={item.id}
key={item.id}
active={multiSelectValues.includes(item.id)}
>
<Group gap="sm" align="center">
{multiSelectValues.includes(item.id) ? <CheckIcon size={12} /> : null}
<Group gap={7} align="center">
<Avatar src={getIconUrl(item.kind)} size="sm" />
<Stack gap={0}>
<span>{item.name}</span>
<Text size="xs" c="gray.6">
{item.url}
</Text>
</Stack>
</Group>
</Group>
</Combobox.Option>
);
});
return (
<Combobox
store={combobox}
onOptionSubmit={handleValueSelect}
withinPortal={false}
>
<Combobox.DropdownTarget>
<PillsInput
pointer
onClick={() => combobox.toggleDropdown()}
{...props}
>
<Pill.Group>
{values.length > 0 ? (
values
) : (
<Input.Placeholder>
{t("common.multiSelect.placeholder")}
</Input.Placeholder>
)}
<Combobox.EventsTarget>
<PillsInput.Field
type="hidden"
onBlur={() => combobox.closeDropdown()}
onKeyDown={(event) => {
if (event.key !== "Backspace") return;
event.preventDefault();
handleValueRemove(
multiSelectValues[multiSelectValues.length - 1]!,
);
}}
/>
</Combobox.EventsTarget>
</Pill.Group>
</PillsInput>
</Combobox.DropdownTarget>
<Combobox.Dropdown>
<Combobox.Options>{options}</Combobox.Options>
</Combobox.Dropdown>
</Combobox>
);
};
export interface IntegrationSelectOption {
id: string;
name: string;
url: string;
kind: IntegrationKind;
}
interface IntegrationPillProps {
option: IntegrationSelectOption;
onRemove: () => void;
}
const IntegrationPill = ({ option, onRemove }: IntegrationPillProps) => (
<Group align="center" wrap="nowrap" gap={0} className={classes.pill}>
<Avatar src={getIconUrl(option.kind)} size={14} mr={6} />
<Text span size="xs" lh={1} fw={500}>
{option.name}
</Text>
<CloseButton
onMouseDown={onRemove}
variant="transparent"
color="gray"
size={22}
iconSize={14}
tabIndex={-1}
/>
</Group>
);