Skip to content

Commit bae933b

Browse files
fix(record-page): the related tab offers only open-in-list and one add entry; a multi-pick add is all or none (#35725)
Part of #35601 Fixes #35710 Part of #35590 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:记录详情页的关联页签只剩「↗」和「+ 添加」两个入口(普通关联的选择框只列出还没挂在任何记录下的子记录,不会悄悄把别处的记录改挂过来),一次选多条要么全部加上、要么一条不加;带状态的子记录按状态分组,已完成的排在最后;从「↗」打开的列表会写明来自哪条记录,可一键重置回去;明细表货币算不出来时合计照样显示金额。 - 为什么做:记录详情页子卡(关联页签只保留开列表与添加两件事),并顺带补上明细表合计缺失的子卡。 - 出错会怎样:一次选多条时如果其中一条失败,整批都不加并在列表下方显示服务端原话;目前这句话不一定点名是哪一条,这一半留在原卡等维护者定夺;改动只在界面层,直接撤回即可。 - 要你做什么:无。「批量添加失败时点名具体哪一条」已另开 #35726(给批量接口的报错加上第几条),本单合并后排队。 ## What changes **The related tab (`RelatedList.tsx`, the enlarged face).** The toolbar draws two entries at its right end: 「↗」 (`data-related-open-list`, the host's `onViewAll`) and 「+ 添加」 (`data-related-add`). The filter box, the 全部/我的/逾期 chips, the export, the tab's own New and the count line under the table are gone; the count lives in the tab title. A page's declared toolbar actions for the child (`toolbarActions`) still draw beside the two entries: they are authored metadata, not tab chrome, and dropping them would silently lose an authored action (see Acceptance notes). **One add entry, chosen by the relationship** when the page authored no `add` (`derivedAddOf`): | child relationship | 「+ 添加」 opens | |---|---| | `lookup` | a picker of the child object, listing only UNLINKED children (this relationship empty); its first row is New (`createRow`) | | `master_detail` whose rows name a catalog record (exactly one other required, single, editable `lookup`) | a picker of that catalog; a pick creates a row naming it (`linkField`) | | `master_detail` with no catalog | the new-record form, linked to this record (the host's `onNew`) | An authored `add` keeps its own picker and its own `picker.filter`, as before. **No silent re-parent (seat ruling on L1-a S1).** The derived lookup picker filters `<relationship> is_empty`: a child already under this record (a no-op pick) and a child under another parent (which a pick would move without notice) are not offered. Moving a child between parents stays on the child's own form, where the change is visible. **All or none.** A pick of N records is ONE `dataSource.batchTransaction` call: one `POST /api/v1/batch` with `atomic: true` (ADR-0035, ADR-0119 D4), never a client loop. Re-parenting a lookup child is `update`, a catalog pick is `create`. On failure nothing is added, the picker closes and the server's own message shows under the list (`role="alert"`). A data source with no `batchTransaction` offers no picker (it falls back to New). This also changes an authored `add` picker everywhere it is used: it was a loop of single writes, it is now the same one batch. **Status grouping.** On the related tab a child is grouped by status when it has a status select (`detectStatusField`) AND a `dueLike` date whose `settledWhen` the status settles. The rule, generic and declared, not a name list: a status option is "completed" exactly when `isDeadlineSettled(deadline, { [status]: option })` is true. Open options come first in the order the select declares them, then rows with no status (「—」), then the completed options; empty groups are not drawn; each group header collapses its rows. No settling option ⇒ no groups (the list draws as before). **Remembered header sort and column widths.** Per list (`CHILD.FK`), in the record page's existing per-user preference row (`sys_user_preference` `ui.record.PARENT`, through `RecordPagePreferencesContext`, which gains an optional `relatedLists` slice); no new storage. The sort is applied once on first read; a header click is written back. Column order and widths ride `object-grid`'s existing `columnState` input and `onColumnStateChange` host prop. **「↗」 on empty lists and body tables.** The card face draws 「↗」 on an empty list and on a body table too (when the host offers a destination). **The list 「↗」 opens knows its record** (`RelatedRecordActionsBridge.tsx`, `ObjectDataPage.tsx`). The bridge appends this record to the record trail (`?from=`) of the URL it already built (`filter[FK]=ID`). The list page then names the record in the condition's tag (「Account Globex ×」, the merged tag reused), draws a breadcrumb (object / record / this list), offers 「Reset」 which puts the sourced condition back after the reader changed or removed filters, and opens New as that record's child (the record form overlay with `formLink`, the related list's own New path). The condition itself stays an ordinary URL filter. **Body-table totals with no resolvable currency (the folded card).** A currency column whose currency resolves to nothing (no code of its own, no tenant default) now totals: the server's figure, drawn as its cells are (two places, no symbol). Before, the total was left out. Record-mode amounts whose rows name their own currency keep the per-currency grouping (a mixed or unknown code still draws no total). **`RecordPickerDialog`** gains an optional `createRow` prop (a dashed first row). Columns and search are untouched. No new i18n key: the strings reuse `detail.add`, `detail.new`, `detail.viewAll`, `common.reset`. The keys the removed chips used (`relatedFilter`, `relatedChips`, `relatedChipAll/Mine/Overdue`, `relatedExport`, `relatedRows`) are now unread and left in the packs (see Acceptance notes). ## Tests Migrated and retired: - `RelatedList.enlargedToolbar-27524.test.tsx`: rewritten. Retired the chip, filter, export and in-tab New cases and the export describe; new pins: exactly ↗ and Add (also on an empty list); lookup picker with New first and three picks as ONE batch of three; a rejected batch adds nothing, shows the reason and sends no single write; master_detail with a catalog creates rows naming the catalog; master_detail without one calls New; no batch route ⇒ no picker; status groups in order and collapsible, with a control; the header sort written to and read from the record-page preference. - `RelatedList.enlargedListGrid-28865.test.tsx`: retired the filter-box DEVIATION pin and the two chip-count pins; added "the count is not repeated under the grid", column state read from and written to the preference, and a no-store control. - `RecordRelatedListRenderer.showViewAll-12741.test.tsx`: 「an EMPTY list: no link」 migrated to 「an EMPTY list: ↗ still draws」. - `RelatedList.bodyTable-27055.test.tsx`: 「…and not at all without one」 split; new pin: with no currency resolving the total is the server figure, no symbol, one ungrouped aggregate. - Add tests given a `batchTransaction` on their data source (the picker gate now needs it): `addGateDataSource`, `addGrant-12082`, `addPickerFilter`, `addPickerGuard`, `addPickerLabelField`, `record-blocks.nestedLabelsI18nLabel-10993`. New: `ObjectDataPage.sourceList-35601.test.tsx` (tag names the record, breadcrumb, Reset, New linked, a no-trail control, `sourceRelationshipField`); a `from` pin in `RelatedRecordActionsBridge.viewAll-12741.test.tsx`; a `relatedLists` sanitize pin in `RecordPreferencesProvider-25883.test.tsx`. <details><summary>Readings at 6ea1cb9</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-detail packages/app-shell/src/views/ObjectDataPage.sourceList-35601.test.tsx packages/fields/src/widgets/RecordPickerDialog packages/react/src/context` at 756d92b: 3 failed (all `record-blocks.nestedLabelsI18nLabel-10993`, missing batch mock), 3773 passed; after the mock: that file and the sourced-list file 14/14. - app-shell `ObjectDataPage*`, `RelatedRecordActionsBridge*`, `RecordPreferencesProvider-25883`: 136/136 after the control fix; console `record-block-record-reach`, `public-block-binding-reach`, `PageBlockInspector.jsonFieldLabel-27178`, plugin-grid `relatedListRowActionDisabled-33215`: 38/38. - `type-check` (tsc --noEmit and tsconfig.test.json): react, fields, plugin-detail, app-shell, exit 0. - Ablation 1 (folded card): `else plan.amount = true;` replaced by `else continue;` (anchor 1 to 0, blob efaf47a to 28984401): the new total pin fails, 1 failed; restored, blob equals HEAD, `git diff HEAD` empty. - Ablation 2 (one request): the batch call (now `await ds.batchTransaction(operations);`) replaced by a per-op loop: 2 failed (the lookup and the catalog batch pins); restored, blob equals HEAD. </details> <details><summary>Fixes after 6ea1cb9 (CI)</summary> - df21125: dropped the unused `isPermissionError` import (Lint UI); the related tab entry's `detail.add` fallback is written once (`addFallbackLabel`), so the residue pin stays at 4 sites, and its comment names the new entry. - 05a187d: `batch.call(dataSource, …)` hid the add from the affordance write census (`affordanceGrantMap-12082`); it now calls `ds.batchTransaction(operations)` directly, and the census has one `handleAddRecords :: batch` site mapped to `relatedNew` + `relatedRowEdit` (replacing the old `create` / `update` pair). - CI at 05a187d: 45 success, 13 skipped, 0 failed. - e62ce9e (seat ruling on L1-a S1): the derived lookup picker filters the relationship to empty; new pin in `RelatedList.enlargedToolbar-27524`: a row linked here and a row linked elsewhere are absent, the unlinked row is present, and every picker read carries the rule. </details> ## Acceptance notes - **Open decision: naming the failed item.** Measured on a live boot: `POST /api/v1/batch` with `atomic: true` answers a failing op with ONE error (`404 {"error":"Record ID not found in showcase_contact","code":"RECORD_NOT_FOUND",...}`) and no op index. The list shows that message, which names the record only when the server's own message does (here it does; a validation error such as a missing required field does not). Naming the item in every case needs the batch route to say which op failed (a `batch-routes.ts` widening, Clause-② yes) or a data-source door over the per-object atomic batch (`/data/OBJECT/batch`, which reports per row). Neither was made here: the op index is filed as #35726 (nested under #35601), which is why the body says Part of for the related-tab card. - **Fence readings, declared:** `RecordPickerDialog` gains `createRow` (the fence names its columns and search; neither changed). `RecordPagePreferencesContext` (react) and `RecordPreferencesProvider` (app-shell) gain the `relatedLists` slice: the ruling's per-user mechanism, no new storage. `ObjectDataPage.tsx` carries the list route's tag, breadcrumb and reset wiring (the claim's "list route wiring"); `useOpenRecordList.ts` needed no change. - **Kept, not removed:** a page's declared `toolbarActions` for the child still draw beside ↗ and Add (authored metadata, not tab chrome). - **Not added:** auto-filling a catalog row's same-named fields (description, unit price) on a picker add; the server's defaults and hooks apply. 「Reset」 rewrites the URL filters; a quick-filter selection inside the list view is read from the URL only on first mount. - **Seen on the list page, not touched (list-page internals are out of this card):** the list view's own locked chip repeats the sourced condition with the raw id (「Account: = 3zKQ…」) under the named tag, and the list view's own 「Reset」 sits under this page's 「Reset」 (screenshot 06). - The "master_detail with no catalog" entry opens the new-record form linked to the record (the ruling's "add a row directly"); it does not insert an inline blank row. - The removed chips' i18n keys are left in the packs, unread. - No platform-checklist item changed: `records-forms.related-list-server-pagination` still holds (paging kept on the tab). ## Verification Two-minute check: on the CRM example, open an opportunity, its Activities tab: two buttons at the right (↗, Add), activities grouped Planned / In Progress / Cancelled / Completed. Open the Line Items body table: the Total row shows amounts with no currency symbol. Browser reading (A4): built console (`pnpm console:build` at this branch), headless Chromium 1440x900 at DSF 2; screenshots in the seat's `a4-35601` folder. <details><summary>A4 readings</summary> - Showcase, account Globex, Contacts tab (lookup, empty): toolbar `["View All","Add"]` (01). Add opens a picker of contacts, first row New (02). Three picks, Confirm: ONE `POST /api/v1/batch` 200 with three `update` ops and `atomic: true`; tab title Contacts 3 (03, 04). - Failing case: three more picked, the third deleted before Confirm: ONE `POST /api/v1/batch` 404 `RECORD_NOT_FOUND`; the alert shows the server message; the account still has 3 contacts and the first two picks kept their old account (05). - ↗ round trip: the list opens at `.../showcase_contact/data?filter[account]=ID&from=[{o,i,t:"Globex"}]`; tag 「Account Globex」, breadcrumb 「Accounts (Success Overlay) / Globex / Contacts」, Reset disabled (06); tag removed, Reset enabled (07); Reset puts `filter[account]` back (08); New opens the Create Contact overlay with `formLink=account:ID` (09); the breadcrumb record link returns to the account page. - CRM, opportunity Initech Expansion, Activities tab: groups `planned, in_progress, cancelled` open and `completed` settled, in that order (11, 12 collapsed). - CRM line items (master_detail, product is text, no catalog): enlarged toolbar `["View All","Add"]`; Add opens the new-record form (`form=new&formObject=crm_opportunity_line_item&formLink=opportunity:ID`), no picker (15, 16). Body table total row 「Total 2,649.75 5,501.00」, cells 「999.00」, 「3,601.50」: no symbol, as the cells (14). - The CRM line-item add-3 case does not exist as filed: the CRM line item has no catalog, so its Add is the form; the add-3 and failing cases were read on the showcase Contacts tab instead. </details> <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZrgaiMgTJCnswR6jQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 96faf44 commit bae933b

23 files changed

Lines changed: 1223 additions & 496 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@object-ui/plugin-detail': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/fields': patch
5+
'@object-ui/react': patch
6+
---
7+
8+
fix(record-page): the related tab offers only 「↗」 and 「+ 添加」, and a pick of several is added all or none
9+
10+
Clause-②: no
11+
Metadata-protocol: none
12+
13+
The record page's related tab drew a filter box, condition chips, an options menu, an export and its own New, and repeated the row count under the table. It now carries two entries at its right end. 「↗」 opens the child object's list under this record, on an empty list too. 「+ 添加」 is the one add entry, chosen by the relationship when the page authored no `add`: a `lookup` child opens a picker of that object whose first row is New; a `master_detail` child whose rows name a catalog record (one other required lookup) opens a picker of that catalog; one with no catalog opens the new-record form directly. The count shows once, in the tab title.
14+
15+
A pick of several records is one request to the transactional batch route: every row is added or none is, and the list says why when none was. Before, each pick was its own write, and a failure part way left the earlier rows added. A data source without the batch route offers no picker.
16+
17+
A child with a status and a deadline that the status settles is grouped by status on the tab: open groups first in the order the status lists them, completed groups last, each collapsible.
18+
19+
The reader's header sort and column widths on the tab are remembered per list in the record page's existing per-user preferences.
20+
21+
The list page 「↗」 opens names the record it came from: its condition tag reads the record's name, a breadcrumb leads back to it, 「Reset」 puts that condition back after the reader changed the filters, and New opens the record form linked to it.
22+
23+
A body table's total under a currency column whose currency does not resolve is drawn as its cells are, an amount with no symbol, instead of being left out (objectstack#35710). Rows that name their own currency are still totalled per currency.

‎ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
* written on its own.
1919
*
2020
* ```json
21-
* { "showEmptyFields": true }
21+
* { "showEmptyFields": true,
22+
* "relatedLists": { "<child>.<field>": { "sort": {…}, "columnState": {…} } } }
2223
* ```
2324
*
2425
* The renderers read it through `@object-ui/react`'s
@@ -40,6 +41,7 @@ import {
4041
RecordPagePreferencesProvider,
4142
type RecordPagePreference,
4243
type RecordPagePreferencesStore,
44+
type RelatedListPreference,
4345
} from '@object-ui/react';
4446
import { useRecordStateFamily } from './UserStateAdapters.js';
4547

@@ -59,9 +61,40 @@ export function sanitizeRecordPreference(v: unknown): RecordPagePreference {
5961
const out: RecordPagePreference = {};
6062
const show = (v as Record<string, unknown>).showEmptyFields;
6163
if (typeof show === 'boolean') out.showEmptyFields = show;
64+
const lists = sanitizeRelatedLists((v as Record<string, unknown>).relatedLists);
65+
if (lists) out.relatedLists = lists;
6266
return out;
6367
}
6468

69+
/** The related tab's remembered sort and column widths, per list (objectstack#35601), well formed. */
70+
function sanitizeRelatedLists(v: unknown): Record<string, RelatedListPreference> | undefined {
71+
if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined;
72+
const out: Record<string, RelatedListPreference> = {};
73+
for (const [id, raw] of Object.entries(v as Record<string, unknown>)) {
74+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;
75+
const entry: RelatedListPreference = {};
76+
const sort = (raw as Record<string, unknown>).sort as { field?: unknown; order?: unknown } | undefined;
77+
if (sort && typeof sort.field === 'string' && sort.field !== '' && (sort.order === 'asc' || sort.order === 'desc')) {
78+
entry.sort = { field: sort.field, order: sort.order };
79+
}
80+
const columns = (raw as Record<string, unknown>).columnState as { order?: unknown; widths?: unknown } | undefined;
81+
if (columns && typeof columns === 'object') {
82+
const state: NonNullable<RelatedListPreference['columnState']> = {};
83+
if (Array.isArray(columns.order)) state.order = columns.order.filter((k): k is string => typeof k === 'string');
84+
if (columns.widths && typeof columns.widths === 'object' && !Array.isArray(columns.widths)) {
85+
const widths: Record<string, number> = {};
86+
for (const [k, w] of Object.entries(columns.widths as Record<string, unknown>)) {
87+
if (typeof w === 'number' && Number.isFinite(w) && w > 0) widths[k] = w;
88+
}
89+
state.widths = widths;
90+
}
91+
entry.columnState = state;
92+
}
93+
if (entry.sort || entry.columnState) out[id] = entry;
94+
}
95+
return Object.keys(out).length > 0 ? out : undefined;
96+
}
97+
6598
export function RecordPreferencesProvider({ children }: { children: ReactNode }) {
6699
const family = useRecordStateFamily<RecordPagePreference>();
67100
const [states, setStates] = useState<Record<string, RecordPagePreference>>({});

‎ui/packages/app-shell/src/context/__tests__/RecordPreferencesProvider-25883.test.tsx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,25 @@ describe('RecordPreferencesProvider — the record page remembers "show empty fi
194194
expect(result.current?.get('account')).toEqual({});
195195
});
196196
});
197+
198+
/**
199+
* objectstack#35601 — the related tab's header sort and column widths ride in
200+
* the same row, per list (`CHILD.FK`); what the row holds is kept only well
201+
* formed.
202+
*/
203+
describe('RecordPreferencesProvider — the related tab\'s remembered sort and widths (objectstack#35601)', () => {
204+
it('keeps a well-formed sort and column state per list and drops the rest', () => {
205+
expect(sanitizeRecordPreference({
206+
relatedLists: {
207+
'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject', 7], widths: { subject: 240, due_date: -1 } } },
208+
'note.project': { sort: { field: 'title', order: 'sideways' } },
209+
'bad.entry': 'x',
210+
},
211+
})).toEqual({
212+
relatedLists: {
213+
'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject'], widths: { subject: 240 } } },
214+
},
215+
});
216+
expect(sanitizeRecordPreference({ relatedLists: ['x'] })).toEqual({});
217+
});
218+
});
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
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#35601 — a list opened from a record's related tab (「↗」)
11+
* knows the record it came from. The record rides on the record trail
12+
* (`?from=`, its last entry); the condition itself stays the ordinary
13+
* `filter[FIELD]=ID` the related list always sent. The page then:
14+
*
15+
* - names the record in the condition's tag (「所属 X:record ×」), not its id;
16+
* - draws a breadcrumb back to it (object / record / this list);
17+
* - offers 「重置」, which puts the sourced condition back after the reader
18+
* changed or removed it;
19+
* - opens New as that record's child (the record form overlay, linked).
20+
*
21+
* Control: the same filter without a trail is an ordinary filtered list.
22+
*/
23+
24+
import * as React from 'react';
25+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
26+
import { render, cleanup, fireEvent, screen } from '@testing-library/react';
27+
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
28+
// The page reaches `@objectstack/lint` through a dynamic import; its first load is paid at collection, not inside a case.
29+
import '@objectstack/lint';
30+
31+
vi.mock('@object-ui/permissions', async (importOriginal) => {
32+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
33+
return {
34+
...actual,
35+
usePermissions: () => ({
36+
check: () => ({ allowed: true }),
37+
checkField: () => true,
38+
getFieldPermissions: () => [],
39+
getRowFilter: () => undefined,
40+
getObjectApiOperations: () => undefined,
41+
roles: [],
42+
isLoaded: false,
43+
hasCapabilities: () => true,
44+
can: () => true,
45+
cannot: () => false,
46+
}),
47+
useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }),
48+
};
49+
});
50+
51+
vi.mock('@object-ui/auth', async (importOriginal) => ({
52+
...(await importOriginal<Record<string, unknown>>()),
53+
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
54+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
55+
createAuthenticatedFetch: () => vi.fn(),
56+
}));
57+
58+
// Heavy children, all orthogonal to the chip row under test and each dragging in
59+
// a plugin bundle — the same posture as the sibling create-affordance test on
60+
// this page.
61+
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
62+
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
63+
ListView: () => null,
64+
}));
65+
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
66+
vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null }));
67+
vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) }));
68+
69+
import { ObjectDataPage, sourceRelationshipField } from './ObjectDataPage';
70+
import { ExpressionProvider } from '../providers/ExpressionProvider';
71+
import { RECORD_TRAIL_PARAM } from '../urlParams';
72+
73+
const h = React.createElement;
74+
75+
const OBJECTS = [
76+
{
77+
name: 'task',
78+
label: 'Task',
79+
pluralLabel: 'Tasks',
80+
managedBy: 'platform',
81+
fields: {
82+
id: { type: 'text', label: 'Id' },
83+
subject: { type: 'text', label: 'Subject' },
84+
project: { type: 'lookup', reference: 'project', label: 'Project' },
85+
status: { type: 'text', label: 'Status' },
86+
},
87+
},
88+
{ name: 'project', label: 'Project', pluralLabel: 'Projects', managedBy: 'platform', fields: { name: { type: 'text', label: 'Name' } } },
89+
];
90+
91+
const TRAIL = encodeURIComponent(JSON.stringify([{ o: 'project', i: 'P-1', t: 'Launch' }]));
92+
93+
function makeDataSource() {
94+
return {
95+
find: vi.fn(async () => ({ data: [], total: 0 })),
96+
findOne: vi.fn(async () => null),
97+
create: vi.fn(async () => ({})),
98+
update: vi.fn(async () => ({})),
99+
delete: vi.fn(async () => ({})),
100+
} as any;
101+
}
102+
103+
function Probe() {
104+
const location = useLocation();
105+
return h('output', { 'data-testid': 'probe' }, `${location.pathname}${location.search}`);
106+
}
107+
108+
function renderAt(search: string) {
109+
return render(
110+
h(ExpressionProvider, {
111+
user: { id: 'u1', name: 'Ada', profile: 'admin' },
112+
children: h(
113+
MemoryRouter,
114+
{ initialEntries: [`/apps/demo/task/data?${search}`] },
115+
h(Routes, null, h(Route, {
116+
path: '/apps/:appName/:objectName/data',
117+
element: h(React.Fragment, null, h(ObjectDataPage, { dataSource: makeDataSource(), objects: OBJECTS }), h(Probe)),
118+
})),
119+
),
120+
}),
121+
);
122+
}
123+
124+
const params = () => new URLSearchParams((screen.getByTestId('probe').textContent ?? '').split('?')[1] ?? '');
125+
const chipText = (field: string) =>
126+
document.querySelector(`[data-testid="object-data-remove-filter-${field}"]`)?.previousElementSibling?.textContent ?? null;
127+
const reset = () => screen.getByTestId('object-data-reset-source') as HTMLButtonElement;
128+
129+
beforeEach(() => {
130+
cleanup();
131+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
132+
status: 200,
133+
headers: { 'content-type': 'application/json' },
134+
})));
135+
});
136+
137+
afterEach(() => {
138+
vi.unstubAllGlobals();
139+
vi.clearAllMocks();
140+
});
141+
142+
describe('a list opened from a related tab knows its record (objectstack#35601)', () => {
143+
it('the condition tag names the record, and a breadcrumb leads back to it', () => {
144+
renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`);
145+
expect(chipText('project')).toBe('Launch');
146+
const crumbs = screen.getByTestId('object-data-source-crumbs');
147+
expect(crumbs.textContent).toBe('Projects/Launch/Tasks');
148+
expect(screen.getByTestId('object-data-source-record').getAttribute('href')).toContain('/apps/demo/project/record/P-1');
149+
// Already on the sourced condition: nothing to reset.
150+
expect(reset().disabled).toBe(true);
151+
});
152+
153+
it('「重置」 puts the sourced condition back after the reader changed the filters', () => {
154+
renderAt(`filter[project]=P-1&filter[status]=open&${RECORD_TRAIL_PARAM}=${TRAIL}`);
155+
fireEvent.click(screen.getByTestId('object-data-remove-filter-project'));
156+
expect(params().get('filter[project]')).toBeNull();
157+
// The trail outlives the removed condition, so the way back stays.
158+
expect(reset().disabled).toBe(false);
159+
fireEvent.click(reset());
160+
expect(params().get('filter[project]')).toBe('P-1');
161+
expect(params().get('filter[status]')).toBeNull();
162+
expect(params().get(RECORD_TRAIL_PARAM)).not.toBeNull();
163+
expect(reset().disabled).toBe(true);
164+
});
165+
166+
it('New opens the record form as that record\'s child', () => {
167+
renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`);
168+
fireEvent.click(document.querySelector('[data-testid="object-data-new-button"]')!);
169+
expect(params().get('form')).toBe('new');
170+
expect(params().get('formObject')).toBe('task');
171+
expect(params().get('formLink')).toBe('project:P-1');
172+
});
173+
174+
it('CONTROL — the same filter without a trail: the id, no breadcrumb, no reset', () => {
175+
renderAt('filter[project]=P-1');
176+
expect(chipText('project')).toBe('= P-1');
177+
expect(screen.queryByTestId('object-data-source-crumbs')).toBeNull();
178+
expect(screen.queryByTestId('object-data-reset-source')).toBeNull();
179+
});
180+
});
181+
182+
describe('sourceRelationshipField', () => {
183+
it('is the one single-valued relationship to the source object, and none when that is ambiguous', () => {
184+
const source = { o: 'project', i: 'P-1' };
185+
expect(sourceRelationshipField(OBJECTS[0], source)).toBe('project');
186+
expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project' }, b: { type: 'lookup', reference: 'project' } } }, source)).toBeUndefined();
187+
expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project', multiple: true } } }, source)).toBeUndefined();
188+
});
189+
});

0 commit comments

Comments
 (0)