diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts new file mode 100644 index 000000000..84ae4ed2a --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/links.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from "vitest" +import type { MouseEvent } from "react" +import { navigatesThisTab } from "./links.ts" + +function click(overrides: Partial = {}): MouseEvent { + return { + button: 0, + metaKey: false, + altKey: false, + ctrlKey: false, + shiftKey: false, + ...overrides, + } as MouseEvent +} + +describe("navigatesThisTab", () => { + it("accepts a plain primary click", () => { + expect(navigatesThisTab(click())).toBe(true) + }) + + // Each of these hands the navigation to a new tab or window, so the tab the + // click happened in keeps whatever tenant it was showing. + it.each(["metaKey", "ctrlKey", "shiftKey", "altKey"] as const)( + "refuses a click modified with %s", + (modifier) => { + expect(navigatesThisTab(click({ [modifier]: true }))).toBe(false) + }, + ) + + it("refuses a non-primary button", () => { + expect(navigatesThisTab(click({ button: 1 }))).toBe(false) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/links.ts b/packages/system/dashboard/images/console/apps/console/src/lib/links.ts new file mode 100644 index 000000000..c6dc28599 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/links.ts @@ -0,0 +1,13 @@ +import type { MouseEvent } from "react" + +/** + * Whether a click on an anchor will navigate the tab it happened in, rather + * than open a new tab or window. React runs `onClick` either way, and a + * cross-tenant link's handler aligns the tenant context of the tab it is + * leaving — which is wrong when that tab is staying where it is. Same button + * and modifier test react-router's own `Link` applies before it intercepts a + * click, minus the `target` check these links have no attribute for. + */ +export function navigatesThisTab(e: MouseEvent): boolean { + return e.button === 0 && !e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey +} diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts new file mode 100644 index 000000000..bf48ae03c --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from "vitest" +import type { TenantNamespace } from "@cozystack/types" +import { realParentNamespace } from "./tenant-tree.ts" + +function tn(name: string, ancestors: string[]): TenantNamespace { + const labels: Record = {} + for (const a of [...ancestors, name]) labels[`tenant.cozystack.io/${a}`] = "" + return { + apiVersion: "core.cozystack.io/v1alpha1", + kind: "TenantNamespace", + metadata: { name, labels }, + } as TenantNamespace +} + +describe("realParentNamespace", () => { + it("takes the deepest ancestor that prefixes the namespace", () => { + // The full chain is on the labels; only the longest prefix is the parent. + expect( + realParentNamespace( + tn("tenant-acme-eu-dev", ["tenant-root", "tenant-acme", "tenant-acme-eu"]), + ), + ).toBe("tenant-acme-eu") + }) + + it("names an inaccessible parent, which is the point of asking", () => { + // Visibility is the caller's problem: the CR of a bridged row lives in a + // namespace the user may not read, and the caller has to be able to tell. + expect( + realParentNamespace(tn("tenant-acme-eu", ["tenant-root", "tenant-acme"])), + ).toBe("tenant-acme") + }) + + it("resolves a tenant ordered directly in the root", () => { + // A tenant `acme` created in `tenant-root` owns `tenant-acme`, not + // `tenant-root-acme`, so the prefix rule alone leaves every top-level + // tenant — most tenants on a normal cluster — looking parentless. + expect(realParentNamespace(tn("tenant-acme", ["tenant-root"]))).toBe( + "tenant-root", + ) + }) + + it("does not mistake a root-level name that starts with root", () => { + // `tenant-root-x` is the tenant `root-x` ordered in the root, and the + // prefix branch answers with the same parent the label does. + expect(realParentNamespace(tn("tenant-root-x", ["tenant-root"]))).toBe( + "tenant-root", + ) + }) + + it("has no parent for the hierarchy root", () => { + expect(realParentNamespace(tn("tenant-root", []))).toBeUndefined() + }) + + it("has no parent when the ancestor labels are gone", () => { + // A TenantNamespace carrying only its own label is either the root or + // mislabelled; either way there is no CR namespace to derive. + expect(realParentNamespace(tn("tenant-acme", []))).toBeUndefined() + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts index a8f474bf9..8f16b583d 100644 --- a/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts +++ b/packages/system/dashboard/images/console/apps/console/src/lib/tenant-tree.ts @@ -1,4 +1,5 @@ import type { TenantNamespace } from "@cozystack/types" +import { ROOT_TENANT_NAMESPACE } from "./constants.ts" import { tenantDisplayName } from "./tenant-context.tsx" const ANCESTOR_LABEL_PREFIX = "tenant.cozystack.io/" @@ -76,11 +77,18 @@ export function flattenTenantForest( /** * Row label relative to the visible parent: `tenant-whmcs-crpjxhwm` under * `tenant-whmcs` shows as `crpjxhwm`. Forest roots keep their full display - * name — there is no parent on screen to be relative to. + * name — there is no parent on screen to be relative to, and neither do the + * root's own children, whose namespace never carries the parent's name: under + * `tenant-root` the tenant `root-x` owns `tenant-root-x`, and stripping the + * prefix there would label it `x` while its CR is `root-x`. */ export function relativeTenantName(node: TenantTreeNode): string { const ns = node.tn.metadata.name - if (node.parentNs && ns.startsWith(`${node.parentNs}-`)) { + if ( + node.parentNs && + node.parentNs !== ROOT_TENANT_NAMESPACE && + ns.startsWith(`${node.parentNs}-`) + ) { return ns.slice(node.parentNs.length + 1) } return tenantDisplayName(node.tn) @@ -96,7 +104,16 @@ export function relativeTenantName(node: TenantTreeNode): string { */ export function realParentNamespace(tn: TenantNamespace): string | undefined { const ns = tn.metadata.name - return ancestorNamespaces(tn) + const ancestors = ancestorNamespaces(tn) + const nested = ancestors .filter((ancestor) => ns.startsWith(`${ancestor}-`)) .sort((a, b) => b.length - a.length)[0] + if (nested) return nested + // The root is the one level the naming rule skips: a tenant `x` ordered in + // `tenant-root` owns `tenant-x`, not `tenant-root-x`, so the prefix test + // never matches and every top-level tenant — most tenants on a normal + // cluster — looked parentless. The ancestor labels still say otherwise. + return ancestors.includes(ROOT_TENANT_NAMESPACE) + ? ROOT_TENANT_NAMESPACE + : undefined } diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx index 035b10fe1..fe2864829 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.test.tsx @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeAll } from "vitest" -import { screen } from "@testing-library/react" +import { fireEvent, screen } from "@testing-library/react" import userEvent from "@testing-library/user-event" +import { useLocation } from "react-router" import { K8sClient, type K8sList, @@ -8,6 +9,7 @@ import { } from "@cozystack/k8s-client" import { TenantsPage } from "./TenantsPage.tsx" import { TenantProvider } from "../lib/tenant-provider.tsx" +import { useTenantContext } from "../lib/tenant-context.tsx" import { SELECTED_TENANT_KEY } from "../lib/constants.ts" import { renderWithK8sProvider } from "../test-utils/render.tsx" @@ -30,10 +32,19 @@ const VISIBLE = [ tn("tenant-whmcs-a-b", ["tenant-root", "tenant-whmcs", "tenant-whmcs-a"]), ] -function makeClient(): K8sClient { +function LocationProbe() { + const { pathname } = useLocation() + return
{pathname}
+} + +function SelectedTenant() { + return {useTenantContext().selectedTenant} +} + +function makeClient(tenants: unknown[] = VISIBLE): K8sClient { const client = new K8sClient() vi.spyOn(client, "list").mockImplementation(async (_g, _v, plural) => { - const items = plural === "tenantnamespaces" ? VISIBLE : [] + const items = plural === "tenantnamespaces" ? tenants : [] return { apiVersion: "v1", kind: `${plural}List`, @@ -89,6 +100,12 @@ describe("TenantsPage tree", () => { expect(editButtons).toHaveLength(1) expect(screen.getByTitle("Edit tenant whmcs-x")).toBeInTheDocument() expect(screen.queryByTitle("Edit tenant whmcs-a-b")).not.toBeInTheDocument() + + // The name links to the detail page, where Delete is, exactly where Edit is + // offered: a row whose CR namespace cannot be read stays plain text. + expect(screen.getByRole("link", { name: "x" })).toHaveAttribute("href", "/admin/tenants/x") + expect(screen.queryByRole("link", { name: "a-b" })).toBeNull() + expect(screen.queryByRole("link", { name: "whmcs" })).toBeNull() }) it("collapses a subtree via the row toggle", async () => { @@ -109,3 +126,131 @@ describe("TenantsPage tree", () => { expect(await screen.findByText("x")).toBeInTheDocument() }) }) + +// Tenants ordered directly in the root are the common case on a normal +// cluster, and they are the one level the hierarchical namespace naming skips: +// `acme` created in `tenant-root` owns `tenant-acme`, not `tenant-root-acme`. +const ROOT_VISIBLE = [ + tn("tenant-root", []), + tn("tenant-acme", ["tenant-root"]), + tn("tenant-acme-eu", ["tenant-root", "tenant-acme"]), + // A root-level tenant whose own name starts with `root`, which is the case + // that makes "strip the parent's prefix" the wrong rule rather than merely + // an incomplete one. + tn("tenant-root-x", ["tenant-root"]), +] + +function renderTenants(tenants: unknown[], selected: string) { + localStorage.setItem(SELECTED_TENANT_KEY, selected) + renderWithK8sProvider( + + + + + , + { client: makeClient(tenants), initialRoute: "/admin/tenants" }, + ) +} + +describe("TenantsPage under a visible root", () => { + it("offers Edit on a tenant ordered directly in the root", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/acme/edit") + }) + + it("names a nested tenant's CR relative to its parent", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme-eu")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/eu/edit") + }) + + // `tenant-root-x` is the tenant `root-x`, not the tenant `x`: the row label + // and the CR the row opens have to agree on that. + it("keeps a root-level tenant named root-x whole", async () => { + renderTenants(ROOT_VISIBLE, "root") + + expect(await screen.findByText("root-x")).toBeInTheDocument() + await userEvent.click(screen.getByTitle("Edit tenant root-x")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/root-x/edit") + }) +}) + +// A forest root that carries no ancestor labels is self-referential: its CR +// lives in its own namespace, and deriving the CR name must not subtract the +// node's own name from itself and leave nothing. +describe("TenantsPage self-referential root", () => { + it("names the CR of a root that is not tenant-root", async () => { + renderTenants([tn("tenant-whmcs", [])], "whmcs") + + await userEvent.click(await screen.findByTitle("Edit tenant whmcs")) + + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/whmcs/edit") + }) +}) + +describe("TenantsPage row link", () => { + it("links every row whose Tenant CR it can name", async () => { + renderTenants(ROOT_VISIBLE, "root") + + // The root's CR is self-referential: `root` inside its own namespace. + expect(await screen.findByRole("link", { name: "root" })).toHaveAttribute( + "href", + "/admin/tenants/root", + ) + expect(screen.getByRole("link", { name: "acme" })).toHaveAttribute("href", "/admin/tenants/acme") + expect(screen.getByRole("link", { name: "eu" })).toHaveAttribute("href", "/admin/tenants/eu") + expect(screen.getByRole("link", { name: "root-x" })).toHaveAttribute( + "href", + "/admin/tenants/root-x", + ) + }) + + it("links a self-referential root to its own CR", async () => { + renderTenants([tn("tenant-whmcs", [])], "whmcs") + + expect(await screen.findByRole("link", { name: "whmcs" })).toHaveAttribute( + "href", + "/admin/tenants/whmcs", + ) + }) + + // The detail page resolves `eu` in the selected tenant's namespace, and eu's + // CR lives in acme's, so the click has to land the tab on acme. + it("switches to the row's parent and opens the detail page", async () => { + renderTenants(ROOT_VISIBLE, "root") + + fireEvent.click(await screen.findByRole("link", { name: "eu" })) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("acme") + expect(screen.getByTestId("location")).toHaveTextContent("/admin/tenants/eu") + }) + + // Edit shares the route with the link, and its form resolves the CR the same + // way, so it has to land on the parent too. + it("switches to the row's parent before opening the edit form", async () => { + renderTenants(ROOT_VISIBLE, "root") + + await userEvent.click(await screen.findByTitle("Edit tenant acme-eu")) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("acme") + }) + + // A ctrl-click opens a new tab; the tab it happened in stays where it is. + it("leaves the current tab alone on a ctrl-click", async () => { + renderTenants(ROOT_VISIBLE, "root") + const link = await screen.findByRole("link", { name: "eu" }) + // jsdom cannot open the new tab; the handler under test has run by then. + link.addEventListener("click", (e) => e.preventDefault()) + + fireEvent.click(link, { ctrlKey: true }) + + expect(screen.getByTestId("selected-tenant").textContent).toBe("root") + expect(screen.getByTestId("location")).toHaveTextContent(/^\/admin\/tenants$/) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx index 2366ee320..3944467f4 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/TenantsPage.tsx @@ -1,5 +1,5 @@ import { useMemo, useState } from "react" -import { useNavigate } from "react-router" +import { Link, useNavigate } from "react-router" import { Plus, Edit, Info, ChevronDown, ChevronRight, CornerDownRight } from "lucide-react" import { Spinner, Section, Button } from "@cozystack/ui" import { useK8sList } from "@cozystack/k8s-client" @@ -13,7 +13,8 @@ import { relativeTenantName, type TenantTreeNode, } from "../lib/tenant-tree.ts" -import { TENANT_NAMESPACE_PREFIX } from "../lib/constants.ts" +import { ROOT_TENANT_NAMESPACE, TENANT_NAMESPACE_PREFIX } from "../lib/constants.ts" +import { navigatesThisTab } from "../lib/links.ts" import { formatAge } from "../lib/status.ts" import { TenantQuotaCompact } from "../components/QuotaDisplay.tsx" import type { ResourceQuota } from "../components/QuotaDisplay.tsx" @@ -34,11 +35,17 @@ type TreeNode = TenantTreeNode /** * The Tenant CR of a namespace lives in its parent's namespace under the * short name: `tenant-whmcs-jzmnbwum` under `tenant-whmcs` is CR `jzmnbwum`. - * Root-level children (`tenant-kvaps` under `tenant-root`) collapse to the - * same rule via the plain `tenant-` prefix strip. + * Under the root the naming rule drops a level — a tenant `kvaps` ordered in + * `tenant-root` owns `tenant-kvaps` — so there the CR name is the plain + * prefix strip, which also names the root's own self-referential CR (`root`). + * Excluding the root from the prefix branch rather than dropping the branch + * keeps two things right at once: a root-level tenant called `root-x` + * resolves to the CR `root-x` and not `x`, and a self-referential node whose + * namespace is not `tenant-root` still names itself instead of the empty + * string that subtracting its own name would leave. */ function tenantCrName(ns: string, parentNs: string): string { - return ns.startsWith(`${parentNs}-`) + return parentNs !== ROOT_TENANT_NAMESPACE && ns.startsWith(`${parentNs}-`) ? ns.slice(parentNs.length + 1) : ns.slice(TENANT_NAMESPACE_PREFIX.length) } @@ -125,8 +132,8 @@ export function TenantsPage() { // A node's Tenant CR lives in its REAL parent's namespace, which is not // necessarily the parent it hangs under: a node whose real parent is // inaccessible is bridged onto the nearest visible ancestor. Deriving the CR - // from that bridged ancestor names a CR that does not exist, so the edit - // target comes from realParentNamespace instead — and is offered only when + // from that bridged ancestor names a CR that does not exist, so Tenant CR + // routes come from realParentNamespace instead — and are offered only when // that namespace is actually readable, since otherwise there is no CR the // user could open. The hierarchy root (no ancestor labels at all) is // self-referential: its CR (`root`) lives in its own namespace. @@ -137,12 +144,20 @@ export function TenantsPage() { const real = realParentNamespace(node.tn) return real && visibleNs.has(real) ? real : undefined } - const canEdit = (node: TreeNode) => !!editParentNs(node) - const editNode = (node: TreeNode) => { + const tenantRoute = (node: TreeNode) => { const parentNs = editParentNs(node) - if (!parentNs) return - selectTenant(parentNs.slice(TENANT_NAMESPACE_PREFIX.length)) - navigate(`${basePath}/tenants/${tenantCrName(node.tn.metadata.name, parentNs)}/edit`) + if (!parentNs) return undefined + return { + parentTenant: parentNs.slice(TENANT_NAMESPACE_PREFIX.length), + path: `${basePath}/tenants/${tenantCrName(node.tn.metadata.name, parentNs)}`, + } + } + const canEdit = (node: TreeNode) => !!tenantRoute(node) + const editNode = (node: TreeNode) => { + const route = tenantRoute(node) + if (!route) return + selectTenant(route.parentTenant) + navigate(`${route.path}/edit`) } return ( @@ -183,6 +198,7 @@ export function TenantsPage() { const modules = modulesByNamespace.get(ns) ?? [] const tenantQuotas = quotasByNamespace.get(ns) ?? [] const host = node.tn.metadata.labels?.[HOST_LABEL] + const route = tenantRoute(node) return ( @@ -207,9 +223,26 @@ export function TenantsPage() { ) : null}
-

- {relativeTenantName(node)} -

+ {route ? ( + { + if (!navigatesThisTab(e)) return + selectTenant(route.parentTenant) + }} + className="block truncate text-sm font-medium text-slate-900 hover:underline" + > + {relativeTenantName(node)} + + ) : ( +

+ {relativeTenantName(node)} +

+ )}

{ns}