Reusable widgets: reference widgets across dashboards + detach to clone
Widgets configured on one dashboard (e.g., a Grafana service's Overview)
can now be live-referenced on other dashboards. Editing the widget config
updates it everywhere it's referenced. References can be detached into
independent clones.
Backend: new widget_references table (dashboard_scope, widget_id,
sort_order) with ON DELETE CASCADE. CRUD methods + 4 endpoints:
GET/POST /api/widgets/references, DELETE /api/widgets/references/{id},
POST /api/widgets/references/{id}/detach (clones the widget into a
standalone instance, then removes the reference).
Frontend: WidgetConfigDialog gains a dashboardScope prop. When set
(the main Dashboard passes 'main'), the dialog shows:
- Owned + referenced widgets in a combined list, with a link badge on
references.
- 'Add existing widget' picker: searchable list of ALL widget instances
not already on this dashboard. Click to create a reference.
- Detach button on references: clones the widget (service_id=NULL) and
removes the reference.
- Delete on a reference removes the REFERENCE (not the original widget).
Dashboard renders referenced widgets alongside owned widgets.
Detaching a service-bound widget clones it with service_id=NULL — the
clone may need re-binding to a service to render correctly. Named
dashboards don't pass dashboardScope yet (pinned-links-only); when they
gain widget support, the backend already handles any scope string.
282 backend tests pass (+2 reference lifecycle); 127 frontend tests
pass; ruff/eslint/tsc/vite all green.
This commit is contained in:
@@ -6,6 +6,21 @@ import type {
|
||||
WidgetInstanceInput,
|
||||
} from "../types";
|
||||
|
||||
export interface WidgetReference {
|
||||
id: string;
|
||||
dashboard_scope: string;
|
||||
widget_id: string;
|
||||
sort_order: number;
|
||||
created_at: number;
|
||||
widget: WidgetInstance;
|
||||
}
|
||||
|
||||
export interface WidgetReferenceInput {
|
||||
dashboard_scope: string;
|
||||
widget_id: string;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export async function fetchBuiltinWidgetKinds(): Promise<
|
||||
BuiltinWidgetKindInfo[]
|
||||
> {
|
||||
@@ -46,3 +61,29 @@ export async function fetchWidgetData(
|
||||
): Promise<WidgetDataResponse> {
|
||||
return get<WidgetDataResponse>(`/api/widgets/instances/${widgetId}/data`);
|
||||
}
|
||||
|
||||
export async function fetchWidgetReferences(
|
||||
dashboardScope: string,
|
||||
): Promise<WidgetReference[]> {
|
||||
return get<WidgetReference[]>("/api/widgets/references", {
|
||||
dashboard_scope: dashboardScope,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createWidgetReference(
|
||||
input: WidgetReferenceInput,
|
||||
): Promise<WidgetReference> {
|
||||
return post<WidgetReference>("/api/widgets/references", input);
|
||||
}
|
||||
|
||||
export async function deleteWidgetReference(
|
||||
referenceId: string,
|
||||
): Promise<{ status: string }> {
|
||||
return del<{ status: string }>(`/api/widgets/references/${referenceId}`);
|
||||
}
|
||||
|
||||
export async function detachWidgetReference(
|
||||
referenceId: string,
|
||||
): Promise<WidgetInstance> {
|
||||
return post<WidgetInstance>(`/api/widgets/references/${referenceId}/detach`);
|
||||
}
|
||||
|
||||
@@ -19,11 +19,23 @@ import {
|
||||
} from "@/components/ui/select";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { ChevronDown, ChevronUp, Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Link2,
|
||||
Pencil,
|
||||
Plus,
|
||||
Trash2,
|
||||
Split,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useCreateWidgetReference,
|
||||
useDeleteWidgetInstance,
|
||||
useDeleteWidgetReference,
|
||||
useDetachWidgetReference,
|
||||
useSaveWidgetInstance,
|
||||
useWidgetInstances,
|
||||
useWidgetReferences,
|
||||
} from "../hooks/useWidgets";
|
||||
import { useServiceInstances } from "../hooks/useServices";
|
||||
import { useTasks } from "../hooks/useSettings";
|
||||
@@ -41,6 +53,8 @@ interface Props {
|
||||
onClose: () => void;
|
||||
/** When set, scope the dialog to a specific service instance's widgets. */
|
||||
serviceId?: string;
|
||||
/** When set, enable widget references ("Add existing") for this dashboard scope. */
|
||||
dashboardScope?: string;
|
||||
}
|
||||
|
||||
interface Draft {
|
||||
@@ -183,12 +197,24 @@ function WidgetConfigEditor({
|
||||
);
|
||||
}
|
||||
|
||||
export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
export function WidgetConfigDialog({
|
||||
open,
|
||||
onClose,
|
||||
serviceId,
|
||||
dashboardScope,
|
||||
}: Props) {
|
||||
const { data: instances = [] } = useWidgetInstances(serviceId);
|
||||
const { data: services = [] } = useServiceInstances();
|
||||
const { data: tasks = [] } = useTasks();
|
||||
const saveWidget = useSaveWidgetInstance();
|
||||
const deleteWidget = useDeleteWidgetInstance();
|
||||
const { data: references = [] } = useWidgetReferences(dashboardScope);
|
||||
const createRef = useCreateWidgetReference();
|
||||
const deleteRef = useDeleteWidgetReference();
|
||||
const detachRef = useDetachWidgetReference();
|
||||
const { data: allWidgets = [] } = useWidgetInstances();
|
||||
const [showExisting, setShowExisting] = useState(false);
|
||||
const [existingSearch, setExistingSearch] = useState("");
|
||||
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
|
||||
@@ -284,6 +310,55 @@ export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
await deleteWidget.mutateAsync(instance.id);
|
||||
}
|
||||
|
||||
// Build a combined view of owned widgets + references for display.
|
||||
const referencedWidgetIds = new Set(references.map((r) => r.widget_id));
|
||||
const combinedWidgets = useMemo(() => {
|
||||
const owned = [...instances].sort(
|
||||
(a, b) => a.sort_order - b.sort_order || a.created_at - b.created_at,
|
||||
);
|
||||
const refs = references.map((r) => ({
|
||||
...r.widget,
|
||||
_ref_id: r.id,
|
||||
_is_reference: true as const,
|
||||
}));
|
||||
return [...owned, ...refs].sort(
|
||||
(a, b) => a.sort_order - b.sort_order || a.created_at - b.created_at,
|
||||
);
|
||||
}, [instances, references]);
|
||||
|
||||
// Available widgets for the "Add existing" picker: all widgets not already
|
||||
// on this dashboard (owned or referenced).
|
||||
const availableWidgets = useMemo(() => {
|
||||
const onDashboard = new Set([
|
||||
...instances.map((w) => w.id),
|
||||
...referencedWidgetIds,
|
||||
]);
|
||||
const search = existingSearch.toLowerCase().trim();
|
||||
return allWidgets
|
||||
.filter((w) => !onDashboard.has(w.id))
|
||||
.filter(
|
||||
(w) =>
|
||||
!search ||
|
||||
w.title.toLowerCase().includes(search) ||
|
||||
w.widget_kind.toLowerCase().includes(search),
|
||||
);
|
||||
}, [allWidgets, instances, referencedWidgetIds, existingSearch]);
|
||||
|
||||
async function handleAddReference(widgetId: string) {
|
||||
await createRef.mutateAsync({
|
||||
dashboard_scope: dashboardScope!,
|
||||
widget_id: widgetId,
|
||||
});
|
||||
}
|
||||
|
||||
async function handleRemoveReference(refId: string) {
|
||||
await deleteRef.mutateAsync(refId);
|
||||
}
|
||||
|
||||
async function handleDetach(refId: string) {
|
||||
await detachRef.mutateAsync(refId);
|
||||
}
|
||||
|
||||
function handleClose(next: boolean) {
|
||||
if (!next) {
|
||||
reset();
|
||||
@@ -370,16 +445,19 @@ export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{sortedInstances.length === 0 ? (
|
||||
{combinedWidgets.length === 0 ? (
|
||||
<Alert>
|
||||
<AlertDescription>No widgets yet. Add one below.</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{sortedInstances.map((instance, index) => {
|
||||
{combinedWidgets.map((instance, index) => {
|
||||
const serviceName = instance.service_id
|
||||
? services.find((s) => s.id === instance.service_id)?.name
|
||||
: "Built-in";
|
||||
const isRef =
|
||||
(instance as { _is_reference?: boolean })._is_reference === true;
|
||||
const refId = (instance as { _ref_id?: string })._ref_id;
|
||||
return (
|
||||
<div
|
||||
key={instance.id}
|
||||
@@ -388,6 +466,12 @@ export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{instance.title}</span>
|
||||
{isRef ? (
|
||||
<Badge variant="secondary">
|
||||
<Link2 className="mr-1 h-3 w-3" />
|
||||
linked
|
||||
</Badge>
|
||||
) : null}
|
||||
<Badge variant="outline">
|
||||
{bindingLabel(instance.service_id, instance.widget_kind)}
|
||||
</Badge>
|
||||
@@ -415,30 +499,52 @@ export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mobile-touch-target h-8 w-8"
|
||||
disabled={index === sortedInstances.length - 1}
|
||||
disabled={index === combinedWidgets.length - 1}
|
||||
onClick={() => moveInstance(index, 1)}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
<Switch
|
||||
className="mobile-touch-target"
|
||||
checked={instance.enabled}
|
||||
onCheckedChange={() => toggleEnabled(instance)}
|
||||
aria-label={`Toggle ${instance.title}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mobile-touch-target h-8 w-8"
|
||||
onClick={() => startEdit(instance)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
{!isRef ? (
|
||||
<Switch
|
||||
className="mobile-touch-target"
|
||||
checked={instance.enabled}
|
||||
onCheckedChange={() => toggleEnabled(instance)}
|
||||
aria-label={`Toggle ${instance.title}`}
|
||||
/>
|
||||
) : null}
|
||||
{!isRef ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mobile-touch-target h-8 w-8"
|
||||
onClick={() => startEdit(instance)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
{isRef && refId ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mobile-touch-target h-8 w-8"
|
||||
title="Make an independent copy"
|
||||
onClick={() => handleDetach(refId)}
|
||||
>
|
||||
<Split className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="mobile-touch-target h-8 w-8 text-destructive"
|
||||
onClick={() => removeInstance(instance)}
|
||||
title={
|
||||
isRef ? "Remove from this dashboard" : "Delete widget"
|
||||
}
|
||||
onClick={() =>
|
||||
isRef && refId
|
||||
? handleRemoveReference(refId)
|
||||
: removeInstance(instance)
|
||||
}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -449,6 +555,65 @@ export function WidgetConfigDialog({ open, onClose, serviceId }: Props) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dashboardScope ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={() => setShowExisting(!showExisting)}
|
||||
>
|
||||
<Link2 className="mr-1 h-3 w-3" />
|
||||
{showExisting ? "Hide" : "Add existing widget"}
|
||||
</Button>
|
||||
{showExisting ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Input
|
||||
placeholder="Search widgets..."
|
||||
value={existingSearch}
|
||||
onChange={(e) => setExistingSearch(e.target.value)}
|
||||
/>
|
||||
{availableWidgets.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No widgets available to reuse.
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{availableWidgets.map((w) => {
|
||||
const owner = w.service_id
|
||||
? services.find((s) => s.id === w.service_id)?.name
|
||||
: "Dashboard";
|
||||
return (
|
||||
<div
|
||||
key={w.id}
|
||||
className="flex items-center gap-2 rounded border p-2"
|
||||
>
|
||||
<div className="flex flex-1 flex-col">
|
||||
<span className="text-sm font-medium">{w.title}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{bindingLabel(w.service_id, w.widget_kind)} ·{" "}
|
||||
{owner}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mobile-touch-target"
|
||||
onClick={() => handleAddReference(w.id)}
|
||||
>
|
||||
<Plus className="mr-1 h-3 w-3" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-sm font-medium">Add widget</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
|
||||
@@ -18,8 +18,12 @@ function setMatchMedia(matches: boolean) {
|
||||
|
||||
vi.mock("../../hooks/useWidgets", () => ({
|
||||
useWidgetInstances: () => ({ data: [] }),
|
||||
useWidgetReferences: () => ({ data: [] }),
|
||||
useSaveWidgetInstance: () => ({ mutateAsync: vi.fn(), isPending: false }),
|
||||
useDeleteWidgetInstance: () => ({ mutateAsync: vi.fn(), isPending: false }),
|
||||
useCreateWidgetReference: () => ({ mutateAsync: vi.fn() }),
|
||||
useDeleteWidgetReference: () => ({ mutateAsync: vi.fn() }),
|
||||
useDetachWidgetReference: () => ({ mutateAsync: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useServices", () => ({
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
createWidgetInstance,
|
||||
createWidgetReference,
|
||||
deleteWidgetInstance,
|
||||
deleteWidgetReference,
|
||||
detachWidgetReference,
|
||||
fetchBuiltinWidgetKinds,
|
||||
fetchWidgetData,
|
||||
fetchWidgetInstances,
|
||||
fetchWidgetReferences,
|
||||
updateWidgetInstance,
|
||||
} from "../api/widgets";
|
||||
import type { WidgetInstanceInput } from "../types";
|
||||
@@ -58,3 +62,42 @@ export function useBuiltinWidgetKinds() {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useWidgetReferences(dashboardScope: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ["widgets", "references", dashboardScope ?? null],
|
||||
queryFn: () => fetchWidgetReferences(dashboardScope!),
|
||||
enabled: !!dashboardScope,
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateWidgetReference() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: createWidgetReference,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["widgets", "references"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteWidgetReference() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: deleteWidgetReference,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["widgets", "references"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDetachWidgetReference() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: detachWidgetReference,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["widgets"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
useDeleteDashboardShortcut,
|
||||
useSaveDashboardShortcut,
|
||||
} from "../hooks/useDashboard";
|
||||
import { useWidgetInstances } from "../hooks/useWidgets";
|
||||
import { useWidgetInstances, useWidgetReferences } from "../hooks/useWidgets";
|
||||
import { useServiceInstances } from "../hooks/useServices";
|
||||
import { useIsMobile } from "../hooks/useIsMobile";
|
||||
import type {
|
||||
@@ -452,16 +452,18 @@ export function Dashboard() {
|
||||
undefined,
|
||||
"dashboard",
|
||||
);
|
||||
const { data: widgetReferences = [] } = useWidgetReferences("main");
|
||||
const { data: services = [] } = useServiceInstances();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const visibleWidgets = useMemo(
|
||||
() =>
|
||||
widgetInstances
|
||||
.filter((w) => w.enabled)
|
||||
.sort((a, b) => a.sort_order - b.sort_order),
|
||||
[widgetInstances],
|
||||
);
|
||||
const visibleWidgets = useMemo(() => {
|
||||
const refs = widgetReferences
|
||||
.filter((r) => r.widget.enabled)
|
||||
.map((r) => r.widget);
|
||||
return [...widgetInstances, ...refs]
|
||||
.filter((w) => w.enabled)
|
||||
.sort((a, b) => a.sort_order - b.sort_order);
|
||||
}, [widgetInstances, widgetReferences]);
|
||||
|
||||
const mobileSections = useMemo(
|
||||
() => groupWidgetsBySection(visibleWidgets, services),
|
||||
@@ -592,6 +594,7 @@ export function Dashboard() {
|
||||
<WidgetConfigDialog
|
||||
open={widgetDialogOpen}
|
||||
onClose={() => setWidgetDialogOpen(false)}
|
||||
dashboardScope="main"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -23,6 +23,7 @@ vi.mock("../../hooks/useSettings", () => ({
|
||||
}));
|
||||
vi.mock("../../hooks/useWidgets", () => ({
|
||||
useWidgetInstances: () => ({ data: [] }),
|
||||
useWidgetReferences: () => ({ data: [] }),
|
||||
}));
|
||||
vi.mock("../../hooks/useServices", () => ({
|
||||
useServiceInstances: () => ({ data: [] }),
|
||||
|
||||
Reference in New Issue
Block a user