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/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 371ea9b7e..6c34321f8 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 ( - + — ) @@ -77,9 +83,9 @@ const AttributeValue: FC<{ value: unknown }> = ({ value }) => { return ( {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.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 60350ee6b..cb289f3f8 100644 --- a/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx +++ b/packages/app-elements/src/ui/resources/ResourceDetailsModal/ResourceDetailsContent.tsx @@ -1,10 +1,15 @@ 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 { + ResourceRelationships, + type ResourceRelationshipsConfig, +} from "./ResourceRelationships" export interface ResourceDetailsTab { /** Tab label. */ @@ -24,15 +29,39 @@ 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 - * 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 @@ -42,8 +71,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,29 +80,62 @@ export interface ResourceDetailsContentProps { export const ResourceDetailsContent: FC = ({ resource, isLoading = false, + 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, + })} + > {[ - + , + ...(relationships != null + ? [ + + + + + , + ] + : []), + ...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 }, )} > + + {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 && ( +