feat: polish custom widgets and workshop

This commit is contained in:
Thomas Camlong committed 2026-07-22 19:33:09 +02:00
1 parent e94b4d4bc9
commit 0066c8bc28
98 files changed
+9097 -1624

No files matched your search

@@ -636,6 +636,8 @@ const HOMARR_COMPONENT_PROPS: Readonly<Record<string, Readonly<Record<string, Ho
loadingLabel: optionalProp("string"),
errorMessage: optionalProp("string"),
fallback: optionalProp("ReactNode"),
triggerContent: optionalProp("ReactNode", undefined, "Custom accessible trigger shown before a manual query runs."),
triggerAriaLabel: optionalProp("string", undefined, "Accessible label for a custom manual-query trigger."),
path: optionalProp("string"),
as: optionalProp("'json' | 'text'", ["json", "text"]),
trigger: optionalProp("'auto' | 'manual'", ["auto", "manual"]),
@@ -103,7 +103,7 @@ export const BUNDLED_CUSTOM_WIDGETS: readonly BundledCustomWidget[] = [
<Group gap="xs"><Badge color={options.accent} variant="light">{data.pokemon?.count?.toLocaleString() ?? "—"} species</Badge><RefreshButton /></Group>
</Group>
<TextInput bind="search" label="Filter loaded Pokémon" placeholder="Search by name…" />
{status.pokemon?.loading ? <SimpleGrid cols={{ base: 1, xs: 2 }}>{[1, 2, 3, 4].map(item => <Skeleton key={item} height={116} radius="md" />)}</SimpleGrid> : status.pokemon?.error ? <Alert color="red" title="The Pokédex could not be loaded">{status.pokemon.error}</Alert> : (data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).length === 0 ? <Alert color="gray" title="No Pokémon found">Try another name or increase the result limit in widget options.</Alert> : <ScrollArea h={300} type="auto"><SimpleGrid cols={{ base: 1, xs: 2 }} spacing="sm">{(data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).map((pokemon, index) => <Card key={pokemon.name} withBorder radius="md" padding="sm"><Stack gap="sm"><Group justify="space-between"><Group gap="xs"><Badge color={options.accent} variant="outline">#{options.offset + index + 1}</Badge><Text fw={700} tt="capitalize">{pokemon.name}</Text></Group><Text size="xs" c="dimmed">Details</Text></Group><SubFetch requestId="detail" params={{ name: pokemon.name }} trigger="manual" loadingLabel="Loading Pokémon…">{(detail) => <Stack gap="sm"><Group align="flex-start" wrap="nowrap"><Image src={detail.sprites?.other?.["official-artwork"]?.front_default ?? detail.sprites?.front_default} alt={detail.name} w={92} h={92} fit="contain" fallbackSrc="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png" /><Stack gap="xs"><Group gap={6}>{(detail.types ?? []).map(type => <Badge key={type.type?.name} variant="light" tt="capitalize">{type.type?.name}</Badge>)}</Group><Text size="xs" c="dimmed">Height {detail.height / 10} m · Weight {detail.weight / 10} kg</Text><Text size="xs"><Text span fw={600}>Abilities: </Text>{(detail.abilities ?? []).map(ability => ability.ability?.name?.replace("-", " ")).join(", ")}</Text></Stack></Group><Divider /><Stack gap={6}>{(detail.stats ?? []).map(stat => <Stack key={stat.stat?.name} gap={3}><Group justify="space-between"><Text size="xs" tt="capitalize">{stat.stat?.name?.replace("-", " ")}</Text><Text size="xs" fw={700}>{stat.base_stat}</Text></Group><Progress value={Math.min(100, stat.base_stat / 2)} color={options.accent} size="sm" /></Stack>)}</Stack></Stack>}</SubFetch></Stack></Card>)}</SimpleGrid></ScrollArea>}
{status.pokemon?.loading ? <Stack gap="xs">{[1, 2, 3, 4].map(item => <Skeleton key={item} height={82} radius="md" />)}</Stack> : status.pokemon?.error ? <Alert color="red" title="The Pokédex could not be loaded">{status.pokemon.error}</Alert> : (data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).length === 0 ? <Alert color="gray" title="No Pokémon found">Try another name or increase the result limit in widget options.</Alert> : <ScrollArea h={390} type="auto"><PaginatedList pageSize={8}>{(data.pokemon?.results ?? []).filter(pokemon => pokemon.name.toLowerCase().includes(String(inputs.search ?? "").toLowerCase())).map(pokemon => <SubFetch key={pokemon.name} requestId="detail" params={{ name: pokemon.name }} trigger="manual" triggerAriaLabel={"Open details for " + pokemon.name} loadingLabel="Loading Pokémon…" fallback={<Card withBorder radius="md" p="xs" mb="xs"><Skeleton height={64} radius="sm" /></Card>} triggerContent={<Card withBorder radius="md" p="xs" mb="xs"><Group wrap="nowrap" justify="space-between"><Group wrap="nowrap" gap="sm"><Image src={"https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/pokemon/" + pokemon.url.split("/").slice(-2, -1)[0] + ".png"} alt={pokemon.name} w={64} h={64} fit="contain" radius="sm" fallbackSrc="https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/items/poke-ball.png" /><Stack gap={0}><Text fw={700} tt="capitalize">{pokemon.name}</Text><Text size="xs" c="dimmed">#{String(pokemon.url.split("/").slice(-2, -1)[0]).padStart(3, "0")}</Text></Stack></Group><Badge color={options.accent} variant="light">Details</Badge></Group></Card>}>{(detail) => <Card withBorder radius="md" p="sm" mb="xs"><Stack gap="sm"><Group align="flex-start" wrap="nowrap"><Image src={"https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/pokemon/other/official-artwork/" + detail.id + ".png"} alt={detail.name} w={80} h={80} fit="contain" radius="md" fallbackSrc="https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/items/poke-ball.png" /><Stack gap="xs" style={{ flex: 1 }}><Group justify="space-between"><Text fw={750} size="lg" tt="capitalize">{detail.name}</Text><Group gap={6}>{(detail.types ?? []).map(type => <Badge key={type.type?.name} variant="light" tt="capitalize">{type.type?.name}</Badge>)}</Group></Group><Text size="xs" c="dimmed">Height {detail.height / 10} m · Weight {detail.weight / 10} kg</Text><Text size="xs"><Text span fw={600}>Abilities: </Text>{(detail.abilities ?? []).map(ability => ability.ability?.name?.replace("-", " ")).join(", ")}</Text></Stack></Group><Divider /><SimpleGrid cols={{ base: 1, xs: 2 }} spacing="xs">{(detail.stats ?? []).map(stat => <Stack key={stat.stat?.name} gap={3}><Group justify="space-between"><Text size="xs" tt="capitalize">{stat.stat?.name?.replace("-", " ")}</Text><Text size="xs" fw={700}>{stat.base_stat}</Text></Group><Progress value={Math.min(100, stat.base_stat / 2)} color={options.accent} size="sm" /></Stack>)}</SimpleGrid></Stack></Card>}</SubFetch>)}</PaginatedList></ScrollArea>}
</Stack>`,
},
},
@@ -1 +1 @@
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previLine truncated
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previLine truncated
@@ -73,10 +73,16 @@ export function parseRequestCapabilities(value: unknown): CustomJsxRequestCapabi
}
class RendererErrorBoundary extends Component<
{ children: ReactNode; onError(error: Error): void },
{ error: Error | null }
{ children: ReactNode; resetKey: string; onError(error: Error): void },
{ error: Error | null; resetKey: string }
> {
public state = { error: null } as { error: Error | null };
public state = { error: null, resetKey: "" } as { error: Error | null; resetKey: string };
public static getDerivedStateFromProps(
props: Readonly<{ resetKey: string }>,
state: Readonly<{ error: Error | null; resetKey: string }>,
) {
return props.resetKey === state.resetKey ? null : { error: null, resetKey: props.resetKey };
}
public static getDerivedStateFromError(error: Error) {
return { error };
}
@@ -195,7 +201,7 @@ function CustomJsxRendererSession({
registerInput={registerInput}
setInputValue={setInputValue}
>
<RendererErrorBoundary key={boundaryKey} onError={handleError}>
<RendererErrorBoundary resetKey={boundaryKey} onError={handleError}>
{rendered.node}
</RendererErrorBoundary>
</CustomJsxInputsProvider>
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
import { Button } from "@mantine/core";
import { ActionIcon } from "@mantine/core";
import { IconRefresh } from "@tabler/icons-react";
import { useCustomWidgetRuntime } from "./context";
@@ -13,7 +13,7 @@ export interface RefreshButtonProps {
size?: string;
}
export function RefreshButton({ label, color = "blue", variant = "light", size = "sm" }: RefreshButtonProps) {
export function RefreshButton({ label, color = "gray", variant = "subtle", size = "sm" }: RefreshButtonProps) {
const runtime = useCustomWidgetRuntime();
const [loading, setLoading] = useState(false);
const refresh = async () => {
@@ -30,16 +30,16 @@ export function RefreshButton({ label, color = "blue", variant = "light", size =
}
};
return (
<Button
<ActionIcon
aria-label={label ?? runtime.messages.refresh}
color={color}
variant={variant as never}
size={size as never}
leftSection={<IconRefresh size={16} />}
onClick={() => void refresh()}
loading={loading}
disabled={(!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
>
{label ?? runtime.messages.refresh}
</Button>
<IconRefresh size={16} />
</ActionIcon>
);
}
@@ -2,7 +2,7 @@
import type { ReactNode } from "react";
import { useEffect, useMemo, useState } from "react";
import { Alert, Button, Code, Skeleton, Text } from "@mantine/core";
import { Alert, Box, Button, Code, Skeleton, Text } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useQuery } from "@tanstack/react-query";
@@ -27,6 +27,8 @@ export interface SubFetchProps {
loadingLabel?: string;
errorMessage?: string;
fallback?: ReactNode;
triggerContent?: ReactNode;
triggerAriaLabel?: string;
path?: string;
as?: "json" | "text";
trigger?: "auto" | "manual";
@@ -55,7 +57,9 @@ export function SubFetch(props: SubFetchProps) {
refetchInterval: refreshMs,
});
useEffect(() => {
if (!props.requestId || !setQueryState) return;
// Manual queries are local to their SubFetch instance. Publishing them by request ID makes
// repeated cards compete for the same data slot and can remount the active query mid-request.
if (!props.requestId || !setQueryState || props.trigger === "manual") return;
if (!enabled) {
setQueryState(props.requestId, null);
return;
@@ -71,13 +75,48 @@ export function SubFetch(props: SubFetchProps) {
error: result?.error ?? (query.error ? messages.requestFailed : undefined),
},
});
}, [enabled, messages.requestFailed, props.requestId, query.data, query.error, query.isFetching, setQueryState]);
}, [
enabled,
messages.requestFailed,
props.requestId,
props.trigger,
query.data,
query.error,
query.isFetching,
setQueryState,
]);
if (!props.requestId) return <RequestIdRequiredAlert />;
if (queriesDisabled) return null;
if (!itemId && !previewSessionId) return props.fallback ?? <Text c="dimmed">{messages.unsavedPreview}</Text>;
if (queriesDisabled) return props.trigger === "manual" ? (props.triggerContent ?? null) : null;
if (!itemId && !previewSessionId)
return props.trigger === "manual" && props.triggerContent
? props.triggerContent
: (props.fallback ?? <Text c="dimmed">{messages.unsavedPreview}</Text>);
if (!params) return <RequestAlert message={messages.invalidParams} />;
if (props.trigger === "manual" && !manualRun) {
if (props.triggerContent) {
return (
<Box
component="button"
type="button"
aria-label={props.triggerAriaLabel ?? messages.loadRequest}
onClick={() => setManualRun(true)}
style={{
appearance: "none",
background: "transparent",
border: 0,
color: "inherit",
cursor: "pointer",
font: "inherit",
padding: 0,
textAlign: "inherit",
width: "100%",
}}
>
{props.triggerContent}
</Box>
);
}
return (
<Button size="compact-sm" variant="light" onClick={() => setManualRun(true)}>
{messages.loadRequest}
@@ -214,6 +214,37 @@ describe("Custom Widget runtime ports", () => {
expect(setItem).not.toHaveBeenCalled();
});
it("preserves input focus across temporary binding updates", async () => {
const components = createCustomJsxComponents({
TablerIcon: (() => null) as never,
copyLabels: { copy: "Copy", copied: "Copied" },
});
await render(
<CustomJsxRenderer
template={'<Stack><TextInput bind="search"/><Text>{inputs.search}</Text></Stack>'}
data={{}}
components={components}
createBindings={() => ({})}
messages={{ noTemplate: "No template", templateWarnings: (count) => `${count} warnings` }}
/>,
createPort(),
);
await settle();
const input = host.querySelector("input") as HTMLInputElement;
input.focus();
await act(async () => {
input.value = "p";
input.dispatchEvent(new InputEvent("input", { bubbles: true, data: "p", inputType: "insertText" }));
});
await settle();
expect(input.isConnected).toBe(true);
expect(document.activeElement).toBe(input);
expect(input.value).toBe("p");
expect(host.textContent).toContain("p");
});
it("resets temporary bindings when the template changes", async () => {
const rendererMessages = {
noTemplate: "No template",
@@ -328,6 +359,50 @@ describe("Custom Widget runtime ports", () => {
expect(host.textContent).toContain("Bulbasaur:200:false");
});
it("keeps manual query results local instead of publishing a shared request slot", async () => {
const port = createPort();
const publish = vi.fn();
await render(
<SubFetch requestId="details" trigger="manual" triggerContent={<span>Bulbasaur card</span>}>
{(data) => <span>{(data as { name: string }).name}</span>}
</SubFetch>,
port,
[],
publish,
);
await act(async () => (host.querySelector("button") as HTMLButtonElement).click());
await settle();
expect(port.query).toHaveBeenCalledOnce();
expect(publish).not.toHaveBeenCalled();
expect(host.textContent).toContain("Bulbasaur");
});
it("runs a manual query from a custom accessible trigger", async () => {
const port = createPort();
await render(
<SubFetch
requestId="details"
trigger="manual"
triggerAriaLabel="Open Bulbasaur"
triggerContent={<span>Bulbasaur card</span>}
>
{(data) => <span>{(data as { name: string }).name}</span>}
</SubFetch>,
port,
);
const trigger = host.querySelector("button") as HTMLButtonElement;
expect(trigger.getAttribute("aria-label")).toBe("Open Bulbasaur");
expect(host.textContent).toContain("Bulbasaur card");
await act(async () => trigger.click());
await settle();
expect(port.query).toHaveBeenCalledOnce();
expect(host.textContent).toContain("Bulbasaur");
});
it("passes cancellation to the port when the component unmounts", async () => {
let signal: AbortSignal | undefined;
const port = createPort({
@@ -43,6 +43,9 @@ export default function CustomApiWidget({
);
if (query.error) {
const errorCode = query.error.data?.code;
if (isEditMode && errorCode === "NOT_FOUND") {
return <Unavailable message={t("editModePending")} />;
}
const isUnavailable = errorCode === "NOT_FOUND" || errorCode === "FORBIDDEN";
return (
<Unavailable
@@ -104,7 +104,7 @@ describe("CustomJsxDisplay", () => {
it("keeps runtime components inside an inert provider before a preview session exists", async () => {
await renderDisplay({ template: '<RefreshButton label="Refresh" />', data: {} });
expect(container.textContent).toContain("Refresh");
expect(container.querySelector('button[aria-label="Refresh"]')).not.toBeNull();
expect(container.textContent).not.toContain("RUNTIME_RENDER_ERROR");
expect(container.querySelector("button")?.disabled).toBe(true);
});
@@ -114,13 +114,29 @@ describe("CustomJsxDisplay", () => {
expect(pokedex).toBeDefined();
await renderDisplay({
template: pokedex?.template,
data: { pokemon: { count: 2, results: [{ name: "bulbasaur" }, { name: "pikachu" }] } },
data: {
pokemon: {
count: 2,
results: [
{ name: "bulbasaur", url: "https://pokeapi.co/api/v2/pokemon/1/" },
{ name: "pikachu", url: "https://pokeapi.co/api/v2/pokemon/25/" },
],
},
},
status: { pokemon: { loading: false, ok: true, status: 200 } },
options: getCustomWidgetDefaultOptions(pokedex?.options ?? {}),
});
expect(container.textContent).toContain("bulbasaur");
expect(container.textContent).toContain("pikachu");
expect(
container.querySelector('img[src="https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/pokemon/1.png"]'),
).not.toBeNull();
expect(
container.querySelector('img[src="https://cdn.jsdelivr.net/gh/PokeAPI/sprites@master/sprites/pokemon/25.png"]'),
).not.toBeNull();
expect(container.querySelectorAll("img.mantine-Image-root")).toHaveLength(2);
expect(container.querySelectorAll(".mantine-Card-root")).toHaveLength(2);
expect(container.textContent).not.toContain("RUNTIME_RENDER_ERROR");
});
+86 -27
View File
@@ -24,6 +24,7 @@ import type {
} from "./schema";
import {
WORKSHOP_API_URL,
MAX_WORKSHOP_SCREENSHOTS,
WORKSHOP_REQUEST_TIMEOUT_MS,
workshopCommentSchema,
workshopReportSchema,
@@ -55,7 +56,13 @@ export interface WorkshopPage<T> {
items: T[];
}
export interface WorkshopScreenshotChanges {
additions?: File[];
removals?: string[];
}
interface WorkshopBaseRecord {
[key: string]: unknown;
id: string;
collectionId: string;
collectionName: string;
@@ -95,6 +102,7 @@ export interface WorkshopSubmissionRecord extends WorkshopBaseRecord {
export interface WorkshopListingRecord extends Omit<WorkshopSubmissionRecord, "content" | "screenshots"> {
screenshots: string[] | string;
authorName: string;
authorAvatar: string;
authorAvatarUrl: string;
authorGithubUsername: string;
authorGithubProfileUrl: string;
@@ -220,7 +228,10 @@ function listingFilter(pocketBase: TypedWorkshopPocketBase, options: WorkshopLis
const isViewCompatibilityError = (error: unknown) =>
error instanceof ClientResponseError && (error.status === 400 || error.status === 404);
const enrichAuthor = (row: unknown) => {
const enrichAuthor = (
row: unknown,
resolveAvatarUrl?: (record: Record<string, unknown>, user: Record<string, unknown>) => string,
) => {
if (typeof row !== "object" || row === null || Array.isArray(row)) return row;
const record = row as Record<string, unknown>;
const expand = record.expand;
@@ -234,7 +245,7 @@ const enrichAuthor = (row: unknown) => {
return {
...record,
authorName: record.authorName || user.displayName || user.username,
authorAvatarUrl: record.authorAvatarUrl || user.avatarUrl,
authorAvatarUrl: resolveAvatarUrl?.(record, user) || record.authorAvatarUrl || user.avatarUrl,
authorGithubUsername: githubUsername,
authorGithubProfileUrl:
record.authorGithubProfileUrl ||
@@ -245,9 +256,12 @@ const enrichAuthor = (row: unknown) => {
};
};
const parseListings = (rows: unknown[]) =>
const parseListings = (
rows: unknown[],
resolveAvatarUrl?: (record: Record<string, unknown>, user: Record<string, unknown>) => string,
) =>
rows.flatMap((row) => {
const result = workshopSubmissionSummarySchema.safeParse(enrichAuthor(row));
const result = workshopSubmissionSummarySchema.safeParse(enrichAuthor(row, resolveAvatarUrl));
return result.success ? [result.data] : [];
});
@@ -282,15 +296,33 @@ export class WorkshopBackend {
this.pocketBase.autoCancellation(false);
}
private userAvatarUrl(record: Record<string, unknown>) {
const avatar = typeof record.avatar === "string" ? record.avatar : "";
if (avatar) return this.pocketBase.files.getURL(record, avatar);
return typeof record.avatarUrl === "string" ? record.avatarUrl : "";
}
private listingAuthorAvatarUrl(record: Record<string, unknown>, user: Record<string, unknown>) {
const expandedAvatarUrl = this.userAvatarUrl(user);
if (expandedAvatarUrl) return expandedAvatarUrl;
const author = typeof record.author === "string" ? record.author : "";
const avatar = typeof record.authorAvatar === "string" ? record.authorAvatar : "";
if (!author || !avatar) return "";
return `${this.baseUrl}/api/files/users/${encodeURIComponent(author)}/${encodeURIComponent(avatar)}`;
}
public get currentUser(): WorkshopUser | null {
const record = this.pocketBase.authStore.record;
if (!record) return null;
return workshopUserSchema.parse({
id: record.id,
displayName: record.displayName || record.name || record.username || "Community member",
avatarUrl: record.avatarUrl || (record.avatar ? this.pocketBase.files.getURL(record, record.avatar) : ""),
githubUsername: record.githubUsername || record.username || "",
githubProfileUrl: record.githubProfileUrl || "",
avatarUrl: this.userAvatarUrl(record),
githubUsername: record.githubUsername || "",
githubProfileUrl:
record.githubProfileUrl ||
(record.githubUsername ? `https://github.com/${encodeURIComponent(record.githubUsername)}` : ""),
isAdmin: record.isAdmin === true,
});
}
@@ -342,7 +374,10 @@ export class WorkshopBackend {
sort: listingSort(options.sort),
signal: requestSignal(options.signal),
});
return { ...result, items: parseListings(result.items) };
return {
...result,
items: parseListings(result.items, (record, user) => this.listingAuthorAvatarUrl(record, user)),
};
} catch (error) {
if (!isViewCompatibilityError(error)) throw error;
const items = filterListings(await this.loadListingsFallback(options.signal), options);
@@ -368,7 +403,7 @@ export class WorkshopBackend {
sort: listingSort(options.sort),
signal: requestSignal(options.signal),
});
return parseListings(rows);
return parseListings(rows, (record, user) => this.listingAuthorAvatarUrl(record, user));
} catch (error) {
if (!isViewCompatibilityError(error)) throw error;
return filterListings(await this.loadListingsFallback(options.signal), options);
@@ -388,7 +423,7 @@ export class WorkshopBackend {
return this.pocketBase.collection("submissions").getFullList({ ...options, expand: "author" });
throw error;
});
return parseListings(rows);
return parseListings(rows, (record, user) => this.listingAuthorAvatarUrl(record, user));
}
public async get(id: string, signal?: AbortSignal): Promise<WorkshopSubmissionDetail> {
@@ -404,7 +439,10 @@ export class WorkshopBackend {
throw error;
});
return workshopSubmissionDetailSchema.parse(
enrichAuthor({ ...submission, ...listing, expand: submission.expand, content: submission.content }),
enrichAuthor(
{ ...submission, ...listing, expand: submission.expand, content: submission.content },
(record, user) => this.listingAuthorAvatarUrl(record, user),
),
);
} catch (error) {
throw workshopError(error, "Submission not found");
@@ -432,15 +470,24 @@ export class WorkshopBackend {
}
}
public async update(id: string, input: WorkshopSubmissionInput, screenshots: File[] = []) {
public async update(id: string, input: WorkshopSubmissionInput, screenshotChanges: WorkshopScreenshotChanges = {}) {
const parsed = workshopSubmissionInputSchema.parse(input);
workshopScreenshotsSchema.parse(screenshots);
const additions = screenshotChanges.additions ?? [];
const removals = screenshotChanges.removals ?? [];
workshopScreenshotsSchema.parse(additions);
const current = await this.get(id);
const data = new FormData();
Object.entries(parsed).forEach(([key, value]) => data.set(key, typeof value === "string" ? value : String(value)));
data.set("widgetSchema", parsed.type === "customCss" ? WORKSHOP_CSS_SCHEMA : CUSTOM_WIDGET_SCHEMA);
data.set("revision", String(current.revision + 1));
screenshots.forEach((file) => data.append("screenshots", file));
const removalSet = new Set(removals);
const retainedCount = current.screenshots.filter((filename) => !removalSet.has(filename)).length;
if (retainedCount + additions.length > MAX_WORKSHOP_SCREENSHOTS)
throw new Error(`A submission can have up to ${MAX_WORKSHOP_SCREENSHOTS} screenshots`);
const data: Record<string, unknown> = {
...parsed,
widgetSchema: parsed.type === "customCss" ? WORKSHOP_CSS_SCHEMA : CUSTOM_WIDGET_SCHEMA,
revision: current.revision + 1,
};
if (additions.length > 0) data["screenshots+"] = additions;
if (removals.length > 0) data["screenshots-"] = removals;
try {
await this.pocketBase.collection("submissions").update(id, data);
return this.get(id);
@@ -554,8 +601,12 @@ export class WorkshopBackend {
workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
authorAvatarUrl: row.expand?.author ? this.userAvatarUrl(row.expand.author) : undefined,
authorGithubProfileUrl:
row.expand?.author?.githubProfileUrl ||
(row.expand?.author?.githubUsername
? `https://github.com/${encodeURIComponent(row.expand.author.githubUsername)}`
: undefined),
}),
);
} catch (error) {
@@ -571,8 +622,12 @@ export class WorkshopBackend {
return workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
authorAvatarUrl: row.expand?.author ? this.userAvatarUrl(row.expand.author) : undefined,
authorGithubProfileUrl:
row.expand?.author?.githubProfileUrl ||
(row.expand?.author?.githubUsername
? `https://github.com/${encodeURIComponent(row.expand.author.githubUsername)}`
: undefined),
});
} catch (error) {
throw workshopError(error, "Failed to post comment");
@@ -587,8 +642,12 @@ export class WorkshopBackend {
return workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
authorAvatarUrl: row.expand?.author ? this.userAvatarUrl(row.expand.author) : undefined,
authorGithubProfileUrl:
row.expand?.author?.githubProfileUrl ||
(row.expand?.author?.githubUsername
? `https://github.com/${encodeURIComponent(row.expand.author.githubUsername)}`
: undefined),
});
} catch (error) {
throw workshopError(error, "Failed to update comment");
@@ -661,12 +720,12 @@ export const workshopUpdateMutationOptions = (backend: WorkshopBackend) =>
mutationFn: ({
id,
input,
screenshots = [],
screenshotChanges,
}: {
id: string;
input: WorkshopSubmissionInput;
screenshots?: File[];
}) => backend.update(id, input, screenshots),
screenshotChanges?: WorkshopScreenshotChanges;
}) => backend.update(id, input, screenshotChanges),
});
export const workshopDeleteMutationOptions = (backend: WorkshopBackend) =>
+36
View File
@@ -82,6 +82,42 @@ describe("WorkshopBackend", () => {
expect(mocks.autoCancellation).toHaveBeenCalledWith(false);
});
test("appends and removes screenshots without replacing retained files", async () => {
const client = new WorkshopBackend("https://workshop.example.com");
const current = {
...listingRecord(),
type: "customCss" as const,
content: ".dashboard { color: red; }",
screenshots: ["keep.png", "remove.png"],
revision: 2,
};
vi.spyOn(client, "get").mockResolvedValue(current as never);
mocks.update.mockResolvedValue(current);
const addition = new File(["image"], "new.png", { type: "image/png" });
await client.update(
current.id,
{
type: "customCss",
title: current.title,
description: current.description,
content: current.content,
changelog: "Updated screenshots",
outdated: false,
},
{ additions: [addition], removals: ["remove.png"] },
);
expect(mocks.update).toHaveBeenCalledWith(
current.id,
expect.objectContaining({
"screenshots+": [addition],
"screenshots-": ["remove.png"],
revision: 3,
}),
);
});
test("uses PocketBase filtering and pagination when the listing view is current", async () => {
mocks.getList.mockResolvedValue({
page: 1,
-393
View File
@@ -1,393 +0,0 @@
import PocketBase, { ClientResponseError } from "pocketbase";
import { CUSTOM_WIDGET_SCHEMA } from "@homarr/custom-widgets/core";
import type {
WorkshopComment,
WorkshopReport,
WorkshopSubmissionDetail,
WorkshopSubmissionInput,
WorkshopSubmissionSummary,
WorkshopSubmissionType,
WorkshopUser,
WorkshopVote,
} from "./schema";
import {
WORKSHOP_API_URL,
WORKSHOP_REQUEST_TIMEOUT_MS,
workshopCommentSchema,
workshopReportSchema,
workshopSubmissionDetailSchema,
workshopSubmissionSummarySchema,
workshopSubmissionInputSchema,
workshopScreenshotsSchema,
workshopUserSchema,
workshopVoteSchema,
WORKSHOP_CSS_SCHEMA,
} from "./schema";
export interface WorkshopListOptions {
page?: number;
perPage?: number;
sort?: "top" | "newest" | "recent" | "discussed";
search?: string;
author?: string;
type?: WorkshopSubmissionType | "all";
includeOutdated?: boolean;
signal?: AbortSignal;
}
export interface WorkshopPage<T> {
page: number;
perPage: number;
totalPages: number;
totalItems: number;
items: T[];
}
const requestSignal = (signal?: AbortSignal) =>
AbortSignal.any(
signal
? [signal, AbortSignal.timeout(WORKSHOP_REQUEST_TIMEOUT_MS)]
: [AbortSignal.timeout(WORKSHOP_REQUEST_TIMEOUT_MS)],
);
function oauthText(...values: unknown[]) {
return values.find((value): value is string => typeof value === "string" && value.trim().length > 0)?.trim();
}
function githubProfile(meta: Record<string, unknown> | undefined, record: Record<string, unknown>) {
const rawUser =
meta?.rawUser && typeof meta.rawUser === "object" ? (meta.rawUser as Record<string, unknown>) : undefined;
const displayName = oauthText(meta?.name, meta?.username, rawUser?.name, rawUser?.login);
const avatarUrl = oauthText(meta?.avatarUrl, meta?.avatarURL, rawUser?.avatar_url);
const githubUsername = oauthText(meta?.username, rawUser?.login);
return {
displayName: (displayName ?? `GitHub user ${String(record.id ?? "").slice(0, 8)}`).slice(0, 100),
avatarUrl: avatarUrl?.startsWith("https://") ? avatarUrl : undefined,
githubUsername,
githubProfileUrl: githubUsername ? `https://github.com/${encodeURIComponent(githubUsername)}` : undefined,
};
}
const listingSort = (sort: WorkshopListOptions["sort"]) => {
if (sort === "newest") return "-created";
if (sort === "recent") return "-updated";
if (sort === "discussed") return "-commentCount,-created";
return "-score,-created";
};
function workshopError(error: unknown, fallback: string) {
const rawMessage = error instanceof Error ? error.message : String(error ?? "");
if (/popup.*block|blocked.*popup/iu.test(rawMessage))
return new Error("GitHub sign-in popup was blocked. Allow popups for this site and try again.", { cause: error });
if (/cancel|closed.*popup|popup.*closed/iu.test(rawMessage))
return new Error("GitHub sign-in was cancelled before it completed.", { cause: error });
if (
/provider|oauth|redirect|callback|client.?id/iu.test(rawMessage) &&
/invalid|missing|not found|failed/iu.test(rawMessage)
)
return new Error("GitHub sign-in is not configured correctly on the Workshop server.", { cause: error });
if (error instanceof ClientResponseError) {
const sdkMessage = error.data?.message || error.message;
const originalMessage =
error.originalError instanceof Error ? error.originalError.message : String(error.originalError?.message ?? "");
const message = !sdkMessage || sdkMessage === "Something went wrong." ? originalMessage || fallback : sdkMessage;
return new Error(message, { cause: error });
}
if (error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError"))
return new Error(`${fallback}. The request timed out.`, { cause: error });
return error instanceof Error ? error : new Error(fallback);
}
export class WorkshopClient {
public readonly pocketBase: PocketBase;
public constructor(public readonly baseUrl = WORKSHOP_API_URL) {
this.pocketBase = new PocketBase(baseUrl.replace(/\/$/u, ""));
}
public get currentUser(): WorkshopUser | null {
const record = this.pocketBase.authStore.record;
if (!record) return null;
return workshopUserSchema.parse({
id: record.id,
displayName: record.displayName || record.name || record.username || "Community member",
avatarUrl: record.avatarUrl || (record.avatar ? this.pocketBase.files.getURL(record, record.avatar) : ""),
githubUsername: record.githubUsername || record.username || "",
githubProfileUrl: record.githubProfileUrl || "",
isAdmin: record.isAdmin === true,
});
}
public subscribeToAuth(listener: (user: WorkshopUser | null) => void) {
return this.pocketBase.authStore.onChange(() => listener(this.currentUser), true);
}
public async refreshAuth() {
if (!this.pocketBase.authStore.isValid) return null;
try {
await this.pocketBase.collection("users").authRefresh();
return this.currentUser;
} catch (error) {
if (error instanceof ClientResponseError && (error.status === 401 || error.status === 403)) {
this.pocketBase.authStore.clear();
return null;
}
return this.currentUser;
}
}
public async signInWithGitHub() {
try {
const auth = await this.pocketBase.collection("users").authWithOAuth2({
provider: "github",
createData: { displayName: "GitHub user" },
});
const profile = githubProfile(auth.meta, auth.record);
const updated = await this.pocketBase.collection("users").update(auth.record.id, profile);
this.pocketBase.authStore.save(auth.token, updated);
return this.currentUser;
} catch (error) {
throw workshopError(error, "GitHub sign-in failed");
}
}
public signOut() {
this.pocketBase.authStore.clear();
}
public async list(options: WorkshopListOptions = {}): Promise<WorkshopPage<WorkshopSubmissionSummary>> {
const filters: string[] = [];
if (options.type && options.type !== "all")
filters.push(this.pocketBase.filter("type = {:type}", { type: options.type }));
if (options.search?.trim())
filters.push(this.pocketBase.filter("title ~ {:search}", { search: options.search.trim() }));
if (options.author) filters.push(this.pocketBase.filter("author = {:author}", { author: options.author }));
if (options.includeOutdated === false) filters.push("outdated = false");
try {
const result = await this.pocketBase
.collection("workshop_listings")
.getList(options.page ?? 1, options.perPage ?? 24, {
filter: filters.join(" && "),
sort: listingSort(options.sort),
signal: requestSignal(options.signal),
});
return { ...result, items: result.items.map((item) => workshopSubmissionSummarySchema.parse(item)) };
} catch (error) {
throw workshopError(error, "Failed to load Workshop submissions");
}
}
public async listAll(options: Omit<WorkshopListOptions, "page" | "perPage"> = {}) {
const filters: string[] = [];
if (options.type && options.type !== "all")
filters.push(this.pocketBase.filter("type = {:type}", { type: options.type }));
if (options.search?.trim())
filters.push(this.pocketBase.filter("title ~ {:search}", { search: options.search.trim() }));
if (options.author) filters.push(this.pocketBase.filter("author = {:author}", { author: options.author }));
if (options.includeOutdated === false) filters.push("outdated = false");
try {
const items = await this.pocketBase.collection("workshop_listings").getFullList({
batch: 200,
filter: filters.join(" && "),
sort: listingSort(options.sort),
signal: requestSignal(options.signal),
});
return items.map((item) => workshopSubmissionSummarySchema.parse(item));
} catch (error) {
throw workshopError(error, "Failed to load Workshop submissions");
}
}
public async get(id: string, signal?: AbortSignal): Promise<WorkshopSubmissionDetail> {
try {
const [submission, listing] = await Promise.all([
this.pocketBase.collection("submissions").getOne(id, { signal: requestSignal(signal) }),
this.pocketBase.collection("workshop_listings").getOne(id, { signal: requestSignal(signal) }),
]);
return workshopSubmissionDetailSchema.parse({ ...submission, ...listing, content: submission.content });
} catch (error) {
throw workshopError(error, "Submission not found");
}
}
public fileUrl(submissionId: string, filename: string, thumb?: string) {
return `${this.baseUrl}/api/files/submissions/${submissionId}/${encodeURIComponent(filename)}${thumb ? `?thumb=${encodeURIComponent(thumb)}` : ""}`;
}
public async create(input: WorkshopSubmissionInput, screenshots: File[] = []) {
const parsed = workshopSubmissionInputSchema.parse(input);
workshopScreenshotsSchema.parse(screenshots);
const data = new FormData();
Object.entries(parsed).forEach(([key, value]) => data.set(key, typeof value === "string" ? value : String(value)));
data.set("widgetSchema", parsed.type === "customCss" ? WORKSHOP_CSS_SCHEMA : CUSTOM_WIDGET_SCHEMA);
data.set("author", this.currentUser?.id ?? "");
data.set("revision", "1");
screenshots.forEach((file) => data.append("screenshots", file));
try {
const result = await this.pocketBase.collection("submissions").create(data);
return this.get(result.id);
} catch (error) {
throw workshopError(error, "Failed to publish submission");
}
}
public async update(id: string, input: WorkshopSubmissionInput, screenshots: File[] = []) {
const parsed = workshopSubmissionInputSchema.parse(input);
workshopScreenshotsSchema.parse(screenshots);
const current = await this.get(id);
const data = new FormData();
Object.entries(parsed).forEach(([key, value]) => data.set(key, typeof value === "string" ? value : String(value)));
data.set("widgetSchema", parsed.type === "customCss" ? WORKSHOP_CSS_SCHEMA : CUSTOM_WIDGET_SCHEMA);
data.set("revision", String(current.revision + 1));
screenshots.forEach((file) => data.append("screenshots", file));
try {
await this.pocketBase.collection("submissions").update(id, data);
return this.get(id);
} catch (error) {
throw workshopError(error, "Failed to update submission");
}
}
public async delete(id: string) {
try {
await this.pocketBase.collection("submissions").delete(id);
} catch (error) {
throw workshopError(error, "Failed to delete submission");
}
}
public async vote(submission: string, value: 1 | -1): Promise<WorkshopVote | null> {
const user = this.currentUser?.id ?? "";
const filter = this.pocketBase.filter("submission = {:submission} && user = {:user}", { submission, user });
try {
const existing = await this.pocketBase
.collection("votes")
.getFirstListItem(filter)
.catch((error: unknown) =>
error instanceof ClientResponseError && error.status === 404 ? null : Promise.reject(error),
);
if (existing?.value === value) {
await this.pocketBase.collection("votes").delete(existing.id);
return null;
}
const record = existing
? await this.pocketBase.collection("votes").update(existing.id, { value })
: await this.pocketBase.collection("votes").create({ submission, user, value });
return workshopVoteSchema.parse(record);
} catch (error) {
throw workshopError(error, "Failed to save vote");
}
}
public async report(submission: string, category: WorkshopReport["category"], explanation: string) {
try {
return workshopReportSchema.parse(
await this.pocketBase.collection("reports").create({
submission,
reporter: this.currentUser?.id ?? "",
category,
explanation: explanation.trim(),
status: "open",
}),
);
} catch (error) {
throw workshopError(error, "Failed to report submission");
}
}
public async listReports(): Promise<WorkshopReport[]> {
try {
const items = await this.pocketBase
.collection("reports")
.getFullList({ batch: 200, filter: "status = 'open'", sort: "-created", expand: "reporter,submission" });
return items.map((item) =>
workshopReportSchema.parse({
...item,
reporterName: item.expand?.reporter?.displayName,
submissionTitle: item.expand?.submission?.title,
}),
);
} catch (error) {
throw workshopError(error, "Failed to load reports");
}
}
public async dismissReport(id: string) {
try {
await this.pocketBase.collection("reports").update(id, { status: "dismissed" });
} catch (error) {
throw workshopError(error, "Failed to dismiss report");
}
}
public async toggleOutdated(id: string, outdated: boolean) {
try {
await this.pocketBase.collection("submissions").update(id, { outdated });
return this.get(id);
} catch (error) {
throw workshopError(error, "Failed to update submission status");
}
}
public async listComments(submission: string): Promise<WorkshopComment[]> {
try {
const rows = await this.pocketBase.collection("comments").getFullList({
filter: this.pocketBase.filter("submission = {:submission}", { submission }),
sort: "-created",
expand: "author",
});
return rows.map((row) =>
workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
}),
);
} catch (error) {
throw workshopError(error, "Failed to load comments");
}
}
public async createComment(submission: string, content: string): Promise<WorkshopComment> {
try {
const row = await this.pocketBase
.collection("comments")
.create({ submission, author: this.currentUser?.id ?? "", content: content.trim() }, { expand: "author" });
return workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
});
} catch (error) {
throw workshopError(error, "Failed to post comment");
}
}
public async updateComment(id: string, content: string): Promise<WorkshopComment> {
try {
const row = await this.pocketBase
.collection("comments")
.update(id, { content: content.trim() }, { expand: "author" });
return workshopCommentSchema.parse({
...row,
authorName: row.expand?.author?.displayName,
authorAvatarUrl: row.expand?.author?.avatarUrl,
authorGithubProfileUrl: row.expand?.author?.githubProfileUrl,
});
} catch (error) {
throw workshopError(error, "Failed to update comment");
}
}
public async deleteComment(id: string) {
try {
await this.pocketBase.collection("comments").delete(id);
} catch (error) {
throw workshopError(error, "Failed to delete comment");
}
}
}
+1 -1
View File
@@ -1,2 +1,2 @@
export * from "./client";
export * from "./backend";
export * from "./schema";