SPB Git

Repository Public

AppShell.tsx 14.6 KB 300 lines tsx

1"use client";2import Link from "next/link";3import { usePathname, useRouter } from "next/navigation";4import { useEffect, useState, type ReactNode } from "react";5import { useApiQuery } from "@/api/query";6import { useI18n, type Locale } from "@/i18n";7import { Badge, Banner, Button, Count, DateTimeRangePicker, Dialog, ErrorState, Icon, IconButton, Kbd, Menu, Skeleton, StateDot, cx, type MenuItem } from "@/ui";8import { ActionFlowProvider } from "@/features/actions/ActionFlow";9import { CommandPalette } from "./CommandPalette";10import { NAV, isActive, type NavItem } from "./nav";11import { usePeriodControl } from "./period";12import { useLastEvent, useRealtimeStatus } from "./realtime";13import { useSession } from "./session";14import { useTheme } from "./theme";15import { apiPatch } from "@/api/client";1617function Brand() {18  const { t } = useI18n();19  return (20    <Link href="/" className="app-brand">21      <svg className="mark" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden="true">22        <rect x="3" y="3" width="7.5" height="7.5" rx="1.5" /><rect x="13.5" y="3" width="7.5" height="7.5" rx="1.5" /><rect x="3" y="13.5" width="7.5" height="7.5" rx="1.5" /><path d="M13.5 17.25h7.5M17.25 13.5V21" />23      </svg>24      <span>MacLustr <small>Command Center</small><span className="sr-only"> — {t("shell.home")}</span></span>25    </Link>26  );27}2829const GROUPS: NavItem["group"][] = ["observe", "operate", "govern"];3031function NavList({ items, onNavigate }: { items: readonly NavItem[]; onNavigate?: () => void }) {32  const { t } = useI18n();33  const pathname = usePathname();34  return (35    <nav className="app-nav" aria-label={t("shell.mainNav")}>36      {GROUPS.map((g) => {37        const list = items.filter((i) => i.group === g);38        if (list.length === 0) return null;39        return (40          <div key={g}>41            <div className="caps" aria-hidden="true">{t(`shell.group.${g}`)}</div>42            <ul>43              {list.map((i) => (44                <li key={i.href}>45                  <Link href={i.href} className="nav-link" aria-current={isActive(pathname, i.href) ? "page" : undefined} onClick={onNavigate} data-nav={i.href}>46                    <Icon name={i.icon} size={16} />47                    {t(i.key)}48                  </Link>49                </li>50              ))}51            </ul>52          </div>53        );54      })}55    </nav>56  );57}5859function ConnectionIndicator() {60  const { t, fmt } = useI18n();61  const s = useRealtimeStatus();62  const last = useLastEvent();63  const tone = s.state === "live" ? "ok" : s.state === "offline" ? "critical" : s.state === "closed" ? "offline" : "warning";64  const text =65    s.state === "live" ? t("shell.conn.live")66    : s.state === "connecting" ? t("shell.conn.connecting")67    : s.state === "reconnecting" ? t("shell.conn.reconnecting")68    : s.state === "offline" ? t("shell.conn.offlineSince", { time: fmt.time(s.since) })69    : t("shell.conn.closed");70  return (71    <span className={cx("conn", `tone-${tone}`)} data-state={s.state} data-testid="connection-indicator" data-last-event-id={last?.id ?? ""} data-last-event-topic={last?.topic ?? ""} role="status" aria-label={`${t("shell.conn.label")}: ${text}`}72      title={last ? t("shell.conn.lastEvent", { time: fmt.time(last.at), topic: last.topic }) : t("shell.conn.help")}>73      {s.state === "live" ? <span className="pulse" aria-hidden="true" /> : <Icon name={s.state === "offline" || s.state === "closed" ? "offline" : "refresh"} size={13} className={s.state === "reconnecting" || s.state === "connecting" ? "mcc-spin" : undefined} />}74      <span className="text">{text}</span>75    </span>76  );77}7879function ClusterState() {80  const { t } = useI18n();81  const { can } = useSession();82  const q = useApiQuery("/cluster/overview", undefined, { enabled: can("cluster.read"), refetchInterval: 30_000 });83  if (!can("cluster.read")) return null;84  if (q.data) {85    const n = q.data.nodes;86    const a = q.data.alerts;87    const worst = n.offline > 0 || (a?.critical ?? 0) > 0 ? "critical" : n.stale > 0 || (a?.warning ?? 0) > 0 ? "warning" : "ok";88    return (89      <div className="cluster" data-testid="cluster-state">90        <Link href="/" title={t("shell.cluster.title")}>91          <StateDot tone={worst} label={t(`shell.cluster.${worst}`)} />92          <span className="counts muted num">{t("shell.cluster.nodes", { fresh: n.fresh, total: n.total })}</span>93          {n.stale > 0 ? <span className="optional"><StateDot tone="stale" label={t("shell.cluster.stale", { count: n.stale })} subtle /></span> : null}94          {n.offline > 0 ? <span className="optional"><StateDot tone="offline" label={t("shell.cluster.offline", { count: n.offline })} subtle /></span> : null}95          {n.maintenance > 0 ? <span className="optional"><StateDot tone="maintenance" label={t("shell.cluster.maintenance", { count: n.maintenance })} subtle /></span> : null}96        </Link>97      </div>98    );99  }100  if (q.isError) {101    return <div className="cluster" data-testid="cluster-state"><StateDot tone="neutral" label={q.error.notImplemented ? t("shell.cluster.notAvailable") : t("shell.cluster.unknown")} subtle /></div>;102  }103  return <div className="cluster"><Skeleton width="40" /></div>;104}105106function Notifications() {107  const { t, fmt } = useI18n();108  const { can } = useSession();109  const [open, setOpen] = useState(false);110  const q = useApiQuery("/alerts", { query: { state: "firing", limit: 20 } }, { enabled: can("alerts.read"), refetchInterval: 60_000 });111  if (!can("alerts.read")) return null;112  const items = q.data?.items ?? [];113  const critical = items.some((a) => a.severity === "critical");114  return (115    <span className="mcc-pop-anchor bell" onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOpen(false); }} onKeyDown={(e) => { if (e.key === "Escape") setOpen(false); }}>116      <IconButton icon="alerts" label={items.length > 0 ? t("shell.notif.labelCount", { count: items.length }) : t("shell.notif.label")} aria-expanded={open} onClick={() => setOpen((o) => !o)} tip={false} />117      {items.length > 0 ? <Count value={items.length} tone={critical ? "critical" : "warning"} /> : null}118      {open ? (119        <div className="mcc-pop right" role="dialog" aria-label={t("shell.notif.label")}>120          <div className="mcc-menu-label caps">{t("shell.notif.firing")}</div>121          {q.isError ? <ErrorState error={q.error} compact /> : items.length === 0 ? <p className="mcc-menu-label muted">{q.isLoading ? t("common.loading") : t("shell.notif.none")}</p> : (122            <ul className="notif-list">123              {items.map((a) => (124                <li key={a.id}>125                  <Link href={`/alerts/${a.id}`} onClick={() => setOpen(false)}>126                    <span className="row"><Badge tone={a.severity === "critical" ? "critical" : a.severity === "warning" ? "warning" : "info"}>{t(`states.severity.${a.severity}`)}</Badge><span className="truncate">{a.rule_name}</span></span>127                    <span className="muted truncate">{a.node_alias ? `${a.node_alias} · ` : ""}{a.summary}</span>128                    <span className="faint num">{fmt.relative(a.fired_at ?? a.started_at)}</span>129                  </Link>130                </li>131              ))}132            </ul>133          )}134          <div className="mcc-menu-sep" />135          <Link className="mcc-menu-item" href="/alerts" onClick={() => setOpen(false)}>{t("shell.notif.all")}</Link>136        </div>137      ) : null}138    </span>139  );140}141142function AccountMenu() {143  const { t, locale, setLocale } = useI18n();144  const { me, signOut, refresh } = useSession();145  const { theme, setTheme } = useTheme();146  const router = useRouter();147  if (!me) return null;148  const initials = me.user.display_name.split(/\s+/).map((p) => p[0] ?? "").join("").slice(0, 2).toUpperCase() || "?";149  const switchLocale = async (l: Locale) => {150    setLocale(l);151    try {152      await apiPatch("/me", { body: { locale: l } });153      await refresh();154    } catch {155      /* the preview stays; the settings page reports persistence errors */156    }157  };158  const items: MenuItem[] = [159    { id: "profile", label: t("shell.account.profile"), icon: "user", onSelect: () => router.push("/settings") },160    { id: "security", label: t("shell.account.security"), icon: "passkey", onSelect: () => router.push("/settings/security") },161    { id: "lang", label: locale === "fr" ? t("shell.account.toEnglish") : t("shell.account.toFrench"), icon: "globe", onSelect: () => void switchLocale(locale === "fr" ? "en" : "fr"), separatorBefore: true },162    { id: "theme", label: theme === "dark" ? t("shell.account.toLight") : t("shell.account.toDark"), icon: theme === "dark" ? "sun" : "moon", onSelect: () => setTheme(theme === "dark" ? "light" : "dark") },163    { id: "signout", label: t("shell.account.signOut"), icon: "logout", onSelect: () => void signOut(), separatorBefore: true },164  ];165  return (166    <Menu167      label={t("shell.account.label", { name: me.user.display_name })}168      items={items}169      header={<div className="account-head"><strong>{me.user.display_name}</strong><span className="muted mono">@{me.user.handle}</span><span className="faint">{t(`states.role.${me.user.role}`)}</span></div>}170      trigger={({ "aria-label": name, ...p }) => (171        // the name is carried by hidden text, not aria-label: the visible initials must not contradict the accessible name172        <button {...p} type="button" className="mcc-btn mcc-btn-ghost mcc-btn-icon" data-testid="account-menu">173          <span className="avatar" aria-hidden="true">{initials}</span>174          <span className="sr-only">{name}</span>175        </button>176      )}177    />178  );179}180181function PeriodSlot() {182  const { value, setValue, users } = usePeriodControl();183  if (users <= 0) return null;184  return <div className="period-slot"><DateTimeRangePicker value={value} onChange={setValue} /></div>;185}186187/** `bare`: authenticated frame without navigation chrome (operations-centre mode). */188export function AppShell({ children, bare }: { children: ReactNode; bare?: boolean }) {189  const { t } = useI18n();190  const session = useSession();191  const router = useRouter();192  const pathname = usePathname();193  const rt = useRealtimeStatus();194  const [palette, setPalette] = useState(false);195  const [more, setMore] = useState(false);196197  useEffect(() => {198    if (session.status === "anonymous") {199      const next = pathname && pathname !== "/" ? `?next=${encodeURIComponent(pathname)}` : "";200      router.replace(`/signin${next}`);201    }202  }, [session.status, pathname, router]);203204  useEffect(() => {205    const onKey = (e: KeyboardEvent) => {206      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {207        e.preventDefault();208        setPalette((o) => !o);209      }210    };211    window.addEventListener("keydown", onKey);212    return () => window.removeEventListener("keydown", onKey);213  }, []);214215  if (session.status === "error") {216    return <main className="public-main"><div className="public-card"><ErrorState error={session.error} onRetry={() => void session.refresh()} /></div></main>;217  }218  if (session.status !== "authenticated" || !session.me) {219    return <main className="public-main" aria-busy="true"><div className="public-card" role="status" aria-label={t("common.loading")}><Skeleton width="40" height="lg" /><Skeleton width="80" /><Skeleton width="60" /></div></main>;220  }221222  if (bare) return <ActionFlowProvider><main id="main" className="app-bare">{children}</main></ActionFlowProvider>;223224  const items = NAV.filter((i) => !i.permission || session.can(i.permission));225  const bottom = ["/", "/nodes", "/alerts", "/maintenance"].map((h) => items.find((i) => i.href === h)).filter((i): i is NavItem => !!i);226227  return (228    <ActionFlowProvider>229    <div className="app">230      <a href="#main" className="skip-link">{t("shell.skip")}</a>231      <aside className="app-side">232        <Brand />233        <NavList items={items} />234        <div className="app-side-foot mono">clustr.spboucher.ai</div>235      </aside>236      <header className="app-top">237        <ClusterState />238        <span className="spacer" />239        <PeriodSlot />240        <button type="button" className="search-trigger" onClick={() => setPalette(true)} title={t("shell.search.open")} aria-keyshortcuts="Meta+K Control+K" data-testid="search-trigger">241          <Icon name="search" size={15} />242          <span className="grow">{t("shell.search.placeholder")}</span>243          <Kbd>⌘K</Kbd>244        </button>245        <ConnectionIndicator />246        <Notifications />247        <AccountMenu />248      </header>249      <main id="main" className="app-main" tabIndex={-1}>250        {rt.state === "offline" ? <div className="offline-banner"><Banner tone="warning" icon="offline" role="alert">{t("shell.offlineBanner")}</Banner></div> : null}251        {children}252      </main>253      <nav className="app-bottom" aria-label={t("shell.bottomNav")}>254        {bottom.map((i) => (255          <Link key={i.href} href={i.href} aria-current={isActive(pathname, i.href) ? "page" : undefined}><Icon name={i.icon} size={20} />{t(i.key)}</Link>256        ))}257        <button type="button" onClick={() => setMore(true)} aria-haspopup="dialog"><Icon name="menu" size={20} />{t("shell.more")}</button>258      </nav>259      <Dialog open={more} onClose={() => setMore(false)} title={t("shell.mainNav")} variant="drawer" footer={<Button onClick={() => setMore(false)}>{t("common.close")}</Button>}>260        <NavList items={items} onNavigate={() => setMore(false)} />261      </Dialog>262      <CommandPalette open={palette} onClose={() => setPalette(false)} />263    </div>264    </ActionFlowProvider>265  );266}267268/** Page-level permission gate: explains the 403 with the missing permission instead of rendering a broken screen. */269export function RequirePermission({ permission, children }: { permission: string; children: ReactNode }) {270  const { can } = useSession();271  const { t } = useI18n();272  if (can(permission)) return <>{children}</>;273  return (274    <div className="page">275      <div className="mcc-statebox tone-offline" role="alert">276        <span className="icon"><Icon name="denied" size={17} /></span>277        <h1>{t("errors.forbidden.title")}</h1>278        <p data-testid="forbidden">{t("errors.forbidden.bodyPermission", { permission })}</p>279        <p>{t("errors.forbidden.askAdmin")}</p>280      </div>281    </div>282  );283}284285/** Standard page frame: h1, optional description and actions. */286export function Page({ title, sub, actions, children }: { title: string; sub?: ReactNode; actions?: ReactNode; children: ReactNode }) {287  useEffect(() => {288    document.title = `${title} · MacLustr Command Center`;289  }, [title]);290  return (291    <div className="page">292      <div className="page-head">293        <div><h1>{title}</h1>{sub ? <div className="sub">{sub}</div> : null}</div>294        {actions ? <div className="toolbar">{actions}</div> : null}295      </div>296      {children}297    </div>298  );299}300
Files main
Menu

Theme