Migrated widget modals from integration modals

This commit is contained in:
Meierschlumpf
2022-12-18 22:58:00 +01:00
parent b4cfa1ac05
commit f98e66fcad
15 changed files with 79 additions and 132 deletions

View File

@@ -3,7 +3,7 @@
"name": "Dash.", "name": "Dash.",
"description": "A module for displaying the graphs of your running Dash. instance.", "description": "A module for displaying the graphs of your running Dash. instance.",
"settings": { "settings": {
"title": "Settings for Dash. integration", "title": "Settings for Dash. widget",
"cpuMultiView": { "cpuMultiView": {
"label": "CPU Multi-Core View" "label": "CPU Multi-Core View"
}, },
@@ -21,8 +21,8 @@
} }
}, },
"remove": { "remove": {
"title": "Remove Dash. integration", "title": "Remove Dash. widget",
"confirm": "Are you sure, that you want to remove the Dash. integration?" "confirm": "Are you sure, that you want to remove the Dash. widget?"
} }
}, },
"card": { "card": {
@@ -55,4 +55,4 @@
} }
} }
} }
} }

View File

@@ -2,10 +2,10 @@ import { SelectItem } from '@mantine/core';
import { closeModal, ContextModalProps } from '@mantine/modals'; import { closeModal, ContextModalProps } from '@mantine/modals';
import { useConfigContext } from '../../../../config/provider'; import { useConfigContext } from '../../../../config/provider';
import { useConfigStore } from '../../../../config/store'; import { useConfigStore } from '../../../../config/store';
import { IntegrationsType } from '../../../../types/integration';
import { WidgetChangePositionModalInnerProps } from '../../Tiles/Widgets/WidgetsMenu'; import { WidgetChangePositionModalInnerProps } from '../../Tiles/Widgets/WidgetsMenu';
import { Tiles } from '../../Tiles/tilesDefinitions'; import { Tiles } from '../../Tiles/tilesDefinitions';
import { ChangePositionModal } from './ChangePositionModal'; import { ChangePositionModal } from './ChangePositionModal';
import widgets from '../../../../widgets';
export const ChangeIntegrationPositionModal = ({ export const ChangeIntegrationPositionModal = ({
context, context,
@@ -63,20 +63,22 @@ export const ChangeIntegrationPositionModal = ({
); );
}; };
const useWidthData = (integration: keyof IntegrationsType): SelectItem[] => { const useWidthData = (integration: string): SelectItem[] => {
const tileDefinitions = Tiles[integration]; const currentWidget = widgets[integration as keyof typeof widgets];
const offset = tileDefinitions.minWidth ?? 2; if (!currentWidget) return [];
const length = (tileDefinitions.maxWidth ?? 12) - offset; const offset = currentWidget.gridstack.minWidth ?? 2;
const length = (currentWidget.gridstack.maxWidth ?? 12) - offset;
return Array.from({ length }, (_, i) => i + offset).map((n) => ({ return Array.from({ length }, (_, i) => i + offset).map((n) => ({
value: n.toString(), value: n.toString(),
label: `${64 * n}px`, label: `${64 * n}px`,
})); }));
}; };
const useHeightData = (integration: keyof IntegrationsType): SelectItem[] => { const useHeightData = (integration: string): SelectItem[] => {
const tileDefinitions = Tiles[integration]; const currentWidget = widgets[integration as keyof typeof widgets];
const offset = tileDefinitions.minHeight ?? 2; if (!currentWidget) return [];
const length = (tileDefinitions.maxHeight ?? 12) - offset; const offset = currentWidget.gridstack.minHeight ?? 2;
const length = (currentWidget.gridstack.maxHeight ?? 12) - offset;
return Array.from({ length }, (_, i) => i + offset).map((n) => ({ return Array.from({ length }, (_, i) => i + offset).map((n) => ({
value: n.toString(), value: n.toString(),
label: `${64 * n}px`, label: `${64 * n}px`,

View File

@@ -1,31 +1,27 @@
import Widgets from '../../../../widgets';
import { Button, Group, MultiSelect, Stack, Switch, TextInput } from '@mantine/core'; import { Button, Group, MultiSelect, Stack, Switch, TextInput } from '@mantine/core';
import { ContextModalProps } from '@mantine/modals'; import { ContextModalProps } from '@mantine/modals';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { useState } from 'react'; import { useState } from 'react';
import { useConfigContext } from '../../../../config/provider'; import { useConfigContext } from '../../../../config/provider';
import { useConfigStore } from '../../../../config/store'; import { useConfigStore } from '../../../../config/store';
import { DashDotGraphType, IntegrationsType } from '../../../../types/integration'; import { IWidget } from '../../../../widgets/widgets';
export type WidgetEditModalInnerProps< export type WidgetEditModalInnerProps = {
TIntegrationKey extends keyof IntegrationsType = keyof IntegrationsType integration: string;
> = { options: IWidget<string, any>['properties'];
integration: TIntegrationKey;
options: IntegrationOptions<TIntegrationKey> | undefined;
labels: IntegrationOptionLabels<IntegrationOptions<TIntegrationKey>>;
}; };
type IntegrationOptionsValueType = IWidget<string, any>['properties'][string];
export const WidgetsEditModal = ({ export const WidgetsEditModal = ({
context, context,
id, id,
innerProps, innerProps,
}: ContextModalProps<WidgetEditModalInnerProps>) => { }: ContextModalProps<WidgetEditModalInnerProps>) => {
const translationKey = integrationModuleTranslationsMap.get(innerProps.integration); const { t } = useTranslation([`modules/${innerProps.integration}`, 'common']);
const { t } = useTranslation([translationKey ?? '', 'common']);
const [moduleProperties, setModuleProperties] = useState(innerProps.options); const [moduleProperties, setModuleProperties] = useState(innerProps.options);
const items = Object.entries(moduleProperties ?? {}) as [ const items = Object.entries(moduleProperties ?? {}) as [string, IntegrationOptionsValueType][];
keyof typeof innerProps.options,
IntegrationOptionsValueType
][];
const { name: configName } = useConfigContext(); const { name: configName } = useConfigContext();
const updateConfig = useConfigStore((x) => x.updateConfig); const updateConfig = useConfigStore((x) => x.updateConfig);
@@ -40,6 +36,14 @@ export const WidgetsEditModal = ({
}); });
}; };
const getMutliselectData = (option: string) => {
const currentWidgetDefinition = Widgets[innerProps.integration as keyof typeof Widgets];
if (!Widgets) return [];
const options = currentWidgetDefinition.options as any;
return options[option]?.data ?? [];
};
const handleSave = () => { const handleSave = () => {
updateConfig(configName, (prev) => ({ updateConfig(configName, (prev) => ({
...prev, ...prev,
@@ -63,23 +67,24 @@ export const WidgetsEditModal = ({
<> <>
{typeof value === 'boolean' ? ( {typeof value === 'boolean' ? (
<Switch <Switch
label={t(innerProps.labels[key as keyof typeof innerProps.labels])} label={t(`descriptor.settings.${key}.label`)}
checked={value} checked={value}
onChange={(ev) => handleChange(key, ev.currentTarget.checked)} onChange={(ev) => handleChange(key, ev.currentTarget.checked)}
/> />
) : null} ) : null}
{typeof value === 'string' ? ( {typeof value === 'string' ? (
<TextInput <TextInput
label={t(innerProps.labels[key])} label={t(`descriptor.settings.${key}.label`)}
value={value} value={value}
onChange={(ev) => handleChange(key, ev.currentTarget.value)} onChange={(ev) => handleChange(key, ev.currentTarget.value)}
/> />
) : null} ) : null}
{typeof value === 'object' && Array.isArray(value) ? ( {typeof value === 'object' && Array.isArray(value) ? (
<MultiSelect <MultiSelect
data={['cpu', 'gpu', 'ram', 'storage', 'network']} data={getMutliselectData(key)}
label={t(`descriptor.settings.${key}.label`)}
value={value} value={value}
onChange={(v) => handleChange(key, v as DashDotGraphType[])} onChange={(v) => handleChange(key, v)}
/> />
) : null} ) : null}
</> </>
@@ -94,29 +99,3 @@ export const WidgetsEditModal = ({
</Stack> </Stack>
); );
}; };
type PropertiesOf<
TKey extends keyof IntegrationsType,
T extends IntegrationsType[TKey]
> = T extends { properties: unknown } ? T['properties'] : {};
export type IntegrationOptions<TKey extends keyof IntegrationsType> = PropertiesOf<
TKey,
IntegrationsType[TKey]
>;
export type IntegrationOptionLabels<TIntegrationOptions> = {
[key in keyof TIntegrationOptions]: string;
};
type IntegrationOptionsValueType = boolean | string | DashDotGraphType[];
export const integrationModuleTranslationsMap = new Map<keyof IntegrationsType, string>([
['calendar', 'modules/calendar'],
['clock', 'modules/date'],
['weather', 'modules/weather'],
['dashDot', 'modules/dashdot'],
['bitTorrent', 'modules/torrents-status'],
['useNet', 'modules/usenet'],
['torrentNetworkTraffic', 'modules/dlspeed'],
]);

View File

@@ -1,36 +1,23 @@
import { Title } from '@mantine/core'; import { Title } from '@mantine/core';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { openContextModalGeneric } from '../../../../tools/mantineModalManagerExtensions'; import { openContextModalGeneric } from '../../../../tools/mantineModalManagerExtensions';
import { IntegrationsType } from '../../../../types/integration'; import { IWidget } from '../../../../widgets/widgets';
import { TileBaseType } from '../../../../types/tile';
import { GenericTileMenu } from '../GenericTileMenu'; import { GenericTileMenu } from '../GenericTileMenu';
import { WidgetEditModalInnerProps } from './WidgetsEditModal';
import { WidgetsRemoveModalInnerProps } from './WidgetsRemoveModal'; import { WidgetsRemoveModalInnerProps } from './WidgetsRemoveModal';
import {
WidgetEditModalInnerProps,
integrationModuleTranslationsMap,
IntegrationOptionLabels,
IntegrationOptions,
} from './WidgetsEditModal';
export type WidgetChangePositionModalInnerProps = { export type WidgetChangePositionModalInnerProps = {
integration: keyof IntegrationsType; integration: string;
module: TileBaseType; module: IWidget<string, any>;
}; };
interface WidgetsMenuProps<TIntegrationKey extends keyof IntegrationsType> { interface WidgetsMenuProps {
integration: TIntegrationKey; integration: string;
module: TileBaseType | undefined; module: IWidget<string, any> | undefined;
options: IntegrationOptions<TIntegrationKey> | undefined;
labels: IntegrationOptionLabels<IntegrationOptions<TIntegrationKey>>;
} }
export const WidgetsMenu = <TIntegrationKey extends keyof IntegrationsType>({ export const WidgetsMenu = ({ integration, module }: WidgetsMenuProps) => {
integration, const { t } = useTranslation(`modules/${integration}`);
options,
labels,
module,
}: WidgetsMenuProps<TIntegrationKey>) => {
const { t } = useTranslation(integrationModuleTranslationsMap.get(integration));
if (!module) return null; if (!module) return null;
@@ -57,13 +44,12 @@ export const WidgetsMenu = <TIntegrationKey extends keyof IntegrationsType>({
}; };
const handleEditClick = () => { const handleEditClick = () => {
openContextModalGeneric<WidgetEditModalInnerProps<TIntegrationKey>>({ openContextModalGeneric<WidgetEditModalInnerProps>({
modal: 'integrationOptions', modal: 'integrationOptions',
title: <Title order={4}>{t('descriptor.settings.title')}</Title>, title: <Title order={4}>{t('descriptor.settings.title')}</Title>,
innerProps: { innerProps: {
integration, integration,
options, options: module.properties,
labels,
}, },
}); });
}; };
@@ -73,7 +59,7 @@ export const WidgetsMenu = <TIntegrationKey extends keyof IntegrationsType>({
handleClickEdit={handleEditClick} handleClickEdit={handleEditClick}
handleClickChangePosition={handleChangeSizeClick} handleClickChangePosition={handleChangeSizeClick}
handleClickDelete={handleDeleteClick} handleClickDelete={handleDeleteClick}
displayEdit={options !== undefined} displayEdit={module.properties !== undefined}
/> />
); );
}; };

View File

@@ -2,11 +2,9 @@ import React from 'react';
import { Button, Group, Stack, Text } from '@mantine/core'; import { Button, Group, Stack, Text } from '@mantine/core';
import { ContextModalProps } from '@mantine/modals'; import { ContextModalProps } from '@mantine/modals';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { IntegrationsType } from '../../../../types/integration';
import { integrationModuleTranslationsMap } from './WidgetsEditModal';
export type WidgetsRemoveModalInnerProps = { export type WidgetsRemoveModalInnerProps = {
integration: keyof IntegrationsType; integration: string;
}; };
export const WidgetsRemoveModal = ({ export const WidgetsRemoveModal = ({
@@ -14,8 +12,7 @@ export const WidgetsRemoveModal = ({
id, id,
innerProps, innerProps,
}: ContextModalProps<WidgetsRemoveModalInnerProps>) => { }: ContextModalProps<WidgetsRemoveModalInnerProps>) => {
const translationKey = integrationModuleTranslationsMap.get(innerProps.integration); const { t } = useTranslation([`modules/${innerProps.integration}`, 'common']);
const { t } = useTranslation([translationKey ?? '', 'common']);
const handleDeletion = () => { const handleDeletion = () => {
// TODO: remove tile // TODO: remove tile
context.closeModal(id); context.closeModal(id);

View File

@@ -1,5 +1,5 @@
import calendarDefinition from '../../../widgets/calendar/CalendarTile'; import calendarDefinition from '../../../widgets/calendar/CalendarTile';
import clockDefinition from '../../../widgets/clock/ClockTile'; import clockDefinition from '../../../widgets/date/DateTile';
import dashDotDefinition from '../../../widgets/dashDot/DashDotTile'; import dashDotDefinition from '../../../widgets/dashDot/DashDotTile';
import useNetDefinition from '../../../widgets/useNet/UseNetTile'; import useNetDefinition from '../../../widgets/useNet/UseNetTile';
import weatherDefinition from '../../../widgets/weather/WeatherTile'; import weatherDefinition from '../../../widgets/weather/WeatherTile';

View File

@@ -13,7 +13,7 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
const config = getConfig(configName); const config = getConfig(configName);
const dashDotUrl = config.integrations.dashDot?.properties.url; const dashDotUrl = config.integrations.dashdot?.properties.url;
if (!dashDotUrl) { if (!dashDotUrl) {
return res.status(400).json({ return res.status(400).json({

View File

@@ -13,7 +13,7 @@ async function Get(req: NextApiRequest, res: NextApiResponse) {
const config = getConfig(configName); const config = getConfig(configName);
const dashDotUrl = config.integrations.dashDot?.properties.url; const dashDotUrl = config.integrations.dashdot?.properties.url;
if (!dashDotUrl) { if (!dashDotUrl) {
return res.status(400).json({ return res.status(400).json({

View File

@@ -5,7 +5,7 @@ import { defineWidget } from '../helper';
import { IWidget } from '../widgets'; import { IWidget } from '../widgets';
const definition = defineWidget({ const definition = defineWidget({
id: 'bitTorrent', id: 'torrents-status',
icon: IconClock, icon: IconClock,
options: {}, options: {},
gridstack: { gridstack: {

View File

@@ -13,7 +13,7 @@ import { DashDotCompactStorage } from './DashDotCompactStorage';
import { DashDotGraph } from './DashDotGraph'; import { DashDotGraph } from './DashDotGraph';
const definition = defineWidget({ const definition = defineWidget({
id: 'dashDot', id: 'dashdot',
icon: 'https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/dashdot.png', icon: 'https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/dashdot.png',
options: { options: {
cpuMultiView: { cpuMultiView: {
@@ -78,18 +78,7 @@ function DashDotTile({ module, className }: DashDotTileProps) {
const menu = ( const menu = (
// TODO: add widgetWrapper that is generic and uses the definition // TODO: add widgetWrapper that is generic and uses the definition
<WidgetsMenu<'dashDot'> <WidgetsMenu module={module} integration={definition.id} />
module={module}
integration="dashDot"
options={module?.properties}
labels={{
isCpuMultiView: 'descriptor.settings.cpuMultiView.label',
isStorageMultiView: 'descriptor.settings.storageMultiView.label',
isCompactView: 'descriptor.settings.useCompactView.label',
graphs: 'descriptor.settings.graphs.label',
url: 'descriptor.settings.url.label',
}}
/>
); );
if (!dashDotUrl) { if (!dashDotUrl) {

View File

@@ -10,7 +10,7 @@ import { IWidget } from '../widgets';
import { IconClock } from '@tabler/icons'; import { IconClock } from '@tabler/icons';
const definition = defineWidget({ const definition = defineWidget({
id: 'clock', id: 'date',
icon: IconClock, icon: IconClock,
options: { options: {
display24HourFormat: { display24HourFormat: {
@@ -18,35 +18,29 @@ const definition = defineWidget({
defaultValue: false, defaultValue: false,
}, },
}, },
gridstack: { gridstack: {
minWidth: 4, minWidth: 4,
minHeight: 2, minHeight: 2,
maxWidth: 12, maxWidth: 12,
maxHeight: 12, maxHeight: 12,
}, },
component: ClockTile, component: DateTile,
}); });
export type IClockWidget = IWidget<typeof definition['id'], typeof definition>; export type IDateWidget = IWidget<typeof definition['id'], typeof definition>;
interface ClockTileProps extends BaseTileProps { interface DateTileProps extends BaseTileProps {
module: IClockWidget; // TODO: change to new type defined through widgetDefinition module: IDateWidget; // TODO: change to new type defined through widgetDefinition
} }
function ClockTile({ className, module }: ClockTileProps) { function DateTile({ className, module }: DateTileProps) {
const date = useDateState(); const date = useDateState();
const formatString = module.properties.display24HourFormat ? 'HH:mm' : 'h:mm A'; const formatString = module.properties.display24HourFormat ? 'HH:mm' : 'h:mm A';
// TODO: add widgetWrapper that is generic and uses the definition // TODO: add widgetWrapper that is generic and uses the definition
return ( return (
<HomarrCardWrapper className={className}> <HomarrCardWrapper className={className}>
<WidgetsMenu<'clock'> <WidgetsMenu integration={definition.id} module={module} />
integration="clock"
module={module}
options={module.properties}
labels={{ is24HoursFormat: 'descriptor.settings.display24HourFormat.label' }}
/>
<Center style={{ height: '100%' }}> <Center style={{ height: '100%' }}>
<Stack spacing="xs"> <Stack spacing="xs">
<Title>{dayjs(date).format(formatString)}</Title> <Title>{dayjs(date).format(formatString)}</Title>

View File

@@ -1,8 +1,16 @@
import date from './date/DateTile';
import calendar from './calendar/CalendarTile'; import calendar from './calendar/CalendarTile';
import dashDot from './dashDot/DashDotTile'; import dashdot from './dashDot/DashDotTile';
import useNet from './useNet/UseNetTile'; import usenet from './useNet/UseNetTile';
import clock from './clock/ClockTile';
import weather from './weather/WeatherTile'; import weather from './weather/WeatherTile';
import bitTorrent from './bitTorrent/BitTorrentTile'; import bitTorrent from './bitTorrent/BitTorrentTile';
import torrentNetworkTraffic from './torrentNetworkTraffic/TorrentNetworkTrafficTile'; import torrentNetworkTraffic from './torrentNetworkTraffic/TorrentNetworkTrafficTile';
export default { calendar, dashDot, useNet, clock, weather, bitTorrent, torrentNetworkTraffic }; export default {
calendar,
dashdot,
usenet,
weather,
'torrents-status': bitTorrent,
dlspeed: torrentNetworkTraffic,
date,
};

View File

@@ -5,7 +5,7 @@ import { defineWidget } from '../helper';
import { IWidget } from '../widgets'; import { IWidget } from '../widgets';
const definition = defineWidget({ const definition = defineWidget({
id: 'torrentNetworkTraffic', id: 'dlspeed',
icon: IconClock, icon: IconClock,
options: {}, options: {},

View File

@@ -32,7 +32,7 @@ dayjs.extend(duration);
const downloadServiceTypes: ServiceIntegrationType['type'][] = ['sabnzbd', 'nzbGet']; const downloadServiceTypes: ServiceIntegrationType['type'][] = ['sabnzbd', 'nzbGet'];
const definition = defineWidget({ const definition = defineWidget({
id: 'useNet', id: 'usenet',
icon: IconFileDownload, icon: IconFileDownload,
options: {}, options: {},
component: UseNetTile, component: UseNetTile,

View File

@@ -67,15 +67,7 @@ function WeatherTile({ className, module }: WeatherTileProps) {
// TODO: add widgetWrapper that is generic and uses the definition // TODO: add widgetWrapper that is generic and uses the definition
return ( return (
<HomarrCardWrapper className={className}> <HomarrCardWrapper className={className}>
<WidgetsMenu <WidgetsMenu integration={definition.id} module={module} />
integration="weather"
module={module}
options={module.properties}
labels={{
isFahrenheit: 'descriptor.settings.displayInFahrenheit.label',
location: 'descriptor.settings.location.label',
}}
/>
<Center style={{ height: '100%' }}> <Center style={{ height: '100%' }}>
<Group spacing="md" noWrap align="center"> <Group spacing="md" noWrap align="center">
<WeatherIcon code={weather!.current_weather.weathercode} /> <WeatherIcon code={weather!.current_weather.weathercode} />