Skip to content

Commit cc38a91

Browse files
fix(console): View all → New seeds the relationship lookup's dependsOn fields (#37421)
Fixes #37290 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:从记录页相关列表点「查看全部」进入列表,再点「新建」时,关联字段所依赖的上级值(如客户)会和父记录一起预填,不再卡在「请先选择客户」。 - 为什么做:补齐上一张相关页签预填改动漏掉的「查看全部」入口,两条入口用同一套预填规则。 - 出错会怎样:只影响新建表单打开时的初始值;关联字段没有声明依赖时行为与今天一致,读不到父记录时退回只带父记录;可直接撤回。 - 要你做什么:无。 ## What changes `ObjectDataPage`'s New under a record trail (a related list's "View all") wrote the parent `formLink` pair alone. It now applies `relatedCreateSeedOf` (from `@object-ui/plugin-detail/core`, already exported and already imported by `RelatedRecordActionsBridge`): parent pair first, then one `formLink` pair per `dependsOn` field, the same URL shape the related tab's New writes. - A2 measured: the page holds only the trail's parent id (`source.i`), not the parent record. The related-tab New uses its mounted parent record; here the page reads it once via `dataSource.findOne(source.o, source.i)`, and only when the relationship lookup declares a non-empty `dependsOn` (looked up with `parentRelationshipFieldDef`, so array-form field lists count too). No `dependsOn` means no read. A failed or empty read opens with the parent pair alone. - A1 holds: no export change; nothing copied. Files to read first (by risk): `ui/packages/app-shell/src/views/ObjectDataPage.tsx` (the New button's `onClick`, the async `findOne` branch). ## Tests `ui/packages/app-shell/src/views/ObjectDataPage.viewAllNewSeed-37290.test.tsx`: two cases. - `contract.opportunity` `dependsOn: ['account']`, trail parent `opportunity O-1` (account `A-1`): `formLink` = `['opportunity:O-1', 'account:A-1']`, `findOne` called once with `('opportunity', 'O-1')`. - CONTROL: `task.opportunity` with no `dependsOn`: `formLink` = `['opportunity:O-1']`, no read of the parent. <details><summary>Pin green with fix, red without (head ad4ceb5)</summary> - With the fix: `Test Files 1 passed (1) · Tests 2 passed (2)`, lock `VERDICT command-exit 0`. - `ObjectDataPage.tsx` checked out from base `ff6f9768d2` (`relatedCreateSeedOf` count 0), restored from `HEAD` (hash matches the HEAD blob, `git diff HEAD` empty): `Tests 1 failed | 1 passed (2)`, `AssertionError: expected [ 'opportunity:O-1' ] to deeply equal [ 'opportunity:O-1', 'account:A-1' ]`, lock `VERDICT command-exit 1`. The control stays green both ways. </details> ## Acceptance notes - "That path seeds through the same `relatedCreateSeedOf`": yes, the one exported function, no copy. - "One pin covers it, red without the fix": the file above, red reading quoted. ## Verification <details><summary>Local gates</summary> - `dispatch-gates --ran`: 38 derived, 36 run (all exit 0), 2 NOT-MEASURED (`check:type-check-debt` and `pnpm --dir ui exec vitest run scripts/`: both need the shared verify lock, held by a sibling run 30+ minutes). CI runs both. - `pnpm --filter @object-ui/app-shell run type-check`: NOT MEASURED locally for the same reason; CI `Type Check UI` covers it. - `overlap-check --branch=HEAD`: `VERDICT clean exit 0`. origin/main merged once before opening (no conflict). </details> Two-minute check: `cd ui && pnpm exec vitest run packages/app-shell/src/views/ObjectDataPage.viewAllNewSeed-37290.test.tsx`; expect 2 passed. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6Ca6EBDpTBZk8v46Jjv --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 82a8510 commit cc38a91

3 files changed

Lines changed: 295 additions & 4 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/console': patch
4+
---
5+
6+
fix(console): New on a list opened from a related list's "View all" seeds the relationship lookup's `dependsOn` fields, as the related tab's New does
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
A related list's "View all" opens the child list under the parent record (the record trail). Its New opened the child's create form with the parent link alone, so a relationship lookup that declares `dependsOn` (an order `dependsOn` the account) drew gated ("Select Account first") with the parent hidden, or was emptied by a `lookupAutofill`. It now opens with the same seed the related tab's New writes (`relatedCreateSeedOf`): the parent pair first, then one `formLink` pair per `dependsOn` field, valued from the parent record. The trail holds the parent's id alone, so the page reads the parent record once, and only when the relationship lookup declares a `dependsOn`; a lookup without one, or a parent that cannot be read, opens with the parent link alone, as before. While the parent is read, New is disabled; a read that has not answered within 5 seconds opens the form with the parent link alone, and a read that answers after the page moved on (another filter, another page) opens nothing.

‎ui/packages/app-shell/src/views/ObjectDataPage.tsx‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import * as React from 'react';
3636
import { Link, useParams, useNavigate, useSearchParams, useLocation } from 'react-router-dom';
3737
import { ListView, conditionCandidatesOf, conditionOptionsOf, useLookupValueNames } from '@object-ui/plugin-list';
38+
import { relatedCreateSeedOf } from '@object-ui/plugin-detail/core';
3839
import { useNavigationOverlay, useRowPredicate } from '@object-ui/react';
3940
import {
4041
Button,
@@ -55,7 +56,7 @@ import { formatMetadataError } from '@object-ui/data-objectstack';
5556
import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n';
5657
import { usePermissions, useFieldPermissions } from '@object-ui/permissions';
5758
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
58-
import { optionDisplayLabel, resolveAffordance, resolveFilterPlaceholders, type SchemaLike } from '@object-ui/core';
59+
import { optionDisplayLabel, parentRelationshipFieldDef, resolveAffordance, resolveFilterPlaceholders, type SchemaLike } from '@object-ui/core';
5960
import { normalizeFilterOperator, ViewFilterRuleSchema } from '@objectstack/spec/ui';
6061
import type { ViewFilterRule } from '@objectstack/spec/ui';
6162
import {
@@ -323,6 +324,13 @@ function addressPanelFilterConditionCount(searchParams: URLSearchParams): number
323324
return Array.isArray(conditions) ? conditions.length : 0;
324325
}
325326

327+
/**
328+
* objectstack#37290 — how long New under a record trail waits for the parent
329+
* read its `dependsOn` seed needs. Past it the form opens with the parent link
330+
* alone, as it does when the read is refused or finds nothing.
331+
*/
332+
export const TRAIL_NEW_PARENT_READ_TIMEOUT_MS = 5000;
333+
326334
export function ObjectDataPage({ dataSource, objects }: any) {
327335
const { appName, objectName } = useParams();
328336
const { t, language } = useObjectTranslation();
@@ -907,6 +915,12 @@ export function ObjectDataPage({ dataSource, objects }: any) {
907915
label: 'builtin:create:disabledWhen',
908916
});
909917
const createDisabled = createPredicates?.disabledWhen != null && createDisabledPred;
918+
// objectstack#37290 — New under a record trail may read the parent first
919+
// (the `dependsOn` seed). While it does, New is pending; a click's result is
920+
// dropped when the page unmounted or the address moved on before it settled.
921+
const [newPending, setNewPending] = React.useState(false);
922+
const newClickRef = React.useRef(0);
923+
React.useEffect(() => () => { newClickRef.current += 1; }, []);
910924

911925
if (!objectDef) {
912926
return (
@@ -961,13 +975,48 @@ export function ObjectDataPage({ dataSource, objects }: any) {
961975
const sp = new URLSearchParams(searchParams);
962976
sp.set(RECORD_FORM_PARAM, 'new');
963977
sp.set(RECORD_FORM_OBJECT_PARAM, objectDef.name);
964-
sp.set(RECORD_FORM_LINK_PARAM, `${sourceField}:${source.i}`);
965-
setSearchParams(sp);
978+
sp.delete(RECORD_FORM_LINK_PARAM);
979+
sp.append(RECORD_FORM_LINK_PARAM, `${sourceField}:${source.i}`);
980+
// objectstack#37290 — and seeded as the related tab's New seeds it
981+
// (objectstack#37246): each `dependsOn` field of the link takes the
982+
// source record's value, or the form gates the lookup. The trail
983+
// carries the record's id alone, so the record is read once, and
984+
// only when the link declares a `dependsOn` to seed.
985+
const dependsOn = (parentRelationshipFieldDef(objectDef.fields, sourceField) as { dependsOn?: unknown } | undefined)?.dependsOn;
986+
const open = (parentRecord?: Record<string, unknown>) => {
987+
for (const [field, value] of Object.entries(relatedCreateSeedOf(objectDef.fields, sourceField, parentRecord))) {
988+
sp.append(RECORD_FORM_LINK_PARAM, `${field}:${value}`);
989+
}
990+
setSearchParams(sp);
991+
};
992+
if (Array.isArray(dependsOn) && dependsOn.length > 0 && typeof dataSource?.findOne === 'function') {
993+
const click = ++newClickRef.current;
994+
const at = `${location.pathname}${location.search}`;
995+
setNewPending(true);
996+
let timer: ReturnType<typeof setTimeout> | undefined;
997+
const timedOut = new Promise<undefined>((resolve) => {
998+
timer = setTimeout(() => resolve(undefined), TRAIL_NEW_PARENT_READ_TIMEOUT_MS);
999+
});
1000+
const read = Promise.resolve()
1001+
.then(() => dataSource.findOne(source.o, source.i))
1002+
.catch(() => undefined);
1003+
void Promise.race([read, timedOut]).then((rec: unknown) => {
1004+
clearTimeout(timer);
1005+
if (click !== newClickRef.current) return;
1006+
setNewPending(false);
1007+
const now = locationRef.current;
1008+
if (`${now.pathname}${now.search}` !== at) return;
1009+
open(rec && typeof rec === 'object' ? (rec as Record<string, unknown>) : undefined);
1010+
});
1011+
return;
1012+
}
1013+
open(undefined);
9661014
return;
9671015
}
9681016
navigate('../new', { relative: 'path' });
9691017
}}
970-
disabled={createDisabled}
1018+
disabled={createDisabled || newPending}
1019+
aria-busy={newPending || undefined}
9711020
className="shadow-none gap-1.5 h-8 sm:h-9"
9721021
data-testid="object-data-new-button"
9731022
>
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
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#37290 — New on a list opened from a related list's "View all"
11+
* (the record trail, objectstack#35601) seeds the child as the related tab's
12+
* New does (objectstack#37246, `relatedCreateSeedOf`): beside the parent pair,
13+
* each `dependsOn` field of the link takes the source record's value. The
14+
* trail holds the record's id alone, so the page reads the record once.
15+
*
16+
* Control: a link with no `dependsOn` writes the parent pair and reads nothing.
17+
* A read refused, empty or past `TRAIL_NEW_PARENT_READ_TIMEOUT_MS` opens the
18+
* form with the parent pair alone; New is pending while the read runs; a read
19+
* that settles after the address moved on opens nothing.
20+
*/
21+
22+
import * as React from 'react';
23+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
24+
import { render, cleanup, fireEvent, screen, waitFor, act } from '@testing-library/react';
25+
import { MemoryRouter, Routes, Route, useLocation, useNavigate } from 'react-router-dom';
26+
// The page reaches `@objectstack/lint` through a dynamic import; its first load is paid at collection, not inside a case.
27+
import '@objectstack/lint';
28+
29+
vi.mock('@object-ui/permissions', async (importOriginal) => {
30+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
31+
return {
32+
...actual,
33+
usePermissions: () => ({
34+
check: () => ({ allowed: true }),
35+
checkField: () => true,
36+
getFieldPermissions: () => [],
37+
getRowFilter: () => undefined,
38+
getObjectApiOperations: () => undefined,
39+
roles: [],
40+
isLoaded: false,
41+
hasCapabilities: () => true,
42+
can: () => true,
43+
cannot: () => false,
44+
}),
45+
useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }),
46+
};
47+
});
48+
49+
vi.mock('@object-ui/auth', async (importOriginal) => ({
50+
...(await importOriginal<Record<string, unknown>>()),
51+
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
52+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
53+
createAuthenticatedFetch: () => vi.fn(),
54+
}));
55+
56+
// Heavy children, all orthogonal to the New path under test and each dragging in
57+
// a plugin bundle — the same posture as the sibling create-affordance test on
58+
// this page.
59+
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
60+
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
61+
ListView: () => null,
62+
}));
63+
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
64+
vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null }));
65+
vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) }));
66+
67+
import { ObjectDataPage, TRAIL_NEW_PARENT_READ_TIMEOUT_MS } from './ObjectDataPage';
68+
import { ExpressionProvider } from '../providers/ExpressionProvider';
69+
import { RECORD_TRAIL_PARAM } from '../urlParams';
70+
71+
const h = React.createElement;
72+
73+
const OBJECTS = [
74+
{
75+
name: 'contract',
76+
label: 'Contract',
77+
pluralLabel: 'Contracts',
78+
managedBy: 'platform',
79+
fields: {
80+
id: { type: 'text', label: 'Id' },
81+
account: { type: 'lookup', reference: 'account', label: 'Account' },
82+
opportunity: { type: 'lookup', reference: 'opportunity', label: 'Opportunity', dependsOn: ['account'] },
83+
},
84+
},
85+
{
86+
name: 'task',
87+
label: 'Task',
88+
pluralLabel: 'Tasks',
89+
managedBy: 'platform',
90+
fields: {
91+
id: { type: 'text', label: 'Id' },
92+
opportunity: { type: 'lookup', reference: 'opportunity', label: 'Opportunity' },
93+
},
94+
},
95+
{ name: 'opportunity', label: 'Opportunity', pluralLabel: 'Opportunities', managedBy: 'platform', fields: { name: { type: 'text', label: 'Name' }, account: { type: 'lookup', reference: 'account', label: 'Account' } } },
96+
{ name: 'account', label: 'Account', pluralLabel: 'Accounts', managedBy: 'platform', fields: { name: { type: 'text', label: 'Name' } } },
97+
];
98+
99+
const TRAIL = encodeURIComponent(JSON.stringify([{ o: 'opportunity', i: 'O-1', t: 'Big deal' }]));
100+
101+
const readParent = async (object: string, id: string) =>
102+
(object === 'opportunity' && id === 'O-1' ? { id: 'O-1', name: 'Big deal', account: 'A-1' } : null);
103+
104+
function makeDataSource(findOne: (object: string, id: string) => Promise<unknown> = readParent) {
105+
return {
106+
find: vi.fn(async () => ({ data: [], total: 0 })),
107+
findOne: vi.fn(findOne),
108+
create: vi.fn(async () => ({})),
109+
update: vi.fn(async () => ({})),
110+
delete: vi.fn(async () => ({})),
111+
} as any;
112+
}
113+
114+
function Probe() {
115+
const location = useLocation();
116+
return h('output', { 'data-testid': 'probe' }, `${location.pathname}${location.search}`);
117+
}
118+
119+
/** Moves the address on (a filter change made while New's read is pending). */
120+
function Mover() {
121+
const navigate = useNavigate();
122+
const location = useLocation();
123+
return h('button', { 'data-testid': 'move', onClick: () => navigate(`${location.pathname}${location.search}&moved=1`) }, 'move');
124+
}
125+
126+
function renderAt(objectName: string, dataSource: any) {
127+
return render(
128+
h(ExpressionProvider, {
129+
user: { id: 'u1', name: 'Ada', profile: 'admin' },
130+
children: h(
131+
MemoryRouter,
132+
{ initialEntries: [`/apps/demo/${objectName}/data?filter[opportunity]=O-1&${RECORD_TRAIL_PARAM}=${TRAIL}`] },
133+
h(Routes, null, h(Route, {
134+
path: '/apps/:appName/:objectName/data',
135+
element: h(React.Fragment, null, h(ObjectDataPage, { dataSource, objects: OBJECTS }), h(Probe), h(Mover)),
136+
})),
137+
),
138+
}),
139+
);
140+
}
141+
142+
const params = () => new URLSearchParams((screen.getByTestId('probe').textContent ?? '').split('?')[1] ?? '');
143+
const newButton = () => document.querySelector('[data-testid="object-data-new-button"]') as HTMLButtonElement;
144+
const clickNew = () => fireEvent.click(newButton());
145+
146+
beforeEach(() => {
147+
cleanup();
148+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
149+
status: 200,
150+
headers: { 'content-type': 'application/json' },
151+
})));
152+
});
153+
154+
afterEach(() => {
155+
vi.useRealTimers();
156+
vi.unstubAllGlobals();
157+
vi.clearAllMocks();
158+
});
159+
160+
describe('New from a record trail seeds the dependsOn fields (objectstack#37290)', () => {
161+
it('opens the child form with the parent pair, then the dependsOn value read from the source record', async () => {
162+
const ds = makeDataSource();
163+
renderAt('contract', ds);
164+
clickNew();
165+
await waitFor(() => expect(params().get('form')).toBe('new'));
166+
expect(params().get('formObject')).toBe('contract');
167+
expect(params().getAll('formLink')).toEqual(['opportunity:O-1', 'account:A-1']);
168+
expect(ds.findOne).toHaveBeenCalledTimes(1);
169+
expect(ds.findOne).toHaveBeenCalledWith('opportunity', 'O-1');
170+
});
171+
172+
it('CONTROL — a link with no dependsOn writes the parent pair alone and reads nothing', async () => {
173+
const ds = makeDataSource();
174+
renderAt('task', ds);
175+
clickNew();
176+
await waitFor(() => expect(params().get('form')).toBe('new'));
177+
expect(params().getAll('formLink')).toEqual(['opportunity:O-1']);
178+
expect(ds.findOne).not.toHaveBeenCalledWith('opportunity', 'O-1');
179+
});
180+
181+
it('a refused parent read opens the form with the parent pair alone', async () => {
182+
const ds = makeDataSource(async () => { throw Object.assign(new Error('forbidden'), { status: 403 }); });
183+
renderAt('contract', ds);
184+
clickNew();
185+
await waitFor(() => expect(params().get('form')).toBe('new'));
186+
expect(params().getAll('formLink')).toEqual(['opportunity:O-1']);
187+
expect(ds.findOne).toHaveBeenCalledWith('opportunity', 'O-1');
188+
expect(newButton().disabled).toBe(false);
189+
});
190+
191+
it('a parent read that finds nothing opens the form with the parent pair alone', async () => {
192+
const ds = makeDataSource(async () => null);
193+
renderAt('contract', ds);
194+
clickNew();
195+
await waitFor(() => expect(params().get('form')).toBe('new'));
196+
expect(params().getAll('formLink')).toEqual(['opportunity:O-1']);
197+
expect(ds.findOne).toHaveBeenCalledWith('opportunity', 'O-1');
198+
});
199+
200+
it('New is pending while the read runs, and a read that never settles opens the parent pair alone after the bound', async () => {
201+
vi.useFakeTimers({ shouldAdvanceTime: true });
202+
const ds = makeDataSource(() => new Promise(() => {}));
203+
renderAt('contract', ds);
204+
clickNew();
205+
await waitFor(() => expect(newButton().disabled).toBe(true));
206+
expect(newButton().getAttribute('aria-busy')).toBe('true');
207+
expect(params().get('form')).toBeNull();
208+
await vi.advanceTimersByTimeAsync(TRAIL_NEW_PARENT_READ_TIMEOUT_MS);
209+
await waitFor(() => expect(params().get('form')).toBe('new'));
210+
expect(params().getAll('formLink')).toEqual(['opportunity:O-1']);
211+
expect(newButton().disabled).toBe(false);
212+
});
213+
214+
it('a read that settles after the address moved on opens nothing and keeps the new address', async () => {
215+
let settle: (rec: unknown) => void = () => {};
216+
const ds = makeDataSource(() => new Promise((resolve) => { settle = resolve; }));
217+
renderAt('contract', ds);
218+
clickNew();
219+
await waitFor(() => expect(newButton().disabled).toBe(true));
220+
fireEvent.click(screen.getByTestId('move'));
221+
await waitFor(() => expect(params().get('moved')).toBe('1'));
222+
expect(newButton().disabled, 'still pending after the move (same mount)').toBe(true);
223+
settle({ id: 'O-1', account: 'A-1' });
224+
await waitFor(() => expect(newButton().disabled).toBe(false));
225+
// A stale open would write the address after the pending flag clears: let it land before reading.
226+
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); });
227+
expect(params().get('form')).toBeNull();
228+
expect(params().getAll('formLink')).toEqual([]);
229+
expect(params().get('moved')).toBe('1');
230+
});
231+
});

0 commit comments

Comments
 (0)