feat(custom-widgets): complete Custom JSX v2 (#6390)

This commit is contained in:
Thomas authored and ajnart committed 2026-08-13 19:48:57 +02:00
1 parent 3a1245cbc5
commit acdfcbb18e
416 files changed
+37853 -18066

No files matched your search

@@ -0,0 +1,27 @@
DROP TABLE `custom_widget_secret`;--> statement-breakpoint
DROP TABLE `custom_widget_definition`;--> statement-breakpoint
CREATE TABLE `custom_widget_definition` (
`id` varchar(64) NOT NULL,
`name` varchar(256) NOT NULL,
`description` text,
`icon_url` text,
`sources` text NOT NULL,
`requests` text NOT NULL,
`options` text NOT NULL,
`template` text NOT NULL,
`enabled` boolean DEFAULT true NOT NULL,
`created_at` timestamp DEFAULT (now()) NOT NULL,
`updated_at` timestamp DEFAULT (now()) NOT NULL,
`creator_id` varchar(64),
CONSTRAINT `custom_widget_definition_id` PRIMARY KEY(`id`)
);--> statement-breakpoint
CREATE TABLE `custom_widget_secret` (
`source_id` varchar(64) NOT NULL,
`kind` varchar(64) NOT NULL,
`encrypted_value` text NOT NULL,
`updated_at` timestamp NOT NULL,
`definition_id` varchar(64) NOT NULL,
CONSTRAINT `custom_widget_secret_definition_id_source_id_kind_pk` PRIMARY KEY(`definition_id`,`source_id`,`kind`)
);--> statement-breakpoint
ALTER TABLE `custom_widget_definition` ADD CONSTRAINT `custom_widget_definition_creator_id_user_id_fk` FOREIGN KEY (`creator_id`) REFERENCES `user`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `custom_widget_secret` ADD CONSTRAINT `cw_secret_definition_id_cw_definition_id_fk` FOREIGN KEY (`definition_id`) REFERENCES `custom_widget_definition`(`id`) ON DELETE cascade ON UPDATE no action;
File diff suppressed because it is too large. Load diff
@@ -309,6 +309,13 @@
"when": 1783852800000,
"tag": "0043_add_right_click_preference",
"breakpoints": true
},
{
"idx": 44,
"version": "5",
"when": 1784305537309,
"tag": "0044_custom_widget_v2_reset",
"breakpoints": true
}
]
}
@@ -0,0 +1,26 @@
DROP TABLE "custom_widget_secret";--> statement-breakpoint
DROP TABLE "custom_widget_definition";--> statement-breakpoint
CREATE TABLE "custom_widget_definition" (
"id" varchar(64) PRIMARY KEY NOT NULL,
"name" varchar(256) NOT NULL,
"description" text,
"icon_url" text,
"sources" text NOT NULL,
"requests" text NOT NULL,
"options" text NOT NULL,
"template" text NOT NULL,
"enabled" boolean DEFAULT true NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
"creator_id" varchar(64)
);--> statement-breakpoint
CREATE TABLE "custom_widget_secret" (
"source_id" varchar(64) NOT NULL,
"kind" varchar(64) NOT NULL,
"encrypted_value" text NOT NULL,
"updated_at" timestamp NOT NULL,
"definition_id" varchar(64) NOT NULL,
CONSTRAINT "custom_widget_secret_definition_id_source_id_kind_pk" PRIMARY KEY("definition_id","source_id","kind")
);--> statement-breakpoint
ALTER TABLE "custom_widget_definition" ADD CONSTRAINT "custom_widget_definition_creator_id_user_id_fk" FOREIGN KEY ("creator_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "custom_widget_secret" ADD CONSTRAINT "custom_widget_secret_definition_id_custom_widget_definition_id_fk" FOREIGN KEY ("definition_id") REFERENCES "public"."custom_widget_definition"("id") ON DELETE cascade ON UPDATE no action;
File diff suppressed because it is too large. Load diff
@@ -71,6 +71,13 @@
"when": 1783786677702,
"tag": "0009_add_right_click_preference",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1784305412862,
"tag": "0010_custom_widget_v2_reset",
"breakpoints": true
}
]
}
+18 -115
View File
@@ -1,7 +1,7 @@
import SuperJSON from "superjson";
import { createId, objectKeys } from "@homarr/common";
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import {
createDocumentationLink,
credentialsAdminGroup,
@@ -27,6 +27,7 @@ import {
import {
apps,
boards,
customWidgetDefinitions,
groupMembers,
groupPermissions,
groups,
@@ -39,102 +40,11 @@ import {
searchEngines,
sections,
users,
customWidgetDefinitions,
} from "../schema";
import type { Integration } from "../schema";
const isTruthyEnv = (value: string | undefined) => ["1", "yes", "t", "true"].includes((value ?? "").toLowerCase());
const CUSTOM_WIDGET_SEEDS: Array<{ id: string; data: Record<string, unknown> }> = [
{
id: "seed-dog-facts",
data: {
$schema: "homarr-custom-widget-v2",
name: "Random Dog Fact",
description: "Displays a random fun fact about dogs",
url: "https://dogapi.dog/api/v2/facts",
authType: "none",
method: "GET",
displayType: "singleValue",
displayConfig: {
type: "singleValue",
jsonPath: "$.data[0].attributes.body",
label: "Dog Fact",
unit: "",
valueSize: "sm",
labelPosition: "above",
},
},
},
{
id: "seed-currency-exchange",
data: {
$schema: "homarr-custom-widget-v2",
name: "Currency Exchange (JPY)",
description: "Converts 50 Japanese Yen to EUR and USD using European Central Bank rates",
url: "https://api.frankfurter.dev/v1/latest?from=JPY&to=EUR,USD&amount=50",
authType: "none",
method: "GET",
displayType: "keyValue",
displayConfig: {
type: "keyValue",
mappings: [
{ label: "50 JPY → EUR", jsonPath: "$.rates.EUR", unit: "€" },
{ label: "50 JPY → USD", jsonPath: "$.rates.USD", unit: "$" },
],
layout: "list",
columns: 2,
},
},
},
{
id: "seed-jellyfin",
data: {
$schema: "homarr-custom-widget-v2",
name: "Jellyfin library",
description: "Counts the number of movies, series, episodes and songs in the library",
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/jellyfin.svg",
url: "https://jellyfin.homelab.com/Items/Counts",
authType: "apiKeyHeader",
headerName: "X-Emby-Token",
method: "GET",
requestBody: null,
displayType: "countGrid",
displayConfig: {
type: "countGrid",
items: [
{ label: "Movies", jsonPath: "$.MovieCount", unit: "" },
{ label: "Series", jsonPath: "$.SeriesCount", unit: "" },
{ label: "Episodes", jsonPath: "$.EpisodeCount", unit: "" },
{ label: "Songs", jsonPath: "$.SongCount", unit: "" },
],
columns: 4,
valueSize: "lg",
},
},
},
{
id: "seed-pokedex",
data: {
$schema: "homarr-custom-widget-v2",
name: "Pokédex",
description: "Browseable Pokémon list",
iconUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png",
url: "https://pokeapi.co/api/v2/pokemon?limit=75",
authType: "none",
headerName: null,
method: "GET",
requestBody: null,
displayType: "customJsx",
displayConfig: {
type: "customJsx",
template:
'<Stack gap="md" p="xs">\n <Card\n withBorder\n radius="xl"\n p="md"\n shadow="md"\n style={{\n background: "linear-gradient(135deg, rgba(250,82,82,0.22), rgba(253,126,20,0.10), rgba(255,255,255,0.03))",\n border: "1px solid rgba(250,82,82,0.35)",\n overflow: "hidden"\n }}\n >\n <Group justify="space-between" wrap="nowrap">\n <Stack gap={2}>\n <Title order={3}>Pokédex</Title>\n </Stack>\n </Group>\n </Card>\n\n <PaginatedList pageSize={12}>\n <Grid gutter="sm">\n {data.results.map((pokemon, i) =>\n <Grid.Col span={1.5}>\n <Anchor href={pokemon.url} target="_blank" underline="never">\n <Card\n withBorder\n radius="xl"\n p="xs"\n shadow="md"\n style={{\n cursor: "pointer",\n position: "relative",\n overflow: "hidden",\n minHeight: 190,\n background: "linear-gradient(160deg, rgba(255,255,255,0.12), rgba(250,82,82,0.10), rgba(0,0,0,0.04))",\n border: "1px solid rgba(250,82,82,0.28)",\n transition: "transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease, background 180ms ease"\n }}\n >\n <Stack gap="sm" align="center">\n <Group justify="space-between" wrap="nowrap" style={{ width: "100%" }}>\n <Badge size="sm" color="red" variant="filled">\n #{String(i + 1).padStart(3, "0")}\n </Badge>\n <Text fw={800} tt="capitalize" ta="right" truncate style={{ maxWidth: 120 }}>\n {pokemon.name}\n </Text>\n </Group>\n\n <Paper\n radius="xl"\n p="xs"\n withBorder\n style={{\n background: "radial-gradient(circle, rgba(255,255,255,0.95), rgba(250,82,82,0.16))",\n border: "1px solid rgba(255,255,255,0.45)",\n boxShadow: "inset 0 0 20px rgba(255,255,255,0.25)"\n }}\n >\n <Avatar\n src={"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/" + String(i + 1) + ".png"}\n alt={pokemon.name}\n size={92}\n radius="xl"\n style={{\n transition: "transform 180ms ease",\n filter: "drop-shadow(0 8px 10px rgba(0,0,0,0.25))"\n }}\n />\n </Paper>\n </Stack>\n </Card>\n </Anchor>\n </Grid.Col>\n )}\n </Grid>\n </PaginatedList>\n</Stack>',
},
},
},
];
export const seedDataAsync = async (db: Database) => {
if (isTruthyEnv(process.env.UNSAFE_ENABLE_MOCK_INTEGRATION)) {
console.warn(
@@ -646,40 +556,33 @@ const seedDemoUserAsync = async (db: Database) => {
};
const seedDefaultCustomWidgetsAsync = async (db: Database) => {
const seedIds = CUSTOM_WIDGET_SEEDS.map((s) => s.id);
const seedIds = BUNDLED_CUSTOM_WIDGETS.map(({ id }) => id);
const existing = await db.query.customWidgetDefinitions.findMany({
columns: { id: true },
where: inArray(customWidgetDefinitions.id, seedIds),
});
const existingIds = new Set(existing.map((row) => row.id));
const seedValues = CUSTOM_WIDGET_SEEDS.filter((seed) => !existingIds.has(seed.id)).map((seed) => {
const parsed = customWidgetImportSchema.parse(seed.data);
const existingIds = new Set(existing.map(({ id }) => id));
const values = BUNDLED_CUSTOM_WIDGETS.filter(({ id }) => !existingIds.has(id)).map(({ id, widget }) => {
const definition = customWidgetDefinitionSchema.parse(widget);
return {
id: seed.id,
name: parsed.name,
description: parsed.description ?? null,
iconUrl: parsed.iconUrl ?? null,
url: parsed.url,
authType: parsed.authType,
headerName: parsed.headerName ?? null,
method: parsed.method,
requestBody: parsed.requestBody ?? null,
displayType: parsed.displayType,
displayConfig: SuperJSON.stringify(parsed.displayConfig),
id,
name: definition.name,
description: definition.description ?? null,
iconUrl: definition.iconUrl ?? null,
sources: SuperJSON.stringify(definition.sources),
requests: SuperJSON.stringify(definition.requests),
options: SuperJSON.stringify(definition.options),
template: definition.template,
enabled: false,
creatorId: null,
};
});
if (seedValues.length === 0) {
console.log("Skipping seeding of default custom widgets as they already exist");
if (values.length === 0) {
console.log("Skipping seeding of bundled custom widgets because they already exist");
return;
}
await db.insert(customWidgetDefinitions).values(seedValues);
console.log(`Created ${seedValues.length} default custom widgets through seeding process`);
await db.insert(customWidgetDefinitions).values(values);
console.log(`Created ${values.length} bundled custom widgets through seeding process`);
};
const seedBoardWidgetsAsync = async (db: Database) => {
@@ -0,0 +1,28 @@
PRAGMA foreign_keys=OFF;--> statement-breakpoint
DROP TABLE `custom_widget_secret`;--> statement-breakpoint
DROP TABLE `custom_widget_definition`;--> statement-breakpoint
CREATE TABLE `custom_widget_definition` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`description` text,
`icon_url` text,
`sources` text NOT NULL,
`requests` text NOT NULL,
`options` text NOT NULL,
`template` text NOT NULL,
`enabled` integer DEFAULT true NOT NULL,
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
`updated_at` integer DEFAULT (unixepoch()) NOT NULL,
`creator_id` text,
FOREIGN KEY (`creator_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE set null
);--> statement-breakpoint
CREATE TABLE `custom_widget_secret` (
`source_id` text NOT NULL,
`kind` text NOT NULL,
`encrypted_value` text NOT NULL,
`updated_at` integer NOT NULL,
`definition_id` text NOT NULL,
PRIMARY KEY(`definition_id`, `source_id`, `kind`),
FOREIGN KEY (`definition_id`) REFERENCES `custom_widget_definition`(`id`) ON UPDATE no action ON DELETE cascade
);--> statement-breakpoint
PRAGMA foreign_keys=ON;
File diff suppressed because it is too large. Load diff
@@ -295,6 +295,13 @@
"when": 1783786658943,
"tag": "0041_add_right_click_preference",
"breakpoints": true
},
{
"idx": 42,
"version": "6",
"when": 1784305283910,
"tag": "0042_custom_widget_v2_reset",
"breakpoints": true
}
]
}
+8 -15
View File
@@ -39,12 +39,7 @@ import type {
SupportedAuthProvider,
WidgetKind,
} from "@homarr/definitions";
import type {
CustomWidgetAuthType,
CustomWidgetDisplayType,
CustomWidgetMethod,
CustomWidgetSecretKind,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
const customBlob = customType<{ data: Buffer }>({
dataType() {
@@ -510,13 +505,10 @@ export const customWidgetDefinitions = mysqlTable("custom_widget_definition", {
name: varchar({ length: 256 }).notNull(),
description: text(),
iconUrl: text(),
url: text().notNull(),
authType: varchar({ length: 32 }).$type<CustomWidgetAuthType>().notNull().default("none"),
headerName: varchar({ length: 256 }),
method: varchar({ length: 16 }).$type<CustomWidgetMethod>().notNull().default("GET"),
requestBody: text(),
displayType: varchar({ length: 32 }).$type<CustomWidgetDisplayType>().notNull().default("singleValue"),
displayConfig: text().default(emptySuperJSON).notNull(),
sources: text().notNull(),
requests: text().notNull(),
options: text().notNull(),
template: text().notNull(),
enabled: boolean().notNull().default(true),
createdAt: timestamp({ mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp({ mode: "date" }).notNull().defaultNow(),
@@ -526,8 +518,9 @@ export const customWidgetDefinitions = mysqlTable("custom_widget_definition", {
export const customWidgetSecrets = mysqlTable(
"custom_widget_secret",
{
sourceId: varchar({ length: 64 }).notNull(),
kind: varchar({ length: 64 }).$type<CustomWidgetSecretKind>().notNull(),
value: text().$type<`${string}.${string}`>().notNull(),
encryptedValue: text("encrypted_value").$type<`${string}.${string}`>().notNull(),
updatedAt: timestamp()
.$onUpdateFn(() => new Date())
.notNull(),
@@ -537,7 +530,7 @@ export const customWidgetSecrets = mysqlTable(
},
(table) => ({
compoundKey: primaryKey({
columns: [table.definitionId, table.kind],
columns: [table.definitionId, table.sourceId, table.kind],
}),
}),
);
+8 -15
View File
@@ -38,12 +38,7 @@ import type {
SupportedAuthProvider,
WidgetKind,
} from "@homarr/definitions";
import type {
CustomWidgetAuthType,
CustomWidgetDisplayType,
CustomWidgetMethod,
CustomWidgetSecretKind,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
const customBlob = customType<{ data: Buffer }>({
dataType() {
@@ -509,13 +504,10 @@ export const customWidgetDefinitions = pgTable("custom_widget_definition", {
name: varchar({ length: 256 }).notNull(),
description: text(),
iconUrl: text(),
url: text().notNull(),
authType: varchar({ length: 32 }).$type<CustomWidgetAuthType>().notNull().default("none"),
headerName: varchar({ length: 256 }),
method: varchar({ length: 16 }).$type<CustomWidgetMethod>().notNull().default("GET"),
requestBody: text(),
displayType: varchar({ length: 32 }).$type<CustomWidgetDisplayType>().notNull().default("singleValue"),
displayConfig: text().default(emptySuperJSON).notNull(),
sources: text().notNull(),
requests: text().notNull(),
options: text().notNull(),
template: text().notNull(),
enabled: boolean().notNull().default(true),
createdAt: timestamp({ mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp({ mode: "date" }).notNull().defaultNow(),
@@ -525,8 +517,9 @@ export const customWidgetDefinitions = pgTable("custom_widget_definition", {
export const customWidgetSecrets = pgTable(
"custom_widget_secret",
{
sourceId: varchar({ length: 64 }).notNull(),
kind: varchar({ length: 64 }).$type<CustomWidgetSecretKind>().notNull(),
value: text().$type<`${string}.${string}`>().notNull(),
encryptedValue: text("encrypted_value").$type<`${string}.${string}`>().notNull(),
updatedAt: timestamp()
.$onUpdateFn(() => new Date())
.notNull(),
@@ -536,7 +529,7 @@ export const customWidgetSecrets = pgTable(
},
(table) => ({
compoundKey: primaryKey({
columns: [table.definitionId, table.kind],
columns: [table.definitionId, table.sourceId, table.kind],
}),
}),
);
+8 -15
View File
@@ -27,12 +27,7 @@ import type {
SupportedAuthProvider,
WidgetKind,
} from "@homarr/definitions";
import type {
CustomWidgetAuthType,
CustomWidgetDisplayType,
CustomWidgetMethod,
CustomWidgetSecretKind,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
export * from "@homarr/core/infrastructure/certificates/hostnames/db/sqlite";
@@ -495,13 +490,10 @@ export const customWidgetDefinitions = sqliteTable("custom_widget_definition", {
name: text().notNull(),
description: text(),
iconUrl: text(),
url: text().notNull(),
authType: text().$type<CustomWidgetAuthType>().notNull().default("none"),
headerName: text(),
method: text().$type<CustomWidgetMethod>().notNull().default("GET"),
requestBody: text(),
displayType: text().$type<CustomWidgetDisplayType>().notNull().default("singleValue"),
displayConfig: text().default(emptySuperJSON).notNull(),
sources: text().notNull(),
requests: text().notNull(),
options: text().notNull(),
template: text().notNull(),
enabled: int({ mode: "boolean" }).notNull().default(true),
createdAt: int({ mode: "timestamp" })
.notNull()
@@ -515,8 +507,9 @@ export const customWidgetDefinitions = sqliteTable("custom_widget_definition", {
export const customWidgetSecrets = sqliteTable(
"custom_widget_secret",
{
sourceId: text().notNull(),
kind: text().$type<CustomWidgetSecretKind>().notNull(),
value: text().$type<`${string}.${string}`>().notNull(),
encryptedValue: text("encrypted_value").$type<`${string}.${string}`>().notNull(),
updatedAt: int({ mode: "timestamp" })
.$onUpdateFn(() => new Date())
.notNull(),
@@ -526,7 +519,7 @@ export const customWidgetSecrets = sqliteTable(
},
(table) => ({
compoundKey: primaryKey({
columns: [table.definitionId, table.kind],
columns: [table.definitionId, table.sourceId, table.kind],
}),
}),
);
@@ -1,18 +0,0 @@
{
"$schema": "homarr-custom-widget-v2",
"name": "Currency Exchange (JPY)",
"description": "Converts 50 Japanese Yen to EUR and USD using European Central Bank rates",
"url": "https://api.frankfurter.dev/v1/latest?from=JPY&to=EUR,USD&amount=50",
"authType": "none",
"method": "GET",
"displayType": "keyValue",
"displayConfig": {
"type": "keyValue",
"mappings": [
{ "label": "50 JPY → EUR", "jsonPath": "$.rates.EUR", "unit": "€" },
{ "label": "50 JPY → USD", "jsonPath": "$.rates.USD", "unit": "$" }
],
"layout": "list",
"columns": 2
}
}
@@ -1,17 +0,0 @@
{
"$schema": "homarr-custom-widget-v2",
"name": "Random Dog Fact",
"description": "Displays a random fun fact about dogs",
"url": "https://dogapi.dog/api/v2/facts",
"authType": "none",
"method": "GET",
"displayType": "singleValue",
"displayConfig": {
"type": "singleValue",
"jsonPath": "$.data[0].attributes.body",
"label": "Dog Fact",
"unit": "",
"valueSize": "sm",
"labelPosition": "above"
}
}
@@ -1,23 +0,0 @@
{
"$schema": "homarr-custom-widget-v2",
"name": "Jellyfin library",
"description": "Counts the number of movies, series, episodes and songs in the library",
"iconUrl": "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/jellyfin.svg",
"url": "https://jellyfin.homelab.com/Items/Counts",
"authType": "apiKeyHeader",
"headerName": "X-Emby-Token",
"method": "GET",
"requestBody": null,
"displayType": "countGrid",
"displayConfig": {
"type": "countGrid",
"items": [
{ "label": "Movies", "jsonPath": "$.MovieCount", "unit": "" },
{ "label": "Series", "jsonPath": "$.SeriesCount", "unit": "" },
{ "label": "Episodes", "jsonPath": "$.EpisodeCount", "unit": "" },
{ "label": "Songs", "jsonPath": "$.SongCount", "unit": "" }
],
"columns": 4,
"valueSize": "lg"
}
}
@@ -1,14 +0,0 @@
{
"$schema": "homarr-custom-widget-v2",
"name": "Pokédex — Charizard",
"description": "Detailed Pokémon card with types, stats, tabs, pagination, and collapsible info",
"iconUrl": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png",
"url": "https://pokeapi.co/api/v2/pokemon/charizard",
"authType": "none",
"method": "GET",
"displayType": "customJsx",
"displayConfig": {
"type": "customJsx",
"template": "<Stack gap=\"sm\" p=\"xs\">\n <Group wrap=\"nowrap\">\n <Avatar\n src={data.sprites.front_default}\n size={80}\n radius=\"sm\"\n />\n <Stack gap={4} style={{flex: 1}}>\n <Title order={3} tt=\"capitalize\">{data.name}</Title>\n <Text size=\"xs\" c=\"dimmed\">#{String(data.id).padStart(3, \"0\")} · {data.height / 10} m · {data.weight / 10} kg</Text>\n <Group gap=\"xs\">\n {data.types.map(t =>\n <TypeBadge type={t.type.name} />\n )}\n </Group>\n </Stack>\n </Group>\n <TabsContainer defaultTab=\"stats\">\n <TabPanel value=\"stats\" label=\"Stats\">\n <Stack gap=\"xs\" pt=\"xs\">\n {data.stats.map(s =>\n <StatBar label={s.stat.name} value={s.base_stat} max={255} color={s.base_stat > 100 ? \"green\" : s.base_stat > 60 ? \"yellow\" : \"red\"} />\n )}\n </Stack>\n </TabPanel>\n <TabPanel value=\"abilities\" label=\"Abilities\">\n <Collapsible title=\"Abilities\" defaultOpen={true}>\n <Group gap=\"xs\" pt=\"xs\">\n {data.abilities.map(a =>\n <Badge variant={a.is_hidden ? \"outline\" : \"filled\"} color={a.is_hidden ? \"gray\" : \"blue\"} tt=\"capitalize\">\n {a.ability.name}{a.is_hidden ? \" (hidden)\" : \"\"}\n </Badge>\n )}\n </Group>\n </Collapsible>\n </TabPanel>\n <TabPanel value=\"moves\" label=\"Moves\">\n <PaginatedList pageSize={12}>\n {data.moves.map(m =>\n <Badge size=\"xs\" variant=\"light\" tt=\"capitalize\" mb={4}>{m.move.name}</Badge>\n )}\n </PaginatedList>\n </TabPanel>\n </TabsContainer>\n</Stack>"
}
}
@@ -0,0 +1,65 @@
import { parse } from "superjson";
import { expect } from "vitest";
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import type { Database } from "..";
import { eq } from "..";
import { seedDataAsync } from "../migrations/seed";
import { customWidgetDefinitions, customWidgetSecrets } from "../schema";
const expectedSeedIds = BUNDLED_CUSTOM_WIDGETS.map(({ id }) => id).toSorted();
const reconstructWidget = (definition: typeof customWidgetDefinitions.$inferSelect) =>
customWidgetDefinitionSchema.parse({
$schema: "homarr-custom-widget-v2",
name: definition.name,
...(definition.description === null ? {} : { description: definition.description }),
...(definition.iconUrl === null ? {} : { iconUrl: definition.iconUrl }),
sources: parse(definition.sources),
requests: parse(definition.requests),
options: parse(definition.options),
template: definition.template,
});
export const expectBundledCustomWidgetsSeeded = async (db: Database) => {
const definitions = await db.query.customWidgetDefinitions.findMany({
where: (table, { like }) => like(table.id, "seed-%"),
});
expect(definitions.map(({ id }) => id).toSorted()).toEqual(expectedSeedIds);
expect(definitions.every(({ enabled }) => !enabled)).toBe(true);
expect(definitions.every(({ creatorId }) => creatorId === null)).toBe(true);
expect(await db.$count(customWidgetSecrets)).toBe(0);
for (const definition of definitions) {
const expected = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === definition.id);
expect(expected).toBeDefined();
expect(reconstructWidget(definition)).toEqual(customWidgetDefinitionSchema.parse(expected?.widget));
}
await db
.update(customWidgetDefinitions)
.set({ name: "User-edited dog facts", enabled: true })
.where(eq(customWidgetDefinitions.id, "seed-dog-facts"));
await db.delete(customWidgetDefinitions).where(eq(customWidgetDefinitions.id, "seed-currency-exchange"));
await seedDataAsync(db);
const reseededDefinitions = await db.query.customWidgetDefinitions.findMany({
where: (table, { like }) => like(table.id, "seed-%"),
});
const editedDefinition = reseededDefinitions.find(({ id }) => id === "seed-dog-facts");
const reseededCurrency = reseededDefinitions.find(({ id }) => id === "seed-currency-exchange");
expect(reseededDefinitions.map(({ id }) => id).toSorted()).toEqual(expectedSeedIds);
expect(editedDefinition).toMatchObject({ name: "User-edited dog facts", enabled: true, creatorId: null });
expect(reseededDefinitions.filter(({ id }) => id !== "seed-dog-facts").every(({ enabled }) => !enabled)).toBe(true);
if (!reseededCurrency) throw new Error("Currency Exchange seed was not restored");
expect(reconstructWidget(reseededCurrency)).toEqual(
customWidgetDefinitionSchema.parse(
BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-currency-exchange")?.widget,
),
);
expect(await db.$count(customWidgetSecrets)).toBe(0);
};
+5
View File
@@ -8,6 +8,9 @@ import { describe, test } from "vitest";
import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
import * as mysqlSchema from "../schema/mysql";
import type { Database } from "..";
import { seedDataAsync } from "../migrations/seed";
import { expectBundledCustomWidgetsSeeded } from "./custom-widget-seed-assertions";
describe("Mysql Migration", () => {
test("should add all tables and keys specified in migration files", async () => {
@@ -31,9 +34,11 @@ describe("Mysql Migration", () => {
await migrate(database, {
migrationsFolder: path.join(__dirname, "..", "migrations", "mysql"),
});
await seedDataAsync(database as unknown as Database);
// Check if users table exists
await database.query.users.findMany();
await expectBundledCustomWidgetsSeeded(database as unknown as Database);
connection.end();
await mysqlContainer.stop();
@@ -8,6 +8,9 @@ import { describe, test } from "vitest";
import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
import * as pgSchema from "../schema/postgresql";
import type { Database } from "..";
import { seedDataAsync } from "../migrations/seed";
import { expectBundledCustomWidgetsSeeded } from "./custom-widget-seed-assertions";
describe("PostgreSql Migration", () => {
test("should add all tables and keys specified in migration files", async () => {
@@ -36,9 +39,11 @@ describe("PostgreSql Migration", () => {
await migrate(database, {
migrationsFolder: path.join(__dirname, "..", "migrations", "postgresql"),
});
await seedDataAsync(database as unknown as Database);
// Check if users table exists
await database.query.users.findMany();
await expectBundledCustomWidgetsSeeded(database as unknown as Database);
// Close the pool to release resources
await pool.end();
+24
View File
@@ -0,0 +1,24 @@
import path from "path";
import BetterSqlite3 from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import { test } from "vitest";
import { DB_CASING } from "@homarr/core/infrastructure/db/constants";
import type { Database } from "..";
import { seedDataAsync } from "../migrations/seed";
import * as sqliteSchema from "../schema/sqlite";
import { expectBundledCustomWidgetsSeeded } from "./custom-widget-seed-assertions";
test("SQLite migrations seed the five disabled bundled custom widgets", async () => {
const connection = new BetterSqlite3(":memory:");
const database = drizzle(connection, { schema: sqliteSchema, casing: DB_CASING });
migrate(database, { migrationsFolder: path.join(__dirname, "..", "migrations", "sqlite") });
await seedDataAsync(database as unknown as Database);
await expectBundledCustomWidgetsSeeded(database as unknown as Database);
connection.close();
});