feat(integrations): add search.ch integration with timetable widget (#5180)
This commit is contained in:
1 parent
279d830b79
commit
abb2dfc92a
19 files changed
+535
No files matched your search
@@ -26,5 +26,6 @@ export const widgetRouter = createTRPCRouter({
|
|||||||
networkController: lazy(() => import("./network-controller").then((mod) => mod.networkControllerRouter)),
|
networkController: lazy(() => import("./network-controller").then((mod) => mod.networkControllerRouter)),
|
||||||
firewall: lazy(() => import("./firewall").then((mod) => mod.firewallRouter)),
|
firewall: lazy(() => import("./firewall").then((mod) => mod.firewallRouter)),
|
||||||
notifications: lazy(() => import("./notifications").then((mod) => mod.notificationsRouter)),
|
notifications: lazy(() => import("./notifications").then((mod) => mod.notificationsRouter)),
|
||||||
|
timetable: lazy(() => import("./timetable").then((mod) => mod.timetableRouter)),
|
||||||
tracearr: lazy(() => import("./tracearr").then((mod) => mod.tracearrRouter)),
|
tracearr: lazy(() => import("./tracearr").then((mod) => mod.tracearrRouter)),
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
import { getIntegrationKindsByCategory } from "@homarr/definitions";
|
||||||
|
import { timetableOptionsSchema } from "@homarr/integrations/types";
|
||||||
|
import {
|
||||||
|
timetableGetTimetableRequestHandler,
|
||||||
|
timetableSearchStationsRequestHandler,
|
||||||
|
} from "@homarr/request-handler/timetable";
|
||||||
|
|
||||||
|
import { createOneIntegrationMiddleware } from "../../middlewares/integration";
|
||||||
|
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||||
|
|
||||||
|
export const timetableRouter = createTRPCRouter({
|
||||||
|
getTimetable: publicProcedure
|
||||||
|
.concat(createOneIntegrationMiddleware("query", ...getIntegrationKindsByCategory("timetable")))
|
||||||
|
.input(timetableOptionsSchema)
|
||||||
|
.query(async ({ input, ctx }) => {
|
||||||
|
const innerHandler = timetableGetTimetableRequestHandler.handler(ctx.integration, {
|
||||||
|
stationId: input.stationId,
|
||||||
|
limit: input.limit,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}),
|
||||||
|
searchStations: publicProcedure
|
||||||
|
.concat(createOneIntegrationMiddleware("query", ...getIntegrationKindsByCategory("timetable")))
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
query: z.string(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.query(async ({ input, ctx }) => {
|
||||||
|
const innerHandler = timetableSearchStationsRequestHandler.handler(ctx.integration, {
|
||||||
|
query: input.query,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -18,6 +18,7 @@ import { mediaServerJob } from "./jobs/integrations/media-server";
|
|||||||
import { mediaTranscodingJob } from "./jobs/integrations/media-transcoding";
|
import { mediaTranscodingJob } from "./jobs/integrations/media-transcoding";
|
||||||
import { networkControllerJob } from "./jobs/integrations/network-controller";
|
import { networkControllerJob } from "./jobs/integrations/network-controller";
|
||||||
import { refreshNotificationsJob } from "./jobs/integrations/notifications";
|
import { refreshNotificationsJob } from "./jobs/integrations/notifications";
|
||||||
|
import { timetableJob } from "./jobs/integrations/timetable";
|
||||||
import { tracearrJob } from "./jobs/integrations/tracearr";
|
import { tracearrJob } from "./jobs/integrations/tracearr";
|
||||||
import { minecraftServerStatusJob } from "./jobs/minecraft-server-status";
|
import { minecraftServerStatusJob } from "./jobs/minecraft-server-status";
|
||||||
import { pingJob } from "./jobs/ping";
|
import { pingJob } from "./jobs/ping";
|
||||||
@@ -51,6 +52,7 @@ export const jobGroup = createCronJobGroup({
|
|||||||
firewallInterfaces: firewallInterfacesJob,
|
firewallInterfaces: firewallInterfacesJob,
|
||||||
refreshNotifications: refreshNotificationsJob,
|
refreshNotifications: refreshNotificationsJob,
|
||||||
weather: weatherJob,
|
weather: weatherJob,
|
||||||
|
timetable: timetableJob,
|
||||||
tracearr: tracearrJob,
|
tracearr: tracearrJob,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { EVERY_5_MINUTES } from "@homarr/cron-jobs-core/expressions";
|
||||||
|
import { createRequestIntegrationJobHandler } from "@homarr/request-handler/lib/cached-request-integration-job-handler";
|
||||||
|
import { timetableGetTimetableRequestHandler } from "@homarr/request-handler/timetable";
|
||||||
|
|
||||||
|
import { createCronJob } from "../../lib";
|
||||||
|
|
||||||
|
export const timetableJob = createCronJob("timetable", EVERY_5_MINUTES).withCallback(
|
||||||
|
createRequestIntegrationJobHandler(timetableGetTimetableRequestHandler.handler, {
|
||||||
|
widgetKinds: ["timetable"],
|
||||||
|
getInput: {
|
||||||
|
timetable: (options) =>
|
||||||
|
options.station
|
||||||
|
? {
|
||||||
|
stationId: options.station.value,
|
||||||
|
limit: 10,
|
||||||
|
}
|
||||||
|
: [],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
@@ -334,6 +334,15 @@ export const integrationDefs = {
|
|||||||
// @ts-expect-error - docs page will be created when integration is merged
|
// @ts-expect-error - docs page will be created when integration is merged
|
||||||
documentationUrl: createDocumentationLink("/docs/integrations/coolify"),
|
documentationUrl: createDocumentationLink("/docs/integrations/coolify"),
|
||||||
},
|
},
|
||||||
|
searchCh: {
|
||||||
|
name: "Search.ch",
|
||||||
|
secretKinds: [[]],
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/search-ch.png",
|
||||||
|
defaultUrl: "https://search.ch",
|
||||||
|
category: ["timetable"],
|
||||||
|
// @ts-expect-error - docs page will be created when integration is merged
|
||||||
|
documentationUrl: createDocumentationLink("/docs/integrations/search-ch"),
|
||||||
|
},
|
||||||
immich: {
|
immich: {
|
||||||
name: "Immich",
|
name: "Immich",
|
||||||
secretKinds: [["apiKey"]],
|
secretKinds: [["apiKey"]],
|
||||||
@@ -434,6 +443,7 @@ export const integrationCategories = [
|
|||||||
"releasesProvider",
|
"releasesProvider",
|
||||||
"notifications",
|
"notifications",
|
||||||
"firewall",
|
"firewall",
|
||||||
|
"timetable",
|
||||||
"photoService",
|
"photoService",
|
||||||
"mediaMonitoring",
|
"mediaMonitoring",
|
||||||
] as const;
|
] as const;
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ export const widgetKinds = [
|
|||||||
"systemResources",
|
"systemResources",
|
||||||
"coolify",
|
"coolify",
|
||||||
"systemDisks",
|
"systemDisks",
|
||||||
|
"timetable",
|
||||||
"immich-serverStats",
|
"immich-serverStats",
|
||||||
"immich-albumCarousel",
|
"immich-albumCarousel",
|
||||||
"tracearr",
|
"tracearr",
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import { PlexIntegration } from "../plex/plex-integration";
|
|||||||
import { ProwlarrIntegration } from "../prowlarr/prowlarr-integration";
|
import { ProwlarrIntegration } from "../prowlarr/prowlarr-integration";
|
||||||
import { ProxmoxIntegration } from "../proxmox/proxmox-integration";
|
import { ProxmoxIntegration } from "../proxmox/proxmox-integration";
|
||||||
import { QuayIntegration } from "../quay/quay-integration";
|
import { QuayIntegration } from "../quay/quay-integration";
|
||||||
|
import { SearchChIntegration } from "../search-ch/search-ch-integration";
|
||||||
import { SeerrIntegration } from "../seerr/seerr-integration";
|
import { SeerrIntegration } from "../seerr/seerr-integration";
|
||||||
import { TracearrIntegration } from "../tracearr/tracearr-integration";
|
import { TracearrIntegration } from "../tracearr/tracearr-integration";
|
||||||
import { TrueNasIntegration } from "../truenas/truenas-integration";
|
import { TrueNasIntegration } from "../truenas/truenas-integration";
|
||||||
@@ -114,6 +115,7 @@ export const integrationCreators = {
|
|||||||
coolify: CoolifyIntegration,
|
coolify: CoolifyIntegration,
|
||||||
tracearr: TracearrIntegration,
|
tracearr: TracearrIntegration,
|
||||||
glances: GlancesIntegration,
|
glances: GlancesIntegration,
|
||||||
|
searchCh: SearchChIntegration,
|
||||||
immich: ImmichIntegration,
|
immich: ImmichIntegration,
|
||||||
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
|
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import type { Station, Timetable, TimetableOptions } from "./timetable-types";
|
||||||
|
|
||||||
|
export interface TimetableIntegration {
|
||||||
|
searchStationsAsync(query: string): Promise<Station[]>;
|
||||||
|
getTimetableAsync(options: TimetableOptions): Promise<Timetable>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
export interface Station {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const timetableOptionsSchema = z.object({
|
||||||
|
stationId: z.string(),
|
||||||
|
limit: z.number().default(10),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TimetableOptions = z.infer<typeof timetableOptionsSchema>;
|
||||||
|
|
||||||
|
export interface TimetableEntry {
|
||||||
|
timestamp: Date;
|
||||||
|
delay: number;
|
||||||
|
line: {
|
||||||
|
name: string;
|
||||||
|
color: string | null;
|
||||||
|
} | null;
|
||||||
|
location: string;
|
||||||
|
platform: {
|
||||||
|
name: string;
|
||||||
|
hasChanged: boolean;
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Timetable {
|
||||||
|
stationId: string;
|
||||||
|
timestamp: Date;
|
||||||
|
entries: TimetableEntry[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
import { ResponseError } from "@homarr/common/server";
|
||||||
|
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||||
|
|
||||||
|
import type { IntegrationTestingInput } from "../base/integration";
|
||||||
|
import { Integration } from "../base/integration";
|
||||||
|
import { TestConnectionError } from "../base/test-connection/test-connection-error";
|
||||||
|
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||||
|
import type { TimetableIntegration } from "../interfaces/timetable/timetable-integration";
|
||||||
|
import type { Station, Timetable, TimetableOptions } from "../interfaces/timetable/timetable-types";
|
||||||
|
|
||||||
|
const supportedStationTypes = ["bus", "tram", "train", "ship", "cablecar", "funicular", "chairlift"];
|
||||||
|
|
||||||
|
export class SearchChIntegration extends Integration implements TimetableIntegration {
|
||||||
|
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
||||||
|
const response = await input.fetchAsync(this.url("/timetable/api/completion.json", { term: "Zürich" }));
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return TestConnectionError.StatusResult(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches for stations matching the given query.
|
||||||
|
* @param query The search query for station names.
|
||||||
|
* @returns A list of stations matching the search query.
|
||||||
|
* @docs https://search.ch/fahrplan/api/help
|
||||||
|
*/
|
||||||
|
public async searchStationsAsync(query: string): Promise<Station[]> {
|
||||||
|
const response = await fetchWithTrustedCertificatesAsync(
|
||||||
|
this.url("/timetable/api/completion.json", {
|
||||||
|
term: query,
|
||||||
|
show_ids: 1,
|
||||||
|
nofavorites: 1,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ResponseError(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await searchSchema.parseAsync(await response.json());
|
||||||
|
|
||||||
|
return (
|
||||||
|
data
|
||||||
|
// Remove completions like addresses, we only want stations.
|
||||||
|
.filter((item) => supportedStationTypes.some((type) => item.iconclass.endsWith(type)))
|
||||||
|
.map((item) => (item.id !== undefined ? { id: item.id, name: item.label } : null))
|
||||||
|
.filter((item) => item !== null)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the departure timetable for a given station.
|
||||||
|
* @param options Timetable options including station ID and limit.
|
||||||
|
* @returns timetable for the given station.
|
||||||
|
* @docs https://search.ch/fahrplan/api/help
|
||||||
|
*/
|
||||||
|
public async getTimetableAsync(options: TimetableOptions): Promise<Timetable> {
|
||||||
|
const now = new Date();
|
||||||
|
// The following format is used [01.01.2000, 23:59:00]. The API allows usage of DD.MM.YYYY format and HH:mm format
|
||||||
|
const [date, time] = now.toLocaleString("en-CH", { timeZone: "Europe/Zurich" }).split(", ") as [string, string];
|
||||||
|
|
||||||
|
const response = await fetchWithTrustedCertificatesAsync(
|
||||||
|
this.url("/timetable/api/stationboard.json", {
|
||||||
|
stop: options.stationId,
|
||||||
|
limit: options.limit,
|
||||||
|
show_delays: 1,
|
||||||
|
show_tracks: 1,
|
||||||
|
date,
|
||||||
|
time: time.substring(0, 5), // Only keep the HH:mm part of the time, as that's what the API expects
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ResponseError(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await timetableSchema.parseAsync(await response.json());
|
||||||
|
|
||||||
|
return {
|
||||||
|
stationId: options.stationId,
|
||||||
|
timestamp: now,
|
||||||
|
entries: data.connections.map((connection) => {
|
||||||
|
// Color is in format A35~F10~ for foreground and background color. Some only have ~~ and therefore no color
|
||||||
|
const color = connection.color.split("~")[0];
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestamp: connection.time,
|
||||||
|
line: connection.line
|
||||||
|
? {
|
||||||
|
name: connection.line,
|
||||||
|
color: color && color.length >= 1 ? `#${color}` : null,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
location: connection.terminal.name,
|
||||||
|
delay: connection.dep_delay,
|
||||||
|
platform: connection.track
|
||||||
|
? {
|
||||||
|
// If the track name contains "!", it indicates a change in the track
|
||||||
|
// so we remove the "!" from the name and set hasChanged to true
|
||||||
|
name: connection.track.replace("!", ""),
|
||||||
|
hasChanged: connection.track.includes("!"),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const timetableSchema = z.object({
|
||||||
|
connections: z.array(
|
||||||
|
z.object({
|
||||||
|
time: z.string().transform((str) => new Date(str)),
|
||||||
|
line: z.string().optional(),
|
||||||
|
color: z.string(),
|
||||||
|
terminal: z.object({
|
||||||
|
name: z.string(),
|
||||||
|
}),
|
||||||
|
track: z.string().optional(),
|
||||||
|
dep_delay: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.transform((str) => (str ? parseInt(str) : 0)),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const searchSchema = z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
label: z.string(),
|
||||||
|
iconclass: z.string(), // This is in format sl-icon-type-{type}
|
||||||
|
}),
|
||||||
|
);
|
||||||
@@ -12,4 +12,5 @@ export * from "./unifi-controller/unifi-controller-types";
|
|||||||
export * from "./opnsense/opnsense-types";
|
export * from "./opnsense/opnsense-types";
|
||||||
export * from "./interfaces/media-releases";
|
export * from "./interfaces/media-releases";
|
||||||
export * from "./coolify/coolify-types";
|
export * from "./coolify/coolify-types";
|
||||||
|
export * from "./interfaces/timetable/timetable-types";
|
||||||
export * from "./tracearr/tracearr-types";
|
export * from "./tracearr/tracearr-types";
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import type { IntegrationKindByCategory } from "@homarr/definitions";
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { Station, Timetable } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
|
||||||
|
|
||||||
|
export const timetableSearchStationsRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
Station[],
|
||||||
|
IntegrationKindByCategory<"timetable">,
|
||||||
|
{ query: string }
|
||||||
|
>({
|
||||||
|
async requestAsync(integration, input) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.searchStationsAsync(input.query);
|
||||||
|
},
|
||||||
|
queryKey: "timetableSearchStations",
|
||||||
|
cacheDuration: dayjs.duration(1, "day"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const timetableGetTimetableRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
Timetable,
|
||||||
|
IntegrationKindByCategory<"timetable">,
|
||||||
|
{ stationId: string; limit: number }
|
||||||
|
>({
|
||||||
|
async requestAsync(integration, input) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.getTimetableAsync({
|
||||||
|
stationId: input.stationId,
|
||||||
|
limit: input.limit,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
queryKey: "timetableGetTimetable",
|
||||||
|
cacheDuration: dayjs.duration(1, "minute"),
|
||||||
|
});
|
||||||
@@ -1525,6 +1525,17 @@
|
|||||||
"offline": "Offline"
|
"offline": "Offline"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"timetable": {
|
||||||
|
"name": "Timetable",
|
||||||
|
"description": "Displays departure times for a station",
|
||||||
|
"title": "Departures {station}",
|
||||||
|
"noStation": "No station selected",
|
||||||
|
"option": {
|
||||||
|
"station": {
|
||||||
|
"label": "Station"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"notebook": {
|
"notebook": {
|
||||||
"name": "Notebook",
|
"name": "Notebook",
|
||||||
"description": "A simple notebook widget that supports markdown",
|
"description": "A simple notebook widget that supports markdown",
|
||||||
@@ -3513,6 +3524,9 @@
|
|||||||
"minecraftServerStatus": {
|
"minecraftServerStatus": {
|
||||||
"label": "Minecraft server status"
|
"label": "Minecraft server status"
|
||||||
},
|
},
|
||||||
|
"timetable": {
|
||||||
|
"label": "Timetable"
|
||||||
|
},
|
||||||
"iconsUpdater": {
|
"iconsUpdater": {
|
||||||
"label": "Icons Updater"
|
"label": "Icons Updater"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { WidgetOptionType } from "../options";
|
import type { WidgetOptionType } from "../options";
|
||||||
import { WidgetAppInput } from "./widget-app-input";
|
import { WidgetAppInput } from "./widget-app-input";
|
||||||
|
import { WidgetDynamicSelectInput } from "./widget-dynamic-select-input";
|
||||||
import { WidgetLocationInput } from "./widget-location-input";
|
import { WidgetLocationInput } from "./widget-location-input";
|
||||||
import { WidgetMultiTextInput } from "./widget-multi-text-input";
|
import { WidgetMultiTextInput } from "./widget-multi-text-input";
|
||||||
import { WidgetMultiReleasesRepositoriesInput } from "./widget-multiReleasesRepositories-input";
|
import { WidgetMultiReleasesRepositoriesInput } from "./widget-multiReleasesRepositories-input";
|
||||||
@@ -23,6 +24,7 @@ const mapping = {
|
|||||||
app: WidgetAppInput,
|
app: WidgetAppInput,
|
||||||
sortableItemList: WidgetSortedItemListInput,
|
sortableItemList: WidgetSortedItemListInput,
|
||||||
multiReleasesRepositories: WidgetMultiReleasesRepositoriesInput,
|
multiReleasesRepositories: WidgetMultiReleasesRepositoriesInput,
|
||||||
|
dynamicSelect: WidgetDynamicSelectInput,
|
||||||
} satisfies Record<WidgetOptionType, unknown>;
|
} satisfies Record<WidgetOptionType, unknown>;
|
||||||
|
|
||||||
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
|
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Group, Loader, Select } from "@mantine/core";
|
||||||
|
import { useDebouncedValue } from "@mantine/hooks";
|
||||||
|
import { IconCheck } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { translateIfNecessary } from "@homarr/translation";
|
||||||
|
import { useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import type { CommonWidgetInputProps } from "./common";
|
||||||
|
import { useWidgetInputTranslation } from "./common";
|
||||||
|
import { useFormContext } from "./form";
|
||||||
|
|
||||||
|
export interface DynamicSelectOption {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const WidgetDynamicSelectInput = ({ property, kind, options }: CommonWidgetInputProps<"dynamicSelect">) => {
|
||||||
|
const t = useI18n();
|
||||||
|
const tWidget = useWidgetInputTranslation(kind, property);
|
||||||
|
const form = useFormContext();
|
||||||
|
const inputProps = form.getInputProps(`options.${property}`);
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [debouncedSearch] = useDebouncedValue(search, 300);
|
||||||
|
const { isPending, options: selectOptions } = options.useOptions(debouncedSearch, form.values.integrationIds);
|
||||||
|
const value = inputProps.value as DynamicSelectOption | null;
|
||||||
|
const onChange = inputProps.onChange as (value: DynamicSelectOption | null) => void;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Select
|
||||||
|
label={tWidget("label")}
|
||||||
|
data={selectOptions
|
||||||
|
.map((option) =>
|
||||||
|
typeof option === "string"
|
||||||
|
? option
|
||||||
|
: {
|
||||||
|
value: option.value,
|
||||||
|
label: translateIfNecessary(t, option.label) ?? option.value,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.concat(
|
||||||
|
typeof value === "object" &&
|
||||||
|
value !== null &&
|
||||||
|
!selectOptions.some((option) =>
|
||||||
|
typeof option === "string" ? option === value.value : option.value === value.value,
|
||||||
|
)
|
||||||
|
? {
|
||||||
|
value: value.value,
|
||||||
|
label: value.label,
|
||||||
|
}
|
||||||
|
: [],
|
||||||
|
)}
|
||||||
|
searchValue={search}
|
||||||
|
onSearchChange={setSearch}
|
||||||
|
leftSection={isPending && <Loader size="xs" />}
|
||||||
|
renderOption={({ option, checked }) => {
|
||||||
|
return (
|
||||||
|
<Group flex="1" gap="xs">
|
||||||
|
{option.label}
|
||||||
|
{checked && (
|
||||||
|
<IconCheck
|
||||||
|
style={{ marginInlineStart: "auto" }}
|
||||||
|
color="currentColor"
|
||||||
|
opacity={0.6}
|
||||||
|
size={18}
|
||||||
|
stroke={1.5}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
description={options.withDescription ? tWidget("description") : undefined}
|
||||||
|
searchable
|
||||||
|
{...inputProps}
|
||||||
|
value={value?.value ?? null}
|
||||||
|
onChange={(value) =>
|
||||||
|
onChange(
|
||||||
|
value
|
||||||
|
? {
|
||||||
|
value,
|
||||||
|
label:
|
||||||
|
selectOptions.filter((option) => typeof option === "object").find((option) => option.value === value)
|
||||||
|
?.label ?? value,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -42,6 +42,7 @@ import * as smartHomeExecuteAutomation from "./smart-home/execute-automation";
|
|||||||
import * as stockPrice from "./stocks";
|
import * as stockPrice from "./stocks";
|
||||||
import * as systemDisks from "./system-disks";
|
import * as systemDisks from "./system-disks";
|
||||||
import * as systemResources from "./system-resources";
|
import * as systemResources from "./system-resources";
|
||||||
|
import * as timetable from "./timetable";
|
||||||
import * as tracearr from "./tracearr";
|
import * as tracearr from "./tracearr";
|
||||||
import * as video from "./video";
|
import * as video from "./video";
|
||||||
import * as weather from "./weather";
|
import * as weather from "./weather";
|
||||||
@@ -82,6 +83,7 @@ export const widgetImports = {
|
|||||||
systemResources,
|
systemResources,
|
||||||
coolify,
|
coolify,
|
||||||
systemDisks,
|
systemDisks,
|
||||||
|
timetable,
|
||||||
"immich-serverStats": immichServerStats,
|
"immich-serverStats": immichServerStats,
|
||||||
"immich-albumCarousel": immichAlbumCarousel,
|
"immich-albumCarousel": immichAlbumCarousel,
|
||||||
tracearr,
|
tracearr,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import type { ZodType } from "zod/v4";
|
|||||||
|
|
||||||
import type { IntegrationKind } from "@homarr/definitions";
|
import type { IntegrationKind } from "@homarr/definitions";
|
||||||
|
|
||||||
|
import type { DynamicSelectOption } from "./_inputs/widget-dynamic-select-input";
|
||||||
import type { inferSelectOptionValue, SelectOption } from "./_inputs/widget-select-input";
|
import type { inferSelectOptionValue, SelectOption } from "./_inputs/widget-select-input";
|
||||||
import type { ReleasesRepository } from "./releases/releases-repository";
|
import type { ReleasesRepository } from "./releases/releases-repository";
|
||||||
|
|
||||||
@@ -47,6 +48,16 @@ interface SelectInput<TOptions extends readonly SelectOption[]> extends CommonIn
|
|||||||
searchable?: boolean;
|
searchable?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DynamicSelectInput extends CommonInput<DynamicSelectOption | null> {
|
||||||
|
useOptions: (
|
||||||
|
query: string,
|
||||||
|
integrationIds: string[],
|
||||||
|
) => {
|
||||||
|
isPending: boolean;
|
||||||
|
options: DynamicSelectOption[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface NumberInput extends CommonInput<number> {
|
interface NumberInput extends CommonInput<number> {
|
||||||
validate: z.ZodNumber;
|
validate: z.ZodNumber;
|
||||||
step?: number;
|
step?: number;
|
||||||
@@ -82,6 +93,12 @@ const optionsFactory = {
|
|||||||
searchable: input.searchable ?? false,
|
searchable: input.searchable ?? false,
|
||||||
withDescription: input.withDescription ?? false,
|
withDescription: input.withDescription ?? false,
|
||||||
}),
|
}),
|
||||||
|
dynamicSelect: (input: DynamicSelectInput) => ({
|
||||||
|
type: "dynamicSelect" as const,
|
||||||
|
defaultValue: input.defaultValue ?? null,
|
||||||
|
useOptions: input.useOptions,
|
||||||
|
withDescription: input.withDescription ?? false,
|
||||||
|
}),
|
||||||
select: <const TOptions extends SelectOption[]>(input: SelectInput<TOptions>) => ({
|
select: <const TOptions extends SelectOption[]>(input: SelectInput<TOptions>) => ({
|
||||||
type: "select" as const,
|
type: "select" as const,
|
||||||
defaultValue: (input.defaultValue ?? input.options[0]) as inferSelectOptionValue<TOptions[number]>,
|
defaultValue: (input.defaultValue ?? input.options[0]) as inferSelectOptionValue<TOptions[number]>,
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { Badge, Center, Group, Stack, Text } from "@mantine/core";
|
||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import type { DynamicSelectOption } from "../_inputs/widget-dynamic-select-input";
|
||||||
|
import type { WidgetComponentProps } from "../definition";
|
||||||
|
|
||||||
|
export default function TimetableWidget({ options, integrationIds }: WidgetComponentProps<"timetable">) {
|
||||||
|
// It will always have at least one integration as otherwise the NoIntegrationSelectedError would be thrown in item-content.tsx
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
|
const integrationId = integrationIds[0]!;
|
||||||
|
const t = useScopedI18n("widget.timetable");
|
||||||
|
|
||||||
|
if (!options.station) {
|
||||||
|
return <Center h="100%">{t("noStation")}</Center>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <TimetableWidgetInner station={options.station} integrationId={integrationId} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimetableWidgetInnerProps {
|
||||||
|
station: DynamicSelectOption;
|
||||||
|
integrationId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TimetableWidgetInner = ({ station, integrationId }: TimetableWidgetInnerProps) => {
|
||||||
|
const [timetable] = clientApi.widget.timetable.getTimetable.useSuspenseQuery({
|
||||||
|
integrationId,
|
||||||
|
stationId: station.value,
|
||||||
|
limit: 10,
|
||||||
|
});
|
||||||
|
const t = useScopedI18n("widget.timetable");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack w="100%" gap="xs" p="sm">
|
||||||
|
<Text fw="bold">{t("title", { station: station.label })}</Text>
|
||||||
|
{timetable.entries.map((entry) => (
|
||||||
|
<Group key={`${entry.timestamp.toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
||||||
|
<Group gap="sm">
|
||||||
|
{entry.line && (
|
||||||
|
<Badge
|
||||||
|
size="sm"
|
||||||
|
color={entry.line.color ?? undefined}
|
||||||
|
variant={entry.line.color ? "filled" : "default"}
|
||||||
|
w={32}
|
||||||
|
p={0}
|
||||||
|
radius={0}
|
||||||
|
>
|
||||||
|
{entry.line.name}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
<Text size="sm">
|
||||||
|
{dayjs(entry.timestamp).format("HH:mm")}{" "}
|
||||||
|
{entry.delay >= 1 && (
|
||||||
|
<Text size="sm" span c="red">
|
||||||
|
+{entry.delay}'
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Text size="sm">{entry.location}</Text>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{entry.platform && (
|
||||||
|
<Text size="sm" c={entry.platform.hasChanged ? "red" : undefined}>
|
||||||
|
{entry.platform.name}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { IconBusStop } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
|
||||||
|
import { createWidgetDefinition } from "../definition";
|
||||||
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
|
export const { componentLoader, definition } = createWidgetDefinition("timetable", {
|
||||||
|
icon: IconBusStop,
|
||||||
|
supportedIntegrations: ["searchCh"],
|
||||||
|
createOptions() {
|
||||||
|
return optionsBuilder.from((factory) => ({
|
||||||
|
station: factory.dynamicSelect({
|
||||||
|
useOptions(query, integrationIds) {
|
||||||
|
const { data: stations, isPending } = clientApi.widget.timetable.searchStations.useQuery(
|
||||||
|
{
|
||||||
|
integrationId: integrationIds[0] ?? "",
|
||||||
|
query,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
enabled: integrationIds.length > 0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isPending,
|
||||||
|
options:
|
||||||
|
stations?.map((station) => ({
|
||||||
|
label: station.name,
|
||||||
|
value: station.id,
|
||||||
|
})) ?? [],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
}).withDynamicImport(() => import("./component"));
|
||||||
Reference in new issue
Block a user