Skip to content

Commit e9fa6b5

Browse files
os-warrenclaude
andauthored
fix(kanban): lanes on a lookup or user field key by the foreign key and are titled by the record's name (#36430) (#36642)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8722AKp5es9SqH3bShhXVa1)_ Card thread for #36430, dispatched by seat repo:objectstack#1 · session_01JQwxba2NAjVpDLao1M9SYN Fixes #36430 (items 1–3; item 4 is open, see below) ## 维护者速读 - 看板按「负责人」这类查找 / 人员 / 主从 / 树形字段分列时,原来画出一堆标题为「[object Object]」的列、每列塞满全部卡片。现在每个被引用的记录一列,列名是它的名字(人名、客户名),卡片各归各列,没有值的卡片在「未分类」。 - 把卡片拖到另一列,会把该字段改成那一列对应的记录(例如把负责人从 Alice 改成 Bob),卡片上的负责人名字也随之更新。 - 第 4 项(在「视图设置 → 分列字段」里提供这些字段)还没做:它在列表视图的设置面板里,等维护者确认后补上,否则由席位另立卡。 ## What changes `ui/packages/plugin-kanban` only. 1. **Lanes from a reference field** — `ObjectKanban#effectiveColumns`' data-derived branch built lanes from `String(record[groupBy])`. The board fetches with `$expand`, so a reference value is the referenced record and every lane was `"[object Object]"`. New `kanbanReferenceLanes.ts`: `lanesFromRecords` makes one lane per distinct key — the expanded record's `id` (`_id`), else the stored value — titled through core's `referencedRecordTitle` (the field's `displayField`, then the target object's `nameField`, then the shared ladder), else the key. When the lane field declares `reference`, the board reads that object's definition (`useSettledSchema`, cached) so its declared name field titles the lane. A record with no value names no lane (it was already bucketed to "Uncategorized"; before, a data-derived board also drew an empty lane titled `null`). 2. **Bucketing on the foreign key** — `bucketCardsIntoColumns` keys a record by `laneKeyOf(value)`, so expanded references land in their lane, including declared `columns` keyed by foreign key. Lane paging already filters each lane's query on the lane id (the key), unchanged. 3. **A drag writes the foreign key** — the PATCH already sends the lane id, which is now the key. The optimistic local row holds the target lane's expanded record (`laneValueOf`) instead of the bare key, so the card keeps naming its new owner; the failure rollback restores the expanded value it held. **Item 4 (lane-field picker) is not in this diff.** It lives in `ui/packages/plugin-list/src/ListView.tsx` (`laneFieldOptions` filter); the seat widened the surface, and the edit is waiting on the maintainer's go-ahead in the thread. ## Why A board grouped by owner is a common grouping and was unusable (#36430, graded p1). ## Verification Head `02acbeab`, tree `objectstack-ai/objectstack@02acbea`: - New `ObjectKanban.referenceLanes-36430.test.tsx` (4 rows: owner lanes titled by name with the right cards; lookup lane titled by the target's `nameField`; a drop writes `{ owner_id: 'u2' }` and the card stays in Bob's lane; declared FK-keyed lanes take expanded values) and two rows in `index.bucket.test.ts`. - Ablation: with `ObjectKanban.tsx` and `index.tsx` restored from `origin/main` and the tests kept, 5 of the new rows fail (all 4 board rows and the FK bucketing row); with the fix, all pass. - `vitest run packages/plugin-kanban/` on `d8058107` (the later head only adds changeset lines): 84 files, 552 tests passed. - `overlap-check.mjs`: clean against `origin/main` `d7411fa3` and 0 open PR heads. - NOT MEASURED locally: `type-check` for plugin-kanban (the `@object-ui/*` dependency declarations are not built in this container; every error printed was a missing-module / implicit-any cascade, none on the new code's logic). `Type Check UI` in CI is the verdict. Clause-②: no Metadata-protocol: none ## Acceptance notes - **Item 4 and the swimlane sibling.** If the maintainer has not approved item 4 by the time CI is green, the seat (repo:objectstack#1) files two follow-up cards and lands this PR with `Fixes #36430` covering items 1–3: - the lane-field picker offering single-valued lookup, user, master-detail and tree fields (`ListView.tsx` `laneFieldOptions`), item 4 of #36430; - a swimlane (`swimlaneField`) on a reference field, which still stringifies the value in `KanbanImpl`'s swimlane bucketing (same defect class, the other axis). - A multi-valued reference used as the lane field still draws `[object Object],…` lanes; the picker change for item 4 leaves multi-valued references out. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxba2NAjVpDLao1M9SYN --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7e89bc6 commit e9fa6b5

6 files changed

Lines changed: 330 additions & 11 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/plugin-kanban': patch
3+
---
4+
5+
fix(kanban): a board grouped by a lookup, user, master-detail or tree field draws one lane per referenced record
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The board reads the lane field off records fetched with `$expand`, so a reference field's value is the referenced record, not its key. The lanes were built from the stringified value: one lane per card, every one titled "[object Object]", each holding every card. A lane on a reference field is now keyed by the foreign key and titled by the referenced record's name (the field's `displayField`, then the target object's `nameField`, then the shared record-title ladder); cards bucket by the foreign key, also into declared `columns` keyed by it; a drag to another lane writes the foreign key, and the moved card keeps naming its new value until the board refetches. A card with no value is drawn in "Uncategorized", as before; a data-derived board no longer draws a lane titled "null" for it.
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#36430 — a board grouped by a reference field (lookup, user,
11+
* master-detail, tree).
12+
*
13+
* The board fetches with `$expand`, so the lane field's value is the
14+
* referenced record. Before the fix the lanes were built from
15+
* `String(value)`: one lane per card, every one titled "[object Object]", and
16+
* each holding every card (bucketing keyed on the same string).
17+
*
18+
* Rows:
19+
* (a) one lane per referenced record, titled by its name, holding that
20+
* record's cards; a card with no value sits in "Uncategorized";
21+
* (b) the referenced object's declared name field titles the lane;
22+
* (c) a drag to another lane writes the foreign key, and the card stays in
23+
* the lane it was dropped on, still naming its new owner;
24+
* (d) declared lanes keyed by foreign key bucket expanded values.
25+
*
26+
* The drop is driven through `DndContext`'s real `onDragEnd`, captured as in
27+
* `ObjectKanban.rejectedMoveRollback.test.tsx`: jsdom has no pointer layout.
28+
*/
29+
30+
import React from 'react';
31+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
32+
import { render, screen, within, act, cleanup, waitFor } from '@testing-library/react';
33+
import '@testing-library/jest-dom';
34+
import { registerAllFields } from '@object-ui/fields';
35+
import type { DataSource } from '@object-ui/types';
36+
import { ObjectKanban } from './ObjectKanban';
37+
import './KanbanImpl';
38+
39+
const dnd = vi.hoisted(() => ({
40+
onDragEnd: undefined as undefined | ((event: unknown) => void),
41+
}));
42+
43+
vi.mock('@dnd-kit/core', async (importOriginal) => {
44+
const actual = await importOriginal<typeof import('@dnd-kit/core')>();
45+
const ReactMod = await import('react');
46+
const CapturingDndContext = (props: Record<string, unknown>) => {
47+
dnd.onDragEnd = props.onDragEnd as (event: unknown) => void;
48+
return ReactMod.createElement(actual.DndContext, props as never);
49+
};
50+
return { ...actual, DndContext: CapturingDndContext };
51+
});
52+
53+
registerAllFields();
54+
55+
const DEAL = {
56+
name: 'deal',
57+
fields: {
58+
title: { type: 'text', label: 'Title' },
59+
owner_id: { type: 'user', label: 'Owner', reference: 'sys_user' },
60+
account_id: { type: 'lookup', label: 'Account', reference: 'account' },
61+
},
62+
};
63+
64+
/** The account object names its records by `company`, not by a name-ish key. */
65+
const ACCOUNT = {
66+
name: 'account',
67+
nameField: 'company',
68+
fields: { company: { type: 'text', label: 'Company' }, code: { type: 'text', label: 'Code' } },
69+
};
70+
71+
const ALICE = { id: 'u1', name: 'Alice' };
72+
const BOB = { id: 'u2', name: 'Bob' };
73+
const ACME = { id: 'a1', company: 'Acme', code: 'ZZ-1' };
74+
const GLOBEX = { id: 'a2', company: 'Globex', code: 'ZZ-2' };
75+
76+
const rows = () => [
77+
{ id: 'd1', title: 'Deal one', owner_id: ALICE, account_id: ACME },
78+
{ id: 'd2', title: 'Deal two', owner_id: BOB, account_id: GLOBEX },
79+
{ id: 'd3', title: 'Deal three', owner_id: ALICE, account_id: ACME },
80+
{ id: 'd4', title: 'Deal four', owner_id: null, account_id: null },
81+
];
82+
83+
function makeDataSource(update = vi.fn(async () => ({}))): DataSource {
84+
return {
85+
getObjectSchema: vi.fn(async (name: string) => (name === 'account' ? ACCOUNT : name === 'deal' ? DEAL : { name, fields: {} })),
86+
find: vi.fn(async () => ({ value: rows() })),
87+
update,
88+
} as unknown as DataSource;
89+
}
90+
91+
/** The cards in a lane, by the lane's visible title. */
92+
function cardsIn(laneTitle: string): string[] {
93+
const list = screen.getByRole('list', { name: `${laneTitle} cards` });
94+
return within(list)
95+
.queryAllByRole('listitem')
96+
.map((el) => el.getAttribute('aria-label') ?? '');
97+
}
98+
99+
function laneTitles(container: HTMLElement): string[] {
100+
return Array.from(container.querySelectorAll<HTMLElement>('[role="group"][aria-label]'))
101+
.map((lane) => lane.getAttribute('aria-label') ?? '');
102+
}
103+
104+
async function mountBoard(groupBy: string, extra: Record<string, unknown> = {}, dataSource = makeDataSource()) {
105+
const result = render(
106+
<ObjectKanban
107+
schema={{ type: 'object-kanban', objectName: 'deal', groupBy, cardTitle: 'title', ...extra } as any}
108+
dataSource={dataSource}
109+
/>,
110+
);
111+
expect(await screen.findByText('Deal four')).toBeInTheDocument();
112+
await act(async () => {
113+
await Promise.resolve();
114+
await Promise.resolve();
115+
});
116+
return result;
117+
}
118+
119+
beforeEach(() => {
120+
dnd.onDragEnd = undefined;
121+
});
122+
123+
afterEach(() => {
124+
cleanup();
125+
vi.restoreAllMocks();
126+
});
127+
128+
describe('a board grouped by a reference field (objectstack#36430)', () => {
129+
it('(a) draws one lane per owner, titled by name, holding that owner\'s cards', async () => {
130+
const { container } = await mountBoard('owner_id');
131+
await waitFor(() => expect(cardsIn('Alice')).toEqual(['Deal one', 'Deal three']));
132+
expect(cardsIn('Bob')).toEqual(['Deal two']);
133+
expect(cardsIn('Uncategorized')).toEqual(['Deal four']);
134+
expect(container.textContent).not.toContain('[object Object]');
135+
expect(laneTitles(container).filter((t) => t === 'Alice')).toHaveLength(1);
136+
});
137+
138+
it('(b) titles a lookup lane by the target object\'s declared name field', async () => {
139+
const { container } = await mountBoard('account_id');
140+
await waitFor(() => expect(cardsIn('Acme')).toEqual(['Deal one', 'Deal three']));
141+
expect(cardsIn('Globex')).toEqual(['Deal two']);
142+
expect(laneTitles(container)).not.toContain('ZZ-1');
143+
expect(container.textContent).not.toContain('[object Object]');
144+
});
145+
146+
it('(c) a drag to another owner\'s lane writes the foreign key and keeps the card there', async () => {
147+
const update = vi.fn(async () => ({}));
148+
await mountBoard('owner_id', {}, makeDataSource(update));
149+
await waitFor(() => expect(cardsIn('Bob')).toEqual(['Deal two']));
150+
151+
expect(dnd.onDragEnd).toBeTypeOf('function');
152+
await act(async () => {
153+
dnd.onDragEnd!({ active: { id: 'd1' }, over: { id: 'u2' } });
154+
});
155+
156+
expect(update).toHaveBeenCalledTimes(1);
157+
expect(update).toHaveBeenCalledWith('deal', 'd1', { owner_id: 'u2' });
158+
// Lanes hold their cards in fetch order, so d1 sorts ahead of d2.
159+
await waitFor(() => expect(cardsIn('Bob')).toEqual(['Deal one', 'Deal two']));
160+
expect(cardsIn('Alice')).toEqual(['Deal three']);
161+
});
162+
163+
it('(d) declared lanes keyed by foreign key take the expanded values', async () => {
164+
await mountBoard('owner_id', {
165+
columns: [{ id: 'u1', title: 'Team Alice' }, { id: 'u2', title: 'Team Bob' }],
166+
});
167+
await waitFor(() => expect(cardsIn('Team Alice')).toEqual(['Deal one', 'Deal three']));
168+
expect(cardsIn('Team Bob')).toEqual(['Deal two']);
169+
expect(cardsIn('Uncategorized')).toEqual(['Deal four']);
170+
});
171+
});

‎ui/packages/plugin-kanban/src/ObjectKanban.tsx‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import {
8282
} from './KanbanLanePaging';
8383
import { resolveCardOwner, type KanbanCardOwner } from './KanbanCardOwner';
8484
import { lanesFromOptions, type LaneLifecycleKind } from './kanbanLaneLifecycle';
85+
import { lanesFromRecords, laneValueOf } from './kanbanReferenceLanes';
8586

8687
/**
8788
* English fallbacks for the record-detail drawer heading this board opens on
@@ -1130,6 +1131,21 @@ export const ObjectKanban: React.FC<ObjectKanbanComponentProps> = ({
11301131
const ownerReference = ownerField ? objectDef?.fields?.[ownerField]?.reference : undefined;
11311132
const ownerPersonObject = typeof ownerReference === 'string' && ownerReference ? ownerReference : 'sys_user';
11321133

1134+
/**
1135+
* objectstack#36430 — a lane field that names the object it references
1136+
* (`reference`): that object, read so each lane is titled by its declared
1137+
* name field (`referencedRecordTitle`), and the field's own `displayField`.
1138+
* A field that names none (a person field left on its default) is titled
1139+
* off the expanded record alone. No read when the lane field names no object.
1140+
*/
1141+
const laneFieldDef = schema.groupBy ? objectDef?.fields?.[schema.groupBy] : undefined;
1142+
const laneTargetObject = typeof laneFieldDef?.reference === 'string' ? laneFieldDef.reference : '';
1143+
const laneDisplayField =
1144+
laneTargetObject && typeof laneFieldDef?.displayField === 'string' && laneFieldDef.displayField
1145+
? (laneFieldDef.displayField as string)
1146+
: undefined;
1147+
const { def: laneTargetDef } = useSettledSchema<any>(laneTargetObject, dataSource);
1148+
11331149
// Enhance data with title mapping and ensure IDs
11341150
// The host predicate scope a card's declared deadline is judged in
11351151
// (objectui#11815).
@@ -1576,17 +1592,17 @@ export const ObjectKanban: React.FC<ObjectKanbanComponentProps> = ({
15761592
);
15771593
}
15781594

1579-
// If no columns, but we have groupBy and data, generate from data
1595+
// If no columns, but we have groupBy and data, generate from data: one
1596+
// lane per distinct value. A reference value is expanded (the referenced
1597+
// record), so its lane is keyed by the foreign key and titled by the
1598+
// record's name (objectstack#36430); before, it was stringified to
1599+
// "[object Object]" for both.
15801600
if (schema.groupBy && effectiveData.length > 0) {
1581-
const groups = new Set(effectiveData.map(item => item[schema.groupBy!]));
1582-
return Array.from(groups).map(g => ({
1583-
id: String(g),
1584-
title: String(g)
1585-
}));
1601+
return lanesFromRecords(effectiveData, schema.groupBy, laneTargetDef ?? undefined, laneDisplayField);
15861602
}
15871603

15881604
return [];
1589-
}, [schema.columns, schema.groupBy, schema.objectName, effectiveData, objectDef, translateOptions]);
1605+
}, [schema.columns, schema.groupBy, schema.objectName, effectiveData, objectDef, translateOptions, laneTargetDef, laneDisplayField]);
15901606

15911607
/**
15921608
* objectui#11629 — the lane total each column header paints, from the
@@ -1812,6 +1828,14 @@ export const ObjectKanban: React.FC<ObjectKanbanComponentProps> = ({
18121828
const objectName = schema.objectName;
18131829
if (!groupBy) return MOVED;
18141830

1831+
// objectstack#36430 — on a reference lane field the lane id is the
1832+
// foreign key, and that is what the write sends; the record held locally
1833+
// keeps the referenced record expanded, as a refetch would return it, so
1834+
// the card goes on naming it (and the rollback restores what it held).
1835+
const loaded: Array<Record<string, unknown>> = Array.isArray(rawData) ? rawData : [];
1836+
const priorValue = loaded.find((r) => String(r?.id ?? r?._id) === String(cardId))?.[groupBy];
1837+
const movedValue = laneValueOf(loaded, groupBy, toColumnId);
1838+
18151839
// Optimistic local update so the card visibly stays in the new column.
18161840
// Skipped when data is owned by a parent (ListView): `fetchedData` is not
18171841
// what renders on that path (`rawData` prefers `externalData`, :219), and
@@ -1823,7 +1847,7 @@ export const ObjectKanban: React.FC<ObjectKanbanComponentProps> = ({
18231847
setFetchedData((prev) =>
18241848
prev.map((r) =>
18251849
String(r.id ?? r._id) === String(cardId)
1826-
? { ...r, [groupBy]: toColumnId }
1850+
? { ...r, [groupBy]: movedValue }
18271851
: r,
18281852
),
18291853
);
@@ -1897,14 +1921,14 @@ export const ObjectKanban: React.FC<ObjectKanbanComponentProps> = ({
18971921
setFetchedData((prev) =>
18981922
prev.map((r) =>
18991923
String(r.id ?? r._id) === String(cardId)
1900-
? { ...r, [groupBy]: fromColumnId }
1924+
? { ...r, [groupBy]: priorValue !== undefined && typeof priorValue === 'object' ? priorValue : fromColumnId }
19011925
: r,
19021926
),
19031927
);
19041928
return { kind: 'refused', message: refusal };
19051929
}
19061930
},
1907-
[schema.groupBy, schema.objectName, dataSource, hasExternalData, tt],
1931+
[schema.groupBy, schema.objectName, dataSource, hasExternalData, tt, rawData],
19081932
);
19091933

19101934
/**

‎ui/packages/plugin-kanban/src/index.bucket.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,30 @@ describe('bucketCardsIntoColumns', () => {
112112
expect(result.find((c) => c.id === KANBAN_UNCOLUMNED_ID)!.cards[0].coverImage).toBe('https://img/b.png');
113113
});
114114
});
115+
116+
describe('bucketCardsIntoColumns — expanded reference values (objectstack#36430)', () => {
117+
const owners = [
118+
{ id: 'u1', title: 'Alice' },
119+
{ id: 'u2', title: 'Bob' },
120+
];
121+
122+
it('buckets an expanded reference by its foreign key, not by "[object Object]"', () => {
123+
const data = [
124+
{ id: '1', owner_id: { id: 'u1', name: 'Alice' } },
125+
{ id: '2', owner_id: { id: 'u2', name: 'Bob' } },
126+
{ id: '3', owner_id: 'u1' },
127+
{ id: '4', owner_id: null },
128+
];
129+
const result = bucketCardsIntoColumns(owners, data, 'owner_id', undefined, 'Uncategorized');
130+
expect(result.map((c) => c.id)).toEqual(['u1', 'u2', KANBAN_UNCOLUMNED_ID]);
131+
expect(result[0].cards.map((c: any) => c.id)).toEqual(['1', '3']);
132+
expect(result[1].cards.map((c: any) => c.id)).toEqual(['2']);
133+
expect(result[2].cards.map((c: any) => c.id)).toEqual(['4']);
134+
});
135+
136+
it('puts an expanded value with no key in Uncategorized', () => {
137+
const data = [{ id: '1', owner_id: { name: 'Nobody' } }];
138+
const result = bucketCardsIntoColumns(owners, data, 'owner_id', undefined, 'Uncategorized');
139+
expect(result.find((c) => c.id === KANBAN_UNCOLUMNED_ID)!.cards.map((c: any) => c.id)).toEqual(['1']);
140+
});
141+
});

‎ui/packages/plugin-kanban/src/index.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { useObjectTranslation } from '@object-ui/i18n';
1717
import type { ComponentInput, KanbanConditionalFormattingRule } from '@object-ui/types';
1818
import { ObjectKanban } from './ObjectKanban';
1919
import { KanbanBoardCore } from './KanbanBoardCore';
20+
import { laneKeyOf } from './kanbanReferenceLanes';
2021

2122
/**
2223
* Sentinel column id for records whose `groupBy` value matches no declared
@@ -142,7 +143,8 @@ export function bucketCardsIntoColumns(
142143
// ⚠️ The repair keeps every record: an offending one keeps its own value as its
143144
// group key and still surfaces in the trailing lane, never discarded (#2792).
144145
const groups = data.reduce((acc, item) => {
145-
const rawKey = String(item[groupBy] ?? '');
146+
// objectstack#36430 — an expanded reference is keyed by its foreign key.
147+
const rawKey = laneKeyOf(item[groupBy]);
146148
const key = laneIdByFoldedId[rawKey.toLowerCase()] ?? rawKey;
147149
if (!acc[key]) acc[key] = [];
148150
acc[key].push(mapCoverImage(item));

0 commit comments

Comments
 (0)