Repository Public
1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { useMemo, useState } from "react";4import { apiDelete, apiPut } from "@/api/client";5import { ApiError } from "@/api/errors";6import { invalidatePaths, useApiQuery } from "@/api/query";7import { useI18n } from "@/i18n";8import { usePref } from "@/lib/prefs";9import { Page, RequirePermission } from "@/shell/AppShell";10import { Banner, Button, ConfirmDialog, EmptyState, LinkButton, Menu, useErrorMessage, useToast } from "@/ui";11import { Grid } from "./Grid";12import { DASHBOARD_NAME, addWidget, addableTypes, defaultLayout, removeWidget, sameLayout, sanitizeLayout, setConfig, type Widget } from "./layout";13import { WIDGET_ICON, widgetTypeLabel } from "./widgets";1415export function OverviewScreen() {16 return (17 <RequirePermission permission="cluster.read">18 <Overview />19 </RequirePermission>20 );21}2223function Overview() {24 const { t } = useI18n();25 const qc = useQueryClient();26 const toast = useToast();27 const explain = useErrorMessage();28 const [compactPref, setCompactPref] = usePref<"0" | "1">("overview.compact", "0");29 const compact = compactPref === "1";3031 // ── layout: saved per user (GET/PUT /me/dashboards), default otherwise; works for the session without persistence32 const dashboards = useApiQuery("/me/dashboards", undefined, { staleTime: 60_000 });33 const saved = useMemo(() => {34 const d = dashboards.data?.items.find((x) => x.name === DASHBOARD_NAME);35 const layout = d ? sanitizeLayout(d.layout) : [];36 return layout.length > 0 ? layout : null;37 }, [dashboards.data]);38 const [local, setLocal] = useState<Widget[] | null>(null); // last layout applied in this page (saved or not)39 const [draft, setDraft] = useState<Widget[] | null>(null); // edit mode40 const [saving, setSaving] = useState(false);41 const [confirmReset, setConfirmReset] = useState(false);42 const [message, setMessage] = useState("");43 const base = useMemo(() => local ?? saved ?? defaultLayout(), [local, saved]);44 const layout = draft ?? base;45 const editing = draft !== null;46 const persistable = dashboards.isSuccess;47 const customised = saved !== null || local !== null;4849 const persist = async (next: Widget[], quiet = false): Promise<void> => {50 setLocal(next);51 if (!persistable) {52 if (!quiet) toast({ tone: "info", title: t("overview.edit.sessionOnly") });53 return;54 }55 setSaving(true);56 try {57 await apiPut("/me/dashboards/{name}", { path: { name: DASHBOARD_NAME }, body: { layout: next } });58 await invalidatePaths(qc, "/me/dashboards");59 if (!quiet) toast({ tone: "ok", title: t("overview.edit.saved") });60 } catch (e) {61 toast({ tone: "critical", ...explain(e) });62 } finally {63 setSaving(false);64 }65 };6667 const finish = async () => {68 if (!draft) return;69 const next = draft;70 setDraft(null);71 if (!sameLayout(next, base)) await persist(next);72 setMessage(t("overview.edit.done"));73 };74 const reset = async () => {75 setSaving(true);76 try {77 if (persistable) {78 try {79 await apiDelete("/me/dashboards/{name}", { path: { name: DASHBOARD_NAME } });80 } catch (e) {81 if (!(e instanceof ApiError && e.status === 404)) throw e; // nothing saved yet is fine82 }83 await invalidatePaths(qc, "/me/dashboards");84 }85 setLocal(null);86 setDraft(null);87 setConfirmReset(false);88 toast({ tone: "ok", title: t("overview.edit.resetDone") });89 } catch (e) {90 toast({ tone: "critical", ...explain(e) });91 } finally {92 setSaving(false);93 }94 };95 const onConfig = (id: string, config: Record<string, unknown>) => {96 if (draft) setDraft(setConfig(draft, id, config));97 else void persist(setConfig(base, id, config), true);98 };99100 const addable = addableTypes(layout);101 return (102 <Page103 title={t("overview.title")}104 sub={t("overview.sub")}105 actions={106 editing ? (107 <>108 <Menu109 label={t("overview.edit.add")}110 align="right"111 items={addable.length > 0 ? addable.map((type) => ({ id: type, label: widgetTypeLabel(t, type), icon: WIDGET_ICON[type], onSelect: () => { setDraft(addWidget(layout, type)); setMessage(t("overview.edit.added", { title: widgetTypeLabel(t, type) })); } })) : [{ id: "none", label: t("overview.edit.nothingToAdd"), disabled: true }]}112 trigger={(p) => <button {...p} type="button" className="mcc-btn" data-testid="ov-add">{t("overview.edit.add")}</button>}113 />114 <Button onClick={() => setConfirmReset(true)} disabled={saving} data-testid="ov-reset">{t("overview.edit.reset")}</Button>115 <Button onClick={() => { setDraft(null); setMessage(t("overview.edit.cancelled")); }} disabled={saving}>{t("common.cancel")}</Button>116 <Button variant="primary" icon="check" onClick={() => void finish()} loading={saving} data-testid="ov-save">{t("common.save")}</Button>117 </>118 ) : (119 <>120 <Button icon={compact ? "expand" : "collapse"} aria-pressed={compact} onClick={() => setCompactPref(compact ? "0" : "1")} data-testid="ov-compact">{t("overview.compact")}</Button>121 <Button icon="edit" onClick={() => setDraft([...base])} data-testid="ov-customize">{t("overview.edit.start")}</Button>122 <LinkButton href="/ops" icon="monitor">{t("overview.opsMode")}</LinkButton>123 </>124 )125 }126 >127 <div className="stack" data-testid="screen-overview" data-editing={editing} data-compact={compact} data-persistable={persistable}>128 {editing ? (129 <Banner tone="info" icon="edit">130 <span id="ov-edit-help">{t("overview.edit.help")}</span>131 {!persistable ? <> <strong data-testid="ov-no-persist">{dashboards.isError && dashboards.error.notImplemented ? t("overview.edit.noPersistNotAvailable") : t("overview.edit.noPersist")}</strong></> : null}132 </Banner>133 ) : null}134 <p className="sr-only" role="status" aria-live="polite" data-testid="ov-live">{message}</p>135 {layout.length === 0 ? <EmptyState icon="grid" title={t("overview.empty.title")} actions={editing ? undefined : <Button icon="edit" onClick={() => setDraft([])}>{t("overview.edit.start")}</Button>}>{t("overview.empty.body")}</EmptyState> : null}136 <Grid137 layout={layout}138 editing={editing}139 compact={compact}140 onLayout={(next) => setDraft(next)}141 onRemove={(id) => { setDraft(removeWidget(layout, id)); setMessage(t("overview.edit.removed")); }}142 onConfig={onConfig}143 announce={setMessage}144 />145 {!editing && customised ? <p className="mcc-hint">{persistable ? t("overview.customised") : t("overview.customisedSession")}</p> : null}146 </div>147 <ConfirmDialog open={confirmReset} onClose={() => setConfirmReset(false)} onConfirm={() => void reset()} busy={saving} danger title={t("overview.edit.resetTitle")} body={t("overview.edit.resetBody")} confirmLabel={t("overview.edit.reset")} />148 </Page>149 );150}151