Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions command-center-sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## 0.5.20

Compatibility axes: additive React `DataTableRowGrouping<T>` and `rowGrouping` props through
`/views`, plus `selectAllPageRows` localization text. No contract ID, wire payload, schema,
fixture, iframe protocol, theme token, or persisted storage change; no backend rollout required.

- Group current-page resource rows with accessible collapsible headers in table and phone forms.
- Keep a stacked mobile toolbar's search field at its natural height rather than its desktop flex basis.
- Keep collapsed rows in page-wide selection and preserve explicit/all-matching discovery,
preflight, confirmation, execution, refresh and selection cleanup.
- Document page-scoped labels and the consumer/SDK ownership boundary in the resource guide,
view README, packaged list skill, and packed consumer example.

## 0.5.19

- Add optional validated locale to v1 iframe initialization and live context. Older
Expand Down
4 changes: 4 additions & 0 deletions command-center-sdk/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Command Center SDK

Resource lists can group their current page with `rowGrouping` on `ResourceListPage` from
`@dev-mainsequence/command-center-sdk/views`. Collapsing a group preserves row selection and the
existing bulk-action lifecycle. See [grouping resource rows](docs/resources.md#group-rows-without-changing-selection).

`@dev-mainsequence/command-center-sdk` is the public TypeScript/React package for building
Command Center-compatible navigation, responsive application layouts, application feedback,
application controls, resource applications, themes, backend contracts, and static-site iframe integrations.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ The collection operation remains authoritative for rows and pagination.

## Do Not Rebuild Owned Behavior

For collapsible categories, pass `rowGrouping` with `getGroupId(item)` and
`renderGroupLabel(groupId, items)` to the same `ResourceListPage`. This groups only the supplied
page; labels must say when their count is page-scoped. Collapsing is presentation, not filtering:
select-all still includes collapsed rows, and the existing explicit/all-matching bulk lifecycle
is unchanged. Do not split groups into independent list instances or build parallel selection.
Group state is memory-only; `renderCard` takes precedence over grouping.

Do not create a parallel page header, toolbar, search row, result counter, selection bar, action
button strip, pagination footer, confirmation flow, or custom collection loading state. Do not use
a native select or bespoke dropdown for SDK-owned list filters.
Expand Down
25 changes: 25 additions & 0 deletions command-center-sdk/docs/resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,31 @@ pagination becomes previous, page summary, next. Row actions collapse into a men
more than two or the pointer is coarse. Pass `"table"` or `"stacked"` to fix the form. See
[Mobile and touch](./concepts/mobile.md).

### Group rows without changing selection

Use the public `rowGrouping` contribution on `ResourceListPage` when an existing paginated list
needs collapsible categories. The same `DataTableRowGrouping<T>` type works with `DataTable`.

```tsx
import { ResourceListPage, type DataTableRowGrouping } from "@dev-mainsequence/command-center-sdk/views";

const organizationGroups: DataTableRowGrouping<Service> = {
getGroupId: (service) => service.organization,
renderGroupLabel: (organization, rows) => `${organization} · ${rows.length} on this page`,
};

<ResourceListPage definition={serviceResource} rowGrouping={organizationGroups} tablePresentation="auto" />;
```

The consumer supplies group identity and label; the SDK renders accessible disclosure buttons in
both table and phone forms. Rows are grouped by first occurrence and keep their relative order.
Only current-page rows reach the label renderer. For complete organization totals, the backend
must provide them; do not infer them from a page. A collapse is not a filter: **Select all rows on
this page** includes collapsed groups. Explicit selected UIDs and all-matching queries continue
through the same discovery, preflight, confirmation, execution, and refresh flow. Group expansion
is transient and does not change backend queries, pagination or persisted storage. Empty and
failed collections keep their standard states. `renderCard` takes precedence over grouping.

## Build a resource detail

Keep the selected UID, query, and tab ids in the host, in the URL when they must survive a reload.
Expand Down
2 changes: 1 addition & 1 deletion command-center-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dev-mainsequence/command-center-sdk",
"version": "0.5.19",
"version": "0.5.20",
"private": false,
"description": "The framework-neutral SDK for building Command Center-compatible resource applications, navigation, layouts, themes, feedback, and embeds.",
"type": "module",
Expand Down
1 change: 1 addition & 0 deletions command-center-sdk/src/localization/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const sdkEnglishMessages = {
"selectAllMatching": "Select all {{count}} matching {{itemLabel}}",
"selectRow": "Select row",
"selectAllRows": "Select all visible rows",
"selectAllPageRows": "Select all rows on this page",
"loadingActions": "Loading actions",
"loadingItems": "Loading {{itemLabel}}…",
"emptyItems": "No {{itemLabel}} yet.",
Expand Down
72 changes: 66 additions & 6 deletions command-center-sdk/src/views/DataTable.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useSdkTranslation } from "../localization/react.js";
import type { KeyboardEvent, ReactNode } from "react";
import { useState, type KeyboardEvent, type ReactNode } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { Button } from "../controls/index.js";

import { useCommandCenterViewport, type CommandCenterViewportState } from "../layout/viewport.js";
import {
Expand Down Expand Up @@ -33,13 +35,21 @@ export interface ResourceRowAction<T> {
export type DataTablePresentation = "auto" | "stacked" | "table";
export type ResolvedDataTablePresentation = Exclude<DataTablePresentation, "auto">;

/** Presentation-only grouping of the supplied page; never narrows selection or the query. */
export interface DataTableRowGrouping<T> {
getGroupId: (item: T) => string;
/** Receives only current-page rows, never an inferred collection total. */
renderGroupLabel: (groupId: string, items: readonly T[]) => ReactNode;
}

export interface DataTableProps<T, Id extends ResourceId> {
columns: readonly ResourceColumnDefinition<T, ReactNode>[];
emptyContent?: ReactNode;
getId: (item: T) => Id;
isSelected?: (id: Id) => boolean;
isRowSelectable?: (item: T) => boolean;
items: readonly T[];
rowGrouping?: DataTableRowGrouping<T>;
/** Label of the per-row overflow menu. */
rowActionsLabel?: string;
rowActions?: readonly ResourceRowAction<T>[];
Expand Down Expand Up @@ -136,6 +146,7 @@ export function DataTable<T, Id extends ResourceId>({
isSelected,
isRowSelectable,
items,
rowGrouping,
moreDetailsLabel: moreDetailsLabelProp,
onActivateRow,
onSortChange,
Expand All @@ -152,12 +163,47 @@ export function DataTable<T, Id extends ResourceId>({
const emptyContent = emptyContentProp ?? t("noTableResults");
const moreDetailsLabel = moreDetailsLabelProp ?? t("moreDetails");
const rowActionsLabel = rowActionsLabelProp ?? t("actions");
const selectionLabel = selectionLabelProp ?? t("selectAllRows");
const selectionLabel = selectionLabelProp ?? t(rowGrouping ? "selectAllPageRows" : "selectAllRows");

const viewport = useCommandCenterViewport();
const resolvedPresentation = resolveDataTablePresentation(presentation, viewport);
const selectable = Boolean(isSelected && onToggleAll && onToggleSelection);
const resolvedColumns = resolveResourceColumnImportance(columns);
const [collapsedGroups, setCollapsedGroups] = useState<ReadonlySet<string>>(() => new Set());
type Entry = { kind: "row"; item: T } | { kind: "group"; id: string; items: readonly T[] };
const entries: Entry[] = [];
if (rowGrouping) {
const groups = new Map<string, T[]>();
for (const item of items) {
const id = rowGrouping.getGroupId(item);
const group = groups.get(id) ?? [];
group.push(item);
groups.set(id, group);
}
for (const [id, groupItems] of groups) {
entries.push({ kind: "group", id, items: groupItems });
if (!collapsedGroups.has(id)) entries.push(...groupItems.map((item) => ({ kind: "row" as const, item })));
}
} else {
entries.push(...items.map((item) => ({ kind: "row" as const, item })));
}
const renderGroupToggle = (entry: Extract<Entry, { kind: "group" }>) => (
<Button
type="button"
variant="ghost"
className="cc-data-table__group-toggle"
aria-expanded={!collapsedGroups.has(entry.id)}
onClick={() => setCollapsedGroups((current) => {
const next = new Set(current);
if (next.has(entry.id)) next.delete(entry.id);
else next.add(entry.id);
return next;
})}
>
{collapsedGroups.has(entry.id) ? <ChevronRight aria-hidden="true" size={16} /> : <ChevronDown aria-hidden="true" size={16} />}
{rowGrouping!.renderGroupLabel(entry.id, entry.items)}
</Button>
);

const activateFromKeyboard = (event: KeyboardEvent<HTMLElement>, item: T) => {
if (!onActivateRow || (event.key !== "Enter" && event.key !== " ")) {
Expand Down Expand Up @@ -206,12 +252,18 @@ export function DataTable<T, Id extends ResourceId>({
<div className="cc-data-table__empty">{emptyContent}</div>
) : (
<ol className="cc-data-table__stack">
{items.map((item) => {
{entries.map((entry) => {
if (entry.kind === "group") return (
<li key={`group:${entry.id}`} className="cc-data-table__group" data-cc-data-table-group={entry.id}>
{renderGroupToggle(entry)}
</li>
);
const item = entry.item;
const id = getId(item);
const rowSelectable = isRowSelectable ? isRowSelectable(item) : true;
return (
<li
key={id}
key={`row:${id}`}
className={`cc-data-table__stacked-row${onActivateRow ? " cc-data-table__row--interactive" : ""}`}
data-cc-data-table-row=""
tabIndex={onActivateRow ? 0 : undefined}
Expand Down Expand Up @@ -331,12 +383,20 @@ export function DataTable<T, Id extends ResourceId>({
</td>
</tr>
) : (
items.map((item) => {
entries.map((entry) => {
if (entry.kind === "group") return (
<tr key={`group:${entry.id}`} className="cc-data-table__group" data-cc-data-table-group={entry.id}>
<td colSpan={visibleColumns.length + (selectable ? 1 : 0) + (rowActions.length ? 1 : 0)}>
{renderGroupToggle(entry)}
</td>
</tr>
);
const item = entry.item;
const id = getId(item);
const rowSelectable = isRowSelectable ? isRowSelectable(item) : true;
return (
<tr
key={id}
key={`row:${id}`}
className={onActivateRow ? "cc-data-table__row--interactive" : undefined}
data-cc-data-table-row=""
tabIndex={onActivateRow ? 0 : undefined}
Expand Down
9 changes: 9 additions & 0 deletions command-center-sdk/src/views/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ Applications should not recreate this toolbar layout. Set
`refreshable` when the collection should expose the framework-owned toolbar refresh control;
consumers do not need to build a parallel refresh row or manage a reload token.

`rowGrouping` on `ResourceListPage` and `DataTable` adds collapsible current-page groups with
`getGroupId(item)` and `renderGroupLabel(groupId, items)`. Group headers are not resource rows.
Collapse affects presentation only: the header checkbox selects the full supplied page, hidden
rows stay selected, and all-matching selection, options, confirmation, preflight, execution and
refresh keep their existing lifecycle. Group order follows first occurrence; row order within a
group follows the collection. Labels receive current-page rows, so never present their length as
a collection-wide group total. The SDK holds expansion only in memory. Grouping is ignored for
`renderCard`, which remains a separate presentation. Backend query and pagination are unchanged.

When an adapter implements `discover`, `ResourceListPage` loads
`command-center.resource_discovery@v1` separately from collection rows. Discovery owns the title,
item label, searchable/filterable/sortable vocabulary, visible column order and headings, UI
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ResourceListPage, type DataTablePresentation, type DataTableRowGrouping } from "./index.js";
import type { ResourceApplicationDefinition, ResourceBulkActionDefinition } from "../resource/types.js";

Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
type Row = { uid: string; name: string; organization: string };
const items: Row[] = [
{ uid: "a", name: "Alpha", organization: "Organization A" },
{ uid: "b", name: "Beta", organization: "Organization B" },
];
const grouping: DataTableRowGrouping<Row> = {
getGroupId: (row) => row.organization,
renderGroupLabel: (id, rows) => `${id} (${rows.length})`,
};
const action: ResourceBulkActionDefinition = {
id: "review", label: "Review", endpoint: "/rows/review/", method: "POST",
selection_modes: ["explicit", "all_matching"], options: [],
preflight_endpoint: "/rows/review/preflight/",
confirmation: { title: "Review rows", button_label: "Review" },
};
const page = { items, pageInfo: { pageIndex: 0, pageSize: 2, totalItems: 12, hasNextPage: true, hasPreviousPage: false } };
const roots: ReturnType<typeof createRoot>[] = [];
afterEach(() => {
roots.splice(0).forEach((root) => act(() => root.unmount()));
document.body.innerHTML = "";
});
function button(text: string) {
const found = [...document.body.querySelectorAll('button')].find((node) => node.textContent === text);
expect(found, text).toBeDefined();
return found!;
}

describe.each<DataTablePresentation>(["table", "stacked"])("grouped %s resource list", (presentation) => {
it.each([false, true])("preserves collapsed rows through select-all, preflight and execution (all matching: %s)", async (allMatching) => {
const executeBulkAction = vi.fn().mockResolvedValue([]);
const preflightBulkAction = vi.fn().mockResolvedValue({ allowed: true, impacts: [], items: [], matchedCount: allMatching ? 12 : 2, raw: {} });
const definition: ResourceApplicationDefinition<Row, string> = {
id: "rows", label: "Rows", itemLabel: "rows", getId: (row) => row.uid,
columns: [{ id: "name", header: "Name", getValue: (row) => row.name }],
adapter: { list: vi.fn().mockResolvedValue(page), listBulkActions: vi.fn().mockResolvedValue([action]), preflightBulkAction, executeBulkAction },
};
const container = document.createElement("div"); document.body.append(container);
const root = createRoot(container); roots.push(root);
await act(async () => root.render(
<ResourceListPage definition={definition} initialResult={page} pageSize={2}
tablePresentation={presentation} rowGrouping={grouping}
renderBulkActionConfirmation={(input) => <div>
<span data-selected-items>{input.selectedItems.map((row) => row.uid).join(",")}</span>
<button disabled={!input.canConfirm} onClick={() => void input.onConfirm()}>Confirm test operation</button>
</div>}
/>,
));
await act(async () => button("Organization A (1)").click());
expect(button("Organization A (1)").getAttribute("aria-expanded")).toBe("false");
expect(container.querySelectorAll('[data-cc-data-table-row]')).toHaveLength(1);
const selectAll = container.querySelector<HTMLInputElement>('input[aria-label="Select all rows on this page"]')!;
await act(async () => selectAll.click());
expect(container.textContent).toContain("2 selected on this page.");
// Reopening proves the SDK selected a row whose checkbox was not mounted.
await act(async () => button("Organization A (1)").click());
expect([...container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].every((input) => input.checked)).toBe(true);
await act(async () => button("Organization A (1)").click());
if (allMatching) await act(async () => button("Select all 12 matching rows").click());
await act(async () => button("Actions").click());
await act(async () => button("Review").click());
const selection = allMatching ? { mode: "all_matching", query: { search: "", filters: {} } }
: { mode: "explicit", uids: ["a", "b"] };
expect(preflightBulkAction).toHaveBeenCalledWith(action, expect.objectContaining({ selection }));
if (!allMatching) expect(container.querySelector('[data-selected-items]')?.textContent).toBe("a,b");
await act(async () => button("Confirm test operation").click());
expect(executeBulkAction).toHaveBeenCalledWith(action, expect.objectContaining({ selection }));
expect(container.textContent).not.toContain("selected on this page");
});
});
5 changes: 5 additions & 0 deletions command-center-sdk/src/views/ResourceListPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
DataTable,
resolveDataTablePresentation,
type DataTablePresentation,
type DataTableRowGrouping,
type ResourceRowAction,
} from "./DataTable.js";
import { ResourceCardGrid } from "./ResourceCardGrid.js";
Expand Down Expand Up @@ -107,6 +108,8 @@ export interface ResourceListPageProps<T, Id extends ResourceId> {
searchable?: boolean;
/** Table form; `auto` stacks rows below the `sm` breakpoint. Ignored when `renderCard` is set. */
tablePresentation?: DataTablePresentation;
/** Group current-page rows visually; select-all and bulk actions include collapsed rows. */
rowGrouping?: DataTableRowGrouping<T>;
toolbarLeading?: ReactNode;
toolbarTrailing?: ReactNode;
onBulkActionSuccess?: (action: ResourceBulkActionDefinition, response: unknown) => void;
Expand Down Expand Up @@ -199,6 +202,7 @@ export function ResourceListPage<T, Id extends ResourceId>({
refreshKey,
renderBulkActionConfirmation,
renderCard,
rowGrouping,
rowActions = [],
searchPlaceholder,
searchable = true,
Expand Down Expand Up @@ -946,6 +950,7 @@ export function ResourceListPage<T, Id extends ResourceId>({
renderCard={renderCard}
/>
) : <DataTable
rowGrouping={rowGrouping}
allSelected={allMatching || selection.allSelected}
columns={columns}
emptyContent={
Expand Down
18 changes: 18 additions & 0 deletions command-center-sdk/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,20 @@ h3),
overflow: hidden;
}

.cc-data-table .cc-data-table__group > td {
padding: 0;
}

.cc-data-table__group-toggle {
width: 100%;
justify-content: flex-start;
text-align: start;
}

.cc-data-table__group {
list-style: none;
}

.cc-resource-card-grid {
display: grid;
gap: 1rem;
Expand Down Expand Up @@ -2864,6 +2878,10 @@ h3),
flex-direction: column;
}

.cc-resource-toolbar__search {
flex-basis: auto;
}

.cc-resource-search {
align-items: stretch;
flex-direction: column;
Expand Down
Loading
Loading