From 51f6735f4cf937c1cd68adc02c60d43320c0325f Mon Sep 17 00:00:00 2001 From: Pier Francesco Ferrari Date: Wed, 18 Nov 2026 18:37:12 +0100 Subject: [PATCH 1/2] feat: redesign the resource details attributes and add a relationships tab The Attributes tab is a single flat list, led by id and type, with a fixed label column and right-aligned values. `relationships: { names, onSelect }` adds a Relationships tab: one row per relationship, telling a single relationship from a multiple one by its name. Sideloaded has-one relationships are read from the resource; any other is fetched when its row is expanded, ten records per page. `onSelect` makes each related record clickable, e.g. to open it in another details modal. PaginationInfo is translated and uses `aria-disabled`, so its buttons keep keyboard focus while a page loads. --- packages/app-elements/src/locales/en.ts | 10 + packages/app-elements/src/locales/it.ts | 10 + packages/app-elements/src/main.ts | 1 + .../ResourceAttributes.tsx | 155 +++--- .../ResourceDetailsContent.tsx | 33 +- .../ResourceRelationships.test.tsx | 384 +++++++++++++ .../ResourceRelationships.tsx | 521 ++++++++++++++++++ .../resources/ResourceDetailsModal/index.ts | 1 + .../useResourceDetailsModal.tsx | 9 +- .../useResourceList/PaginationInfo.tsx | 35 +- .../useResourceList/useResourceList.test.tsx | 44 +- packages/docs/src/mocks/data/relationships.js | 37 ++ packages/docs/src/mocks/handlers.js | 3 + .../useResourceDetailsModal.stories.tsx | 46 ++ 14 files changed, 1175 insertions(+), 114 deletions(-) create mode 100644 packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.test.tsx create mode 100644 packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.tsx create mode 100644 packages/docs/src/mocks/data/relationships.js diff --git a/packages/app-elements/src/locales/en.ts b/packages/app-elements/src/locales/en.ts index f3fdbb368..062f44767 100644 --- a/packages/app-elements/src/locales/en.ts +++ b/packages/app-elements/src/locales/en.ts @@ -288,6 +288,9 @@ const en = { not_authorized: "Not authorized", not_authorized_description: "You are not authorized to access this page.", not_handled: "Not handled", + pagination_range: "{{first}}-{{last}} of {{total}}", + previous_page: "Previous page", + next_page: "Next page", parcel_total: "Total", parcel_weight: "Weight", parcel_item: "{{count}} item", @@ -461,6 +464,13 @@ const en = { title: "Resource details", attributes: "Attributes", events: "Events", + relationships: "Relationships", + no_relationships: "This resource has no relationships.", + has_one: "Has one", + has_many: "Has many", + no_records: "No records.", + relationship_error: "Could not load these records.", + view_record: "View {{id}}", json: "Json", no_events: "No events found for this resource.", unknown_event: "Unknown event", diff --git a/packages/app-elements/src/locales/it.ts b/packages/app-elements/src/locales/it.ts index 04cdb27a7..c4c95e71d 100644 --- a/packages/app-elements/src/locales/it.ts +++ b/packages/app-elements/src/locales/it.ts @@ -60,6 +60,9 @@ const it: typeof en = { not_authorized_description: "Non sei autorizzato ad accedere a questa pagina.", not_handled: "Non gestito", + pagination_range: "{{first}}-{{last}} di {{total}}", + previous_page: "Pagina precedente", + next_page: "Pagina successiva", parcel_total: "Totale", parcel_weight: "Peso", parcel_item: "{{count}} prodotto", @@ -238,6 +241,13 @@ const it: typeof en = { title: "Dettagli risorsa", attributes: "Attributi", events: "Eventi", + relationships: "Relazioni", + no_relationships: "Questa risorsa non ha relazioni.", + has_one: "Singola", + has_many: "Multipla", + no_records: "Nessun record.", + relationship_error: "Impossibile caricare questi record.", + view_record: "Visualizza {{id}}", json: "Json", no_events: "Nessun evento trovato per questa risorsa.", unknown_event: "Evento sconosciuto", diff --git a/packages/app-elements/src/main.ts b/packages/app-elements/src/main.ts index 901e041a5..c8d28f611 100644 --- a/packages/app-elements/src/main.ts +++ b/packages/app-elements/src/main.ts @@ -422,6 +422,7 @@ export { ResourceDetailsTimelineItem, type ResourceDetailsTimelineItemProps, type ResourceDetailsTimelineProps, + type ResourceRelationshipsConfig, type UseResourceDetailsModalProps, type UseResourceDetailsModalReturn, useResourceDetailsModal, diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx index 371ea9b7e..e936fe035 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx @@ -1,75 +1,81 @@ import type { Resource } from "@commercelayer/sdk" +import cn from "classnames" import capitalize from "lodash-es/capitalize" import lowerCase from "lodash-es/lowerCase" -import { type FC, useState } from "react" +import { type FC, type ReactNode, useState } from "react" import type { JsonObject } from "type-fest" import { t } from "#providers/i18n" import { Button } from "#ui/atoms/Button" -import { Card } from "#ui/atoms/Card" import { CodeBlock } from "#ui/atoms/CodeBlock" import { Icon } from "#ui/atoms/Icon" import { withSkeletonTemplate } from "#ui/atoms/SkeletonTemplate" -import { Spacer } from "#ui/atoms/Spacer" import { Text } from "#ui/atoms/Text" -import { ListItem } from "#ui/composite/ListItem" import { splitResourceFields } from "./resourceFields" /** - * Lists a resource's plain attributes. Relationships are filtered out: they - * are rendered by whoever owns that concern, so they don't leak into this list - * as raw JSON. + * Lists a resource's plain attributes as a single flat list, led by its id and + * type. Relationships are filtered out: they are rendered by whoever owns that + * concern, so they don't leak into this list as raw JSON. */ export const ResourceAttributes = withSkeletonTemplate<{ resource: Resource }>( ({ resource }) => { const { attributes } = splitResourceFields(resource) return ( - <> - - - - ID - - - - Type - - - - - - - {attributes.map((attribute, idx) => ( - - ))} - - +
+ + + + + + + {attributes.map((attribute) => ( + + ))} +
) }, ) -function capitalizeAttributeName(attribute: string): string { - return capitalize(lowerCase(attribute)) -} - -const AttributeLabel: FC<{ - attribute?: string - children?: React.ReactNode -}> = ({ attribute, children }) => ( - - {attribute != null ? capitalizeAttributeName(attribute) : children} - +/** + * A label on the left, its value right-aligned. Labels share a fixed width so + * values line up whatever the label length. + */ +const AttributeRow: FC<{ + label: string + hasBorder?: boolean + children: ReactNode +}> = ({ label, hasBorder = true, children }) => ( +
+ + {label} + +
{children}
+
) const AttributeValue: FC<{ value: unknown }> = ({ value }) => { if (value == null || value === "") { return ( - + — ) @@ -79,7 +85,7 @@ const AttributeValue: FC<{ value: unknown }> = ({ value }) => { {String(value)} @@ -89,44 +95,39 @@ const AttributeValue: FC<{ value: unknown }> = ({ value }) => { const AttributeItem = withSkeletonTemplate<{ attribute: string value: unknown - hasBorderBottom: boolean -}>(({ attribute, value, hasBorderBottom }) => { +}>(({ attribute, value }) => { const [showJson, setShowJson] = useState(false) - const isObjectValue = value != null && typeof value === "object" + const label = capitalize(lowerCase(attribute)) + + if (value == null || typeof value !== "object") { + return ( + + + + ) + } return ( <> - - - {isObjectValue ? ( - - ) : ( - - )} - - {showJson && isObjectValue && ( - + + + {showJson && ( +
{value as JsonObject} - +
)} ) diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx index 60350ee6b..9d426ca19 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx @@ -5,6 +5,10 @@ import { Spacer } from "#ui/atoms/Spacer" import { Tab, Tabs } from "#ui/atoms/Tabs" import { ResourceAttributes } from "./ResourceAttributes" import { ResourceEvents } from "./ResourceEvents" +import { + ResourceRelationships, + type ResourceRelationshipsConfig, +} from "./ResourceRelationships" export interface ResourceDetailsTab { /** Tab label. */ @@ -24,7 +28,13 @@ export interface ResourceDetailsContentProps { resource: Resource /** Renders skeletons while the caller is still loading the resource. */ isLoading?: boolean - /** Extra tabs, rendered between Attributes and Events. */ + /** + * Shows a Relationships tab right after Attributes. Has-one relationships + * the caller sideloaded are read from `resource`; any other is fetched only + * when its row is expanded. Leave it unset to hide the tab. + */ + relationships?: ResourceRelationshipsConfig + /** Extra tabs, rendered between Attributes (or Relationships) and Events. */ tabs?: ResourceDetailsTab[] /** * Fixed height for each tab panel, e.g. `"70vh"`. Set it when the surrounding @@ -42,8 +52,8 @@ export interface ResourceDetailsContentProps { } /** - * Tabbed view of a single resource: its attributes, any tabs the caller adds, - * and its event stream. + * Tabbed view of a single resource: its attributes, its relationships when + * asked for, any tabs the caller adds, and its event stream. * * Usable on its own inside a page, or wrapped in a modal via * `useResourceDetailsModal`. @@ -51,6 +61,7 @@ export interface ResourceDetailsContentProps { export const ResourceDetailsContent: FC = ({ resource, isLoading = false, + relationships, tabs = [], panelHeight, id, @@ -66,6 +77,22 @@ export const ResourceDetailsContent: FC = ({ , + ...(relationships != null + ? [ + + + + + , + ] + : []), + ...tabs.map((tab) => ( {tab.content(resource)} diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.test.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.test.tsx new file mode 100644 index 000000000..8578d759d --- /dev/null +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.test.tsx @@ -0,0 +1,384 @@ +import type { Resource } from "@commercelayer/sdk" +import { + act, + fireEvent, + type RenderResult, + render, +} from "@testing-library/react" +import { delay, HttpResponse, http } from "msw" +import type { ReactNode } from "react" +import { SWRConfig } from "swr" +import { CoreSdkProvider } from "#providers/CoreSdkProvider" +import { MockTokenProvider as TokenProvider } from "#providers/TokenProvider/MockTokenProvider" +import { server } from "../../../mocks/server" +import { + ResourceDetailsContent, + type ResourceDetailsContentProps, +} from "./ResourceDetailsContent" +import { isHasManyRelationship } from "./ResourceRelationships" + +/** + * Rendered without `I18NProvider`, so `t()` yields raw keys: assertions match + * record ids and labels, which are data, and relationship names, which are + * formatted locally. + */ +const resource = { + id: "NgojhKoyYN", + type: "orders", + status: "placed", + market: { id: "dvzXAuNQpm", type: "markets", name: "Europe" }, + customer: null, +} as unknown as Resource + +/** + * Every test gets its own SWR cache: the requests share their keys, so a + * cached page from an earlier test would otherwise be served without a fetch. + */ +const Providers = ({ children }: { children: ReactNode }) => ( + new Map() }}> + + {children} + + +) + +/** Serves `/orders/:id/line_items` and records every page requested. */ +function mockLineItems(): { requestedPages: string[] } { + const requestedPages: string[] = [] + server.use( + http.get(`https://*/api/:version/orders/:id/line_items`, ({ request }) => { + requestedPages.push( + new URL(request.url).searchParams.get("page[number]") ?? "1", + ) + return HttpResponse.json({ + data: [ + { + id: "kDrVYTkJDl", + type: "line_items", + attributes: { name: "Black T-shirt", sku_code: "TSHIRT" }, + }, + { id: "pWqzLbNmXa", type: "line_items", attributes: {} }, + ], + meta: { record_count: 2, page_count: 1 }, + }) + }), + ) + return { requestedPages } +} + +/** + * Serves `/orders/:id/line_items` as 12 records, ten per page, and records + * every `page/size` requested. + */ +function mockPagedLineItems(): { requestedPages: string[] } { + const requestedPages: string[] = [] + server.use( + http.get(`https://*/api/:version/orders/:id/line_items`, ({ request }) => { + const params = new URL(request.url).searchParams + const pageNumber = Number(params.get("page[number]") ?? "1") + const pageSize = Number(params.get("page[size]")) + requestedPages.push(`${pageNumber}/${pageSize}`) + const from = (pageNumber - 1) * pageSize + const to = Math.min(from + pageSize, 12) + return HttpResponse.json({ + data: Array.from({ length: to - from }, (_, index) => ({ + id: `lineItem${from + index}`, + type: "line_items", + attributes: {}, + })), + meta: { record_count: 12, page_count: 2 }, + }) + }), + ) + return { requestedPages } +} + +const setup = async ( + relationships: ResourceDetailsContentProps["relationships"], +): Promise => { + const result = await act(async () => + render( + + + , + ), + ) + + await act(async () => { + result.getAllByRole("tab")[1]?.click() + }) + + return result +} + +const expand = async (result: RenderResult, name: string): Promise => { + await act(async () => { + fireEvent.click(result.getByRole("button", { name: new RegExp(name) })) + }) +} + +describe("ResourceDetailsContent relationships", () => { + it("adds no Relationships tab unless asked to", async () => { + const { getAllByRole } = await act(async () => + render( + + + , + ), + ) + + expect(getAllByRole("tab")).toHaveLength(2) + }) + + it("renders the Relationships tab right after Attributes", async () => { + const { getAllByRole } = await setup({ names: ["market"] }) + + const tabs = getAllByRole("tab") + expect(tabs).toHaveLength(3) + expect(tabs[1]?.textContent).toBe("common.resource_details.relationships") + }) + + it("lists the relationships alphabetically", async () => { + const { getAllByRole } = await setup({ + names: ["market", "customer", "line_items"], + }) + + const rows = getAllByRole("button", { expanded: false }) + expect(rows.map((row) => row.textContent?.split("common")[0])).toEqual([ + "Customer", + "Line items", + "Market", + ]) + }) + + it("tells single relationships from multiple ones before loading them", async () => { + const { getByRole } = await setup({ names: ["market", "line_items"] }) + + expect(getByRole("button", { name: /^Market/ }).textContent).toContain( + "common.resource_details.has_one", + ) + expect(getByRole("button", { name: /^Line items/ }).textContent).toContain( + "common.resource_details.has_many", + ) + }) + + it("reads a sideloaded has-one from the payload, without fetching", async () => { + const { requestedPages } = mockLineItems() + const result = await setup({ names: ["market"] }) + + await expand(result, "Market") + + expect(result.getByText("dvzXAuNQpm")).toBeVisible() + expect(result.getByText("Europe")).toBeVisible() + expect(requestedPages).toEqual([]) + }) + + it("shows an empty has-one as having no records", async () => { + const result = await setup({ names: ["customer"] }) + + await expand(result, "Customer") + + expect(result.getByText("common.resource_details.no_records")).toBeVisible() + }) + + it("fetches a has-many only once its row is expanded", async () => { + const { requestedPages } = mockLineItems() + const result = await setup({ names: ["line_items"] }) + + expect(requestedPages).toEqual([]) + + await expand(result, "Line items") + + expect(await result.findByText("kDrVYTkJDl")).toBeVisible() + expect(result.getByText("Black T-shirt")).toBeVisible() + expect(requestedPages).toEqual(["1"]) + }) + + it("pages through a has-many ten records at a time", async () => { + const { requestedPages } = mockPagedLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + expect(await result.findByText("lineItem0")).toBeVisible() + expect(result.getByText("lineItem9")).toBeVisible() + expect(result.queryByText("lineItem10")).toBeNull() + expect(result.getByText("common.pagination_range")).toBeVisible() + + await act(async () => { + fireEvent.click(result.getByRole("button", { name: "common.next_page" })) + }) + + expect(await result.findByText("lineItem10")).toBeVisible() + expect(result.queryByText("lineItem0")).toBeNull() + expect(requestedPages).toEqual(["1/10", "2/10"]) + }) + + it("keeps keyboard focus on the pager while it turns pages", async () => { + mockPagedLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + await result.findByText("lineItem0") + const next = result.getByRole("button", { name: "common.next_page" }) + next.focus() + + await act(async () => { + fireEvent.click(next) + }) + await result.findByText("lineItem10") + + expect(next).toHaveFocus() + expect(next).toHaveAttribute("aria-disabled", "true") + }) + + it("exposes an expanded row as a region labelled by its button", async () => { + mockLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + + const button = result.getByRole("button", { name: /^Line items/ }) + const region = result.getByRole("region", { name: /^Line items/ }) + expect(button).toHaveAttribute("aria-controls", region.id) + }) + + it("announces the loading of a relationship", async () => { + server.use( + http.get(`https://*/api/:version/orders/:id/line_items`, async () => { + await delay(100) + return HttpResponse.json({ + data: [{ id: "kDrVYTkJDl", type: "line_items", attributes: {} }], + meta: { record_count: 1, page_count: 1 }, + }) + }), + ) + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + + expect(result.getByRole("status")).toHaveTextContent("common.loading") + expect(await result.findByText("kDrVYTkJDl")).toBeVisible() + expect(result.queryByRole("status")).toBeNull() + }) + + it("shows no pager when the records fit in one page", async () => { + mockLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + await result.findByText("kDrVYTkJDl") + + expect( + result.queryByRole("button", { name: "common.next_page" }), + ).toBeNull() + }) + + it("reopens a row on the page it was left on, without fetching it again", async () => { + const { requestedPages } = mockPagedLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + await result.findByText("lineItem0") + await act(async () => { + fireEvent.click(result.getByRole("button", { name: "common.next_page" })) + }) + await result.findByText("lineItem10") + await expand(result, "Line items") + await expand(result, "Line items") + + expect(result.getByText("lineItem10")).toBeVisible() + expect(requestedPages).toEqual(["1/10", "2/10"]) + }) + + it("keeps the fetched records when the row is collapsed and reopened", async () => { + const { requestedPages } = mockLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + await result.findByText("kDrVYTkJDl") + await expand(result, "Line items") + await expand(result, "Line items") + + expect(result.getByText("kDrVYTkJDl")).toBeVisible() + expect(requestedPages).toEqual(["1"]) + }) + + it("calls onSelect with the related record", async () => { + mockLineItems() + const onSelect = vi.fn() + const result = await setup({ names: ["line_items"], onSelect }) + + await expand(result, "Line items") + await result.findByText("kDrVYTkJDl") + + await act(async () => { + fireEvent.click( + result.getAllByRole("button", { + name: "common.resource_details.view_record", + })[0] as HTMLElement, + ) + }) + + expect(onSelect).toHaveBeenCalledWith({ + type: "line_items", + id: "kDrVYTkJDl", + }) + }) + + it("lists records without a clickable eye when onSelect is not given", async () => { + mockLineItems() + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + await result.findByText("kDrVYTkJDl") + + expect( + result.queryAllByRole("button", { + name: "common.resource_details.view_record", + }), + ).toHaveLength(0) + }) + + it("reports a relationship the SDK does not know, instead of an empty one", async () => { + const result = await setup({ names: ["not_a_relationship"] }) + + await expand(result, "Not a relationship") + + expect(await result.findByRole("alert")).toHaveTextContent( + "common.resource_details.relationship_error", + ) + }) + + it("reports a failed request inside the row", async () => { + server.use( + http.get(`https://*/api/:version/orders/:id/line_items`, () => + HttpResponse.json({ errors: [] }, { status: 500 }), + ), + ) + const result = await setup({ names: ["line_items"] }) + + await expand(result, "Line items") + + expect(await result.findByRole("alert")).toHaveTextContent( + "common.resource_details.relationship_error", + ) + }) +}) + +describe("isHasManyRelationship", () => { + it.each([ + ["line_items", true], + ["available_payment_methods", true], + ["skus", true], + ["available_free_skus", true], + ["market", false], + ["billing_address", false], + ["sku", false], + ["discount_engine_item", false], + ])("%s → %s", (name, expected) => { + expect(isHasManyRelationship(name)).toBe(expected) + }) +}) diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.tsx new file mode 100644 index 000000000..481b17225 --- /dev/null +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceRelationships.tsx @@ -0,0 +1,521 @@ +import type { + ListResponse, + QueryParamsList, + Resource, + ResourceTypeLock, +} from "@commercelayer/sdk" +import cn from "classnames" +import capitalize from "lodash-es/capitalize" +import lowerCase from "lodash-es/lowerCase" +import pluralize from "pluralize" +import { type FC, useId, useState } from "react" +import useSWR from "swr" +import { isMockedId } from "#helpers/mocks" +import { useCoreSdkProvider } from "#providers/CoreSdkProvider" +import { t } from "#providers/i18n" +import { Icon } from "#ui/atoms/Icon" +import { SkeletonTemplate } from "#ui/atoms/SkeletonTemplate" +import { Text } from "#ui/atoms/Text" +import { PaginationInfo } from "#ui/resources/useResourceList/PaginationInfo" + +const PAGE_SIZE = 10 + +export interface ResourceRelationshipsConfig { + /** + * Relationship names to list, e.g. `["customer", "line_items"]`. + * + * They come from the caller because neither the SDK nor the payload can tell + * which relationships a type has: a relationship that was not sideloaded is + * simply absent from the resource. + */ + names: string[] + /** + * Called with a related record when its eye icon is clicked. Without it the + * records are listed but not clickable. + */ + onSelect?: (related: { type: string; id: string }) => void +} + +/** + * Lists a resource's relationships as an accordion, each row telling whether + * it holds a single record or many. + * + * A has-one sideloaded by the caller is read straight from the payload. + * Everything else is fetched through the relationship endpoint only when its + * row is expanded, one page at a time: loading every has-many upfront would + * cost one request each, dozens for an order. + */ +export const ResourceRelationships: FC< + ResourceRelationshipsConfig & { resource: Resource } +> = ({ resource, names, onSelect }) => { + if (names.length === 0) { + return ( + + {t("common.resource_details.no_relationships")} + + ) + } + + return ( +
+ {[...names].sort().map((name) => ( + + ))} +
+ ) +} + +const RelationshipRow: FC<{ + resource: Resource + name: string + onSelect: ResourceRelationshipsConfig["onSelect"] +}> = ({ resource, name, onSelect }) => { + const [isOpen, setIsOpen] = useState(false) + // Kept here rather than in the panel, which unmounts when the row is + // collapsed: reopening the row shows the page it was left on. + const [pageNumber, setPageNumber] = useState(1) + const id = useId() + const buttonId = `${id}-button` + const panelId = `${id}-panel` + + return ( + <> + + + {isOpen && ( +
+
+ +
+
+ )} + + ) +} + +interface RelationshipPanelProps { + resource: Resource + name: string + pageNumber: number + onPageChange: (pageNumber: number) => void + onSelect: ResourceRelationshipsConfig["onSelect"] +} + +/** The content of an expanded row, mounted only while the row is open. */ +const RelationshipPanel: FC = ({ + resource, + name, + pageNumber, + onPageChange, + onSelect, +}) => { + const sideloaded = getSideloadedHasOne(resource, name) + + if (sideloaded !== undefined) { + return ( + + ) + } + + return ( + + ) +} + +const FetchedRelatedRecords: FC = ({ + resource, + name, + pageNumber, + onPageChange, + onSelect, +}) => { + const { data, error, isLoading } = useRelatedRecords({ + resource, + name, + pageNumber, + }) + + if (error != null) { + return ( + + {t("common.resource_details.relationship_error")} + + ) + } + + if (data == null) { + return ( +
+ {t("common.loading")} + +
+ ) + } + + return ( + <> +
+ +
+ {data.meta.pageCount > 1 && ( + + )} + + ) +} + +/** + * Reads one page of a relationship through its endpoint. The endpoint answers + * a has-many with a list and a has-one with a single record (or nothing), so + * both are normalized to a list. The previous page stays on screen while the + * next one loads, so the pager doesn't jump, and a page already seen is not + * fetched again when its row is reopened. + */ +const useRelatedRecords = ({ + resource, + name, + pageNumber, +}: { + resource: Resource + name: string + pageNumber: number +}) => { + const { sdkClient } = useCoreSdkProvider() + + return useSWR( + getRelatedRecordsKey({ resource, name, pageNumber }), + async () => { + // `name` is only known at runtime, so the relationship method can't be + // resolved through the SDK's static types. + const reader = (sdkClient as unknown as RelationshipReader)[ + resource.type as ResourceTypeLock + ] + + // A name the SDK doesn't know would otherwise read as an empty + // relationship, hiding a typo or a renamed relationship. + const read = reader?.[name] + if (typeof read !== "function") { + throw new Error(`Unknown relationship "${name}" for "${resource.type}"`) + } + + return toListResponse( + await read.call(reader, resource.id, { + pageNumber, + pageSize: PAGE_SIZE, + }), + ) + }, + { keepPreviousData: true, revalidateIfStale: false }, + ) +} + +/** The SWR key of a relationship page, or `null` while the resource is a placeholder. */ +function getRelatedRecordsKey({ + resource, + name, + pageNumber, +}: { + resource: Resource + name: string + pageNumber: number +}): [string, string, string, string, number] | null { + if (isMockedId(resource.id)) { + return null + } + + return ["relationships", resource.type, resource.id, name, pageNumber] +} + +const RelatedRecords: FC<{ + records: Resource[] + onSelect?: ResourceRelationshipsConfig["onSelect"] +}> = ({ records, onSelect }) => { + if (records.length === 0) { + return ( + + {t("common.resource_details.no_records")} + + ) + } + + return ( +
+ {records.map((record, idx) => ( + + ))} +
+ ) +} + +const RelatedRecord: FC<{ + record: Resource + hasBorder: boolean + onSelect?: ResourceRelationshipsConfig["onSelect"] +}> = ({ record, hasBorder, onSelect }) => { + const className = cn( + // The ring is drawn inside: the card clips anything outside its edges. + "w-full flex items-center justify-between gap-4 px-4 py-2.5 text-left focus-visible:outline-offset-[-2px]", + { "border-b border-gray-100": hasBorder }, + ) + + const content = ( + <> + + + {record.id} + + + {getRecordLabel(record) ?? <>—} + + + {onSelect != null && ( +
diff --git a/packages/app-elements/src/ui/resources/useResourceList/useResourceList.test.tsx b/packages/app-elements/src/ui/resources/useResourceList/useResourceList.test.tsx index 0d015c8c8..3fa043175 100644 --- a/packages/app-elements/src/ui/resources/useResourceList/useResourceList.test.tsx +++ b/packages/app-elements/src/ui/resources/useResourceList/useResourceList.test.tsx @@ -174,14 +174,14 @@ describe("useResourceList - the page in the url", () => { expect(currentPageParam()).toBeNull() await act(async () => { - ;(await findByRole("button", { name: "Next page" })).click() + ;(await findByRole("button", { name: "common.next_page" })).click() }) await waitFor(() => { expect(currentPageParam()).toBe("2") }) await act(async () => { - ;(await findByRole("button", { name: "Previous page" })).click() + ;(await findByRole("button", { name: "common.previous_page" })).click() }) await waitFor(() => { expect(currentPageParam()).toBeNull() @@ -205,7 +205,7 @@ describe("useResourceList - the page in the url", () => { await findAllByTestId("orderItem-ready") await act(async () => { - ;(await findByRole("button", { name: "Next page" })).click() + ;(await findByRole("button", { name: "common.next_page" })).click() }) await waitFor(() => { expect(currentPageParam()).toBe("2") @@ -327,13 +327,15 @@ describe("useResourceList - the page in the url, on a metrics-backed list", () = const goNext = async (view: ReturnType): Promise => { await act(async () => { - ;(await view.findByRole("button", { name: "Next page" })).click() + ;(await view.findByRole("button", { name: "common.next_page" })).click() }) } const goPrevious = async (view: ReturnType): Promise => { await act(async () => { - ;(await view.findByRole("button", { name: "Previous page" })).click() + ;( + await view.findByRole("button", { name: "common.previous_page" }) + ).click() }) } @@ -379,7 +381,9 @@ describe("useResourceList - the page in the url, on a metrics-backed list", () = expect(new URLSearchParams(window.location.search).get("page")).toBeNull() }) // and the pager agrees it is on the first page - expect(await findByRole("button", { name: "Previous page" })).toBeDisabled() + expect( + await findByRole("button", { name: "common.previous_page" }), + ).toHaveAttribute("aria-disabled", "true") }) test("Should honour a page whose cursor the trail already holds", async () => { @@ -393,7 +397,7 @@ describe("useResourceList - the page in the url, on a metrics-backed list", () = await findAllByTestId("orderItem-ready") await act(async () => { - ;(await findByRole("button", { name: "Next page" })).click() + ;(await findByRole("button", { name: "common.next_page" })).click() }) await waitFor(() => { @@ -533,7 +537,7 @@ describe("useResourceList - pagination mode", () => { expect(page1Items[0]?.dataset.page).toBe("page1") // Navigate to page 2 (wait for button to be enabled) - const nextButton = await findByRole("button", { name: "Next page" }) + const nextButton = await findByRole("button", { name: "common.next_page" }) await act(async () => { nextButton.click() }) @@ -557,26 +561,32 @@ describe("useResourceList - pagination mode", () => { // Wait for buttons to appear (Pagination renders only after data is loaded) await waitFor(async () => { - const prevButton = await findByRole("button", { name: "Previous page" }) - const nextButton = await findByRole("button", { name: "Next page" }) - expect(prevButton).toBeDisabled() - expect(nextButton).not.toBeDisabled() + const prevButton = await findByRole("button", { + name: "common.previous_page", + }) + const nextButton = await findByRole("button", { + name: "common.next_page", + }) + expect(prevButton).toHaveAttribute("aria-disabled", "true") + expect(nextButton).toHaveAttribute("aria-disabled", "false") }) // Navigate to last page (page_count is 2) - const nextButton = await findByRole("button", { name: "Next page" }) + const nextButton = await findByRole("button", { name: "common.next_page" }) await act(async () => { nextButton.click() }) // On page 2 (last): next should be disabled, prev enabled await waitFor(async () => { - const prevButton = await findByRole("button", { name: "Previous page" }) + const prevButton = await findByRole("button", { + name: "common.previous_page", + }) const nextButtonUpdated = await findByRole("button", { - name: "Next page", + name: "common.next_page", }) - expect(nextButtonUpdated).toBeDisabled() - expect(prevButton).not.toBeDisabled() + expect(nextButtonUpdated).toHaveAttribute("aria-disabled", "true") + expect(prevButton).toHaveAttribute("aria-disabled", "false") }) }) }) diff --git a/packages/docs/src/mocks/data/relationships.js b/packages/docs/src/mocks/data/relationships.js new file mode 100644 index 000000000..e46ec868f --- /dev/null +++ b/packages/docs/src/mocks/data/relationships.js @@ -0,0 +1,37 @@ +import { delay, HttpResponse, http } from "msw" + +const RECORD_COUNT = 30 + +/** + * Any relationship of an order, e.g. `/orders/:id/available_payment_methods`, answered + * with 30 records paged by the requested `page[size]`, so the pager can be tried out. + * + * Keep it after the specific handlers: msw serves the first match, and this + * one would otherwise swallow `event_stores` and the like. + */ +const orderRelationship = http.get( + `https://mock.localhost/api/:version/orders/:id/:relationship`, + async ({ params, request }) => { + await delay(500) + const relationship = params.relationship.toString() + const searchParams = new URL(request.url).searchParams + const pageNumber = Number(searchParams.get("page[number]") ?? "1") + const pageSize = Number(searchParams.get("page[size]") ?? "10") + const from = (pageNumber - 1) * pageSize + const to = Math.min(from + pageSize, RECORD_COUNT) + + return HttpResponse.json({ + data: Array.from({ length: to - from }, (_, index) => ({ + id: `${relationship.slice(0, 4)}${String(from + index).padStart(6, "0")}`, + type: relationship, + attributes: { name: `${relationship} #${from + index + 1}` }, + })), + meta: { + record_count: RECORD_COUNT, + page_count: Math.ceil(RECORD_COUNT / pageSize), + }, + }) + }, +) + +export default [orderRelationship] diff --git a/packages/docs/src/mocks/handlers.js b/packages/docs/src/mocks/handlers.js index cfcc27300..0a4772274 100644 --- a/packages/docs/src/mocks/handlers.js +++ b/packages/docs/src/mocks/handlers.js @@ -8,6 +8,7 @@ import lineItems from "./data/line_items" import markets from "./data/markets" import metrics from "./data/metrics" import orders from "./data/orders" +import relationships from "./data/relationships" import shippingMethods from "./data/shipping_methods" import sku_lists from "./data/sku_lists" import skus from "./data/skus" @@ -29,4 +30,6 @@ export const handlers = [ ...skus, ...sku_lists, ...tags, + // Last: it matches any order relationship, see the file. + ...relationships, ] diff --git a/packages/docs/src/stories/resources/useResourceDetailsModal.stories.tsx b/packages/docs/src/stories/resources/useResourceDetailsModal.stories.tsx index 9bd4aba8e..0dbc170d1 100644 --- a/packages/docs/src/stories/resources/useResourceDetailsModal.stories.tsx +++ b/packages/docs/src/stories/resources/useResourceDetailsModal.stories.tsx @@ -114,6 +114,52 @@ export const WithAdditionalTabs: StoryFn = () => ( ) +/** + * Pass `relationships` to add a Relationships tab. List the relationship names + * yourself: neither the SDK nor the payload can tell which ones a type has. + * + * Each row says whether the relationship holds a single record or many. A + * has-one you sideloaded (`market` here) is read from the resource; any other + * relationship is fetched only when its row is expanded, ten records per page, + * with a pager showing the total when there is more than one. With `onSelect`, each + * related record gets an eye icon that hands you its `type` and `id`, e.g. to + * open it in another resource details modal. + * + * ```tsx + * navigate(`/${type}/${id}`), + * }} + * /> + * ``` + */ +export const WithRelationships: StoryFn = () => ( + + { + alert(`${type} ${id}`) + }, + }} + /> + +) + /** * While you are still fetching, pass `isLoading` to render skeletons in place * of the attribute list. From 08ed419947e70ff33750948ca3a708754229e669 Mon Sep 17 00:00:00 2001 From: Pier Francesco Ferrari Date: Thu, 19 Nov 2026 17:47:58 +0100 Subject: [PATCH 2/2] feat: match the resource details tabs, events and modal to the design --- .../app-elements/src/ui/atoms/Tabs.test.tsx | 2 +- packages/app-elements/src/ui/atoms/Tabs.tsx | 4 +- .../src/ui/composite/Modal.test.tsx | 20 ++++ .../app-elements/src/ui/composite/Modal.tsx | 39 ++++++-- .../ResourceAttributes.tsx | 6 +- .../ResourceDetailsContent.test.tsx | 73 ++++++++++++++ .../ResourceDetailsContent.tsx | 95 +++++++++++++++---- .../ResourceDetailsTimeline.tsx | 41 ++++++-- .../ResourceRelationships.tsx | 20 ++-- .../useResourceDetailsModal.tsx | 44 ++++++--- .../useResourceList/PaginationInfo.tsx | 14 ++- 11 files changed, 297 insertions(+), 61 deletions(-) diff --git a/packages/app-elements/src/ui/atoms/Tabs.test.tsx b/packages/app-elements/src/ui/atoms/Tabs.test.tsx index fa03de908..a3c29f636 100644 --- a/packages/app-elements/src/ui/atoms/Tabs.test.tsx +++ b/packages/app-elements/src/ui/atoms/Tabs.test.tsx @@ -91,7 +91,7 @@ describe("Tabs size", () => { ) const active = getByRole("tab", { name: "Colors" }) - expect(active).toHaveClass("text-xs", "font-semibold") + expect(active).toHaveClass("text-xs", "leading-5", "font-semibold") expect(active.querySelector("span")).toHaveClass("border-b-transparent") expect(getByRole("tablist")).toHaveClass("gap-4") }) diff --git a/packages/app-elements/src/ui/atoms/Tabs.tsx b/packages/app-elements/src/ui/atoms/Tabs.tsx index d05b8630e..704b32aa7 100644 --- a/packages/app-elements/src/ui/atoms/Tabs.tsx +++ b/packages/app-elements/src/ui/atoms/Tabs.tsx @@ -347,11 +347,13 @@ function TabNav({ // room around the label for a rounded focus ring, cancelled out by the // negative margin so the tabs keep their spacing className={cn( - "focus-ring-inline text-center leading-6 cursor-pointer -mb-[2px]", + "focus-ring-inline text-center cursor-pointer -mb-[2px]", // never break a two-word label ("In progress") onto a second line, and never // let the row squeeze it: the row scrolls instead "whitespace-nowrap shrink-0", { + "leading-6": size === "regular", + "leading-5": size === "small", "text-black font-semibold": isActive, "text-gray-500": !isActive, "text-xs": size === "small", diff --git a/packages/app-elements/src/ui/composite/Modal.test.tsx b/packages/app-elements/src/ui/composite/Modal.test.tsx index fc2688c88..a6c10b8e1 100644 --- a/packages/app-elements/src/ui/composite/Modal.test.tsx +++ b/packages/app-elements/src/ui/composite/Modal.test.tsx @@ -55,6 +55,26 @@ describe("Modal", () => { expect(fireEvent.keyDown(closeButton, { key: " " })).toBe(true) }) + test("Should keep a fixed height only when given one", () => { + const { getByTestId, rerender } = render( + + Short + , + ) + expect( + (getByTestId("modal").firstElementChild as HTMLElement).style.height, + ).toBe("") + + rerender( + + Short + , + ) + expect( + (getByTestId("modal").firstElementChild as HTMLElement).style.height, + ).toBe("500px") + }) + test("Should move focus to the modal panel on open, not to the close button", () => { const { closeButton, getByTestId } = setup() diff --git a/packages/app-elements/src/ui/composite/Modal.tsx b/packages/app-elements/src/ui/composite/Modal.tsx index c279c3bfc..e682ed77a 100644 --- a/packages/app-elements/src/ui/composite/Modal.tsx +++ b/packages/app-elements/src/ui/composite/Modal.tsx @@ -44,6 +44,13 @@ export type ModalProps = { children: React.ReactNode /** Max width preset */ size?: "large" | "medium" | "small" | "x-small" + /** + * Fixed height of the modal, as any CSS length (e.g. `clamp(480px, 70vh, 760px)`), + * with the body scrolling inside it. For content that changes while the modal + * is open, such as tabs or expandable rows, so the modal does not resize along + * with it. The modal never grows past its maximum height, `min(90vh, 800px)`. + */ + height?: string /** * Enables modal dismissal via backdrop click and Escape key. * @@ -76,7 +83,16 @@ type ModalComponent = React.ForwardRefExoticComponent< ModalProps & React.RefAttributes > & { Header: React.FC - Body: React.FC + Body: React.FC< + React.PropsWithChildren<{ + /** + * Drops the body's padding, for content that lays out its own: a row + * running from edge to edge, or one that sticks to the top while the + * body scrolls. + */ + flush?: boolean + }> + > Footer: React.FC } @@ -88,6 +104,7 @@ const ModalRoot = ( onClose, size = "small", dismissible = false, + height, onSubmit, dialogRef: forwardedDialogRef, }: ModalProps, @@ -160,7 +177,7 @@ const ModalRoot = ( ) const contentClassName = cn( - "bg-white rounded-md shadow-xl", + "bg-white rounded shadow-xl", "max-h-[min(90vh,800px)] flex flex-col", ) @@ -170,11 +187,17 @@ const ModalRoot = ( {onSubmit != null ? ( -
+ {children}
) : ( -
{children}
+
+ {children} +
)}
@@ -294,8 +317,12 @@ Modal.Header = ({ children }) => { ) } -Modal.Body = ({ children }) => { - return
{children}
+Modal.Body = ({ children, flush = false }) => { + return ( +
+ {children} +
+ ) } Modal.Footer = ({ children }) => { diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx index e936fe035..6c34321f8 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceAttributes.tsx @@ -56,7 +56,7 @@ const AttributeRow: FC<{ })} > = ({ value }) => { if (value == null || value === "") { return ( = ({ value }) => { return ( diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.test.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.test.tsx index 22a72337c..fcbb4888c 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.test.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.test.tsx @@ -149,3 +149,76 @@ describe("ResourceDetailsContent", () => { ).toBeNull() }) }) + +describe("ResourceDetailsContent edgeToEdge", () => { + const renderContent = async (edgeToEdge?: boolean): Promise => + await act(async () => + render( + + + + + , + ), + ) + + it("keeps the tabs and their content flush with the container by default", async () => { + const { getByRole } = await renderContent() + + expect(getByRole("tablist").parentElement?.parentElement).not.toHaveClass( + "[&_[role=tablist]]:px-6", + ) + expect(getByRole("tabpanel").firstElementChild).not.toHaveClass("px-6") + }) + + it("gives the tabs and their content a gutter, the row spanning the edges", async () => { + const { getByRole } = await renderContent(true) + + expect(getByRole("tablist").parentElement?.parentElement).toHaveClass( + "[&_[role=tablist]]:px-6", + // the room above the tabs, the container having none of its own + "[&_[role=tablist]]:pt-4", + // and the content 12px under the row, as designed + "[&_[role=tabpanel]]:pt-3", + ) + expect(getByRole("tabpanel").firstElementChild).toHaveClass("px-6") + }) +}) + +describe("ResourceDetailsContent fillHeight", () => { + const renderContent = async (fillHeight?: boolean): Promise => + await act(async () => + render( + + + + + , + ), + ) + + it("lets the content flow with the page by default", async () => { + const { getByRole } = await renderContent() + + expect(getByRole("tablist").parentElement?.parentElement).not.toHaveClass( + "h-full", + ) + }) + + it("fills the container and scrolls the open panel only, under the tab row", async () => { + const { getByRole } = await renderContent(true) + + expect(getByRole("tablist").parentElement?.parentElement).toHaveClass( + "h-full", + "flex", + "flex-col", + "[&>[role=tabpanel]]:overflow-y-auto", + ) + }) +}) diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx index 9d426ca19..cb289f3f8 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx @@ -1,8 +1,9 @@ import type { Resource, ResourceTypeLock } from "@commercelayer/sdk" +import cn from "classnames" import { type FC, type ReactNode, useId } from "react" import { t } from "#providers/i18n" import { Spacer } from "#ui/atoms/Spacer" -import { Tab, Tabs } from "#ui/atoms/Tabs" +import { Tab, Tabs, type TabsProps } from "#ui/atoms/Tabs" import { ResourceAttributes } from "./ResourceAttributes" import { ResourceEvents } from "./ResourceEvents" import { @@ -37,12 +38,30 @@ export interface ResourceDetailsContentProps { /** Extra tabs, rendered between Attributes (or Relationships) and Events. */ tabs?: ResourceDetailsTab[] /** - * Fixed height for each tab panel, e.g. `"70vh"`. Set it when the surrounding - * container must not resize as tabs change (a modal, typically). Leave it - * unset on a page, so content flows naturally instead of gaining a nested - * scrollbar. + * Fixed height for each tab panel, e.g. `"70vh"`, which then scrolls on its + * own. Set it when the surrounding container must not resize as tabs change + * and cannot scroll as a whole. Leave it unset on a page, so content flows + * naturally instead of gaining a nested scrollbar. */ panelHeight?: string + /** + * Size of the tab row. `small` suits a side column, next to a list. + * @default regular + */ + tabsSize?: TabsProps["size"] + /** + * Lets the tab row run from edge to edge of the container, with the tabs and + * their content kept 24px from the sides, the tabs 16px from the top and the + * content 12px under the row. For a container with no padding of its own, + * such as a side column next to a list. + */ + edgeToEdge?: boolean + /** + * Fills the height of the container, which must have one: the tab row stays + * in place and only the open panel scrolls, so its scrollbar starts under the + * row. For a modal or a side column that should not scroll as a whole. + */ + fillHeight?: boolean /** * Id for the tab list, used to build the ids that link each tab to its panel. * Defaults to a generated one, so several instances can coexist on the same @@ -64,15 +83,29 @@ export const ResourceDetailsContent: FC = ({ relationships, tabs = [], panelHeight, + tabsSize, + edgeToEdge = false, + fillHeight = false, id, }) => { const generatedId = useId() return ( - + [role=tabpanel]]:flex-1 [&>[role=tabpanel]]:min-h-0 [&>[role=tabpanel]]:overflow-y-auto [&>[role=tabpanel]]:pb-6": + fillHeight, + })} + > {[ - + , @@ -83,7 +116,7 @@ export const ResourceDetailsContent: FC = ({ key="relationships" name={t("common.resource_details.relationships")} > - + = ({ ...tabs.map((tab) => ( - {tab.content(resource)} + + {tab.content(resource)} + )), - + = ({ /** * Wraps a tab's content, optionally pinning it to a fixed height so switching - * tabs can't resize the container. The gradient strips hint that it scrolls. + * tabs can't resize the container. * * Styled inline rather than with utility classes: consumers of this library * have no Tailwind build of their own, and keeping the height configurable at * runtime rules out a static class anyway. */ -const TabPanel: FC<{ height?: string; children: ReactNode }> = ({ - height, - children, -}) => { +const TabPanel: FC<{ + height?: string + hasGutter: boolean + children: ReactNode +}> = ({ height, hasGutter, children }) => { if (height == null) { - return {children} + return ( + + {children} + + ) } return ( -
-
-
{children}
+
+
+ {children}
-
-
) } + +/** + * Room between the tab row and the content. An edge-to-edge row sets it on the + * whole panel instead, to the design's 12px. + */ +function getPanelTop(hasGutter: boolean): "2" | undefined { + if (hasGutter) { + return undefined + } + + return "2" +} diff --git a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsTimeline.tsx b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsTimeline.tsx index 97bd05a7b..edd9c29f4 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsTimeline.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsTimeline.tsx @@ -54,8 +54,13 @@ export function ResourceDetailsTimeline({ <> {Object.entries(groupedByDay).map(([day, dayItems], idx) => (
- - + + {formatDate({ isoDate: day, format: "date", timezone })} @@ -68,6 +73,19 @@ export function ResourceDetailsTimeline({ ) } +/** + * Room above a day's heading. The first one sits 12px down, level with the text + * of the first row of a list such as the attributes; the others leave a wide gap + * from the day before. + */ +function getDayTop(idx: number): "3" | "12" { + if (idx === 0) { + return "3" + } + + return "12" +} + export interface ResourceDetailsTimelineItemProps { /** Shown in bold. The time of `isoDate` sits on the right, next to the caret. */ title: ReactNode @@ -97,7 +115,9 @@ export function ResourceDetailsTimelineItem({ gap="none" className={cn( "w-full rounded! hover:border-black hover:shadow-cardhover", - { "border-black! shadow-cardhover!": isOpen }, + // a 2px black frame once open: the border plus a ring inside it, so the + // content does not move + { "border-black! inset-ring-1 inset-ring-black": isOpen }, )} > @@ -71,7 +77,7 @@ export function PaginationInfo({ onPageChange(currentPage + 1) } }} - className="p-2 aria-disabled:opacity-30 aria-disabled:cursor-default rounded-[8px] border border-gray-200" + className="p-2 bg-white aria-disabled:opacity-30 aria-disabled:cursor-default rounded-[8px] border border-gray-200" >