Skip to content
23 changes: 23 additions & 0 deletions .changeset/35601-related-tab-open-and-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@object-ui/plugin-detail': patch
'@object-ui/app-shell': patch
'@object-ui/fields': patch
'@object-ui/react': patch
---

fix(record-page): the related tab offers only 「↗」 and 「+ 添加」, and a pick of several is added all or none

Clause-②: no
Metadata-protocol: none

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.

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.

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.

The reader's header sort and column widths on the tab are remembered per list in the record page's existing per-user preferences.

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.

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.
35 changes: 34 additions & 1 deletion ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
* written on its own.
*
* ```json
* { "showEmptyFields": true }
* { "showEmptyFields": true,
* "relatedLists": { "<child>.<field>": { "sort": {…}, "columnState": {…} } } }
* ```
*
* The renderers read it through `@object-ui/react`'s
Expand All @@ -40,6 +41,7 @@ import {
RecordPagePreferencesProvider,
type RecordPagePreference,
type RecordPagePreferencesStore,
type RelatedListPreference,
} from '@object-ui/react';
import { useRecordStateFamily } from './UserStateAdapters.js';

Expand All @@ -59,9 +61,40 @@ export function sanitizeRecordPreference(v: unknown): RecordPagePreference {
const out: RecordPagePreference = {};
const show = (v as Record<string, unknown>).showEmptyFields;
if (typeof show === 'boolean') out.showEmptyFields = show;
const lists = sanitizeRelatedLists((v as Record<string, unknown>).relatedLists);
if (lists) out.relatedLists = lists;
return out;
}

/** The related tab's remembered sort and column widths, per list (objectstack#35601), well formed. */
function sanitizeRelatedLists(v: unknown): Record<string, RelatedListPreference> | undefined {
if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined;
const out: Record<string, RelatedListPreference> = {};
for (const [id, raw] of Object.entries(v as Record<string, unknown>)) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;
const entry: RelatedListPreference = {};
const sort = (raw as Record<string, unknown>).sort as { field?: unknown; order?: unknown } | undefined;
if (sort && typeof sort.field === 'string' && sort.field !== '' && (sort.order === 'asc' || sort.order === 'desc')) {
entry.sort = { field: sort.field, order: sort.order };
}
const columns = (raw as Record<string, unknown>).columnState as { order?: unknown; widths?: unknown } | undefined;
if (columns && typeof columns === 'object') {
const state: NonNullable<RelatedListPreference['columnState']> = {};
if (Array.isArray(columns.order)) state.order = columns.order.filter((k): k is string => typeof k === 'string');
if (columns.widths && typeof columns.widths === 'object' && !Array.isArray(columns.widths)) {
const widths: Record<string, number> = {};
for (const [k, w] of Object.entries(columns.widths as Record<string, unknown>)) {
if (typeof w === 'number' && Number.isFinite(w) && w > 0) widths[k] = w;
}
state.widths = widths;
}
entry.columnState = state;
}
if (entry.sort || entry.columnState) out[id] = entry;
}
return Object.keys(out).length > 0 ? out : undefined;
}

export function RecordPreferencesProvider({ children }: { children: ReactNode }) {
const family = useRecordStateFamily<RecordPagePreference>();
const [states, setStates] = useState<Record<string, RecordPagePreference>>({});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,25 @@ describe('RecordPreferencesProvider — the record page remembers "show empty fi
expect(result.current?.get('account')).toEqual({});
});
});

/**
* objectstack#35601 — the related tab's header sort and column widths ride in
* the same row, per list (`CHILD.FK`); what the row holds is kept only well
* formed.
*/
describe('RecordPreferencesProvider — the related tab\'s remembered sort and widths (objectstack#35601)', () => {
it('keeps a well-formed sort and column state per list and drops the rest', () => {
expect(sanitizeRecordPreference({
relatedLists: {
'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject', 7], widths: { subject: 240, due_date: -1 } } },
'note.project': { sort: { field: 'title', order: 'sideways' } },
'bad.entry': 'x',
},
})).toEqual({
relatedLists: {
'task.project': { sort: { field: 'due_date', order: 'desc' }, columnState: { order: ['subject'], widths: { subject: 240 } } },
},
});
expect(sanitizeRecordPreference({ relatedLists: ['x'] })).toEqual({});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* objectstack#35601 — a list opened from a record's related tab (「↗」)
* knows the record it came from. The record rides on the record trail
* (`?from=`, its last entry); the condition itself stays the ordinary
* `filter[FIELD]=ID` the related list always sent. The page then:
*
* - names the record in the condition's tag (「所属 X:record ×」), not its id;
* - draws a breadcrumb back to it (object / record / this list);
* - offers 「重置」, which puts the sourced condition back after the reader
* changed or removed it;
* - opens New as that record's child (the record form overlay, linked).
*
* Control: the same filter without a trail is an ordinary filtered list.
*/

import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup, fireEvent, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
// The page reaches `@objectstack/lint` through a dynamic import; its first load is paid at collection, not inside a case.
import '@objectstack/lint';

vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
return {
...actual,
usePermissions: () => ({
check: () => ({ allowed: true }),
checkField: () => true,
getFieldPermissions: () => [],
getRowFilter: () => undefined,
getObjectApiOperations: () => undefined,
roles: [],
isLoaded: false,
hasCapabilities: () => true,
can: () => true,
cannot: () => false,
}),
useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }),
};
});

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
createAuthenticatedFetch: () => vi.fn(),
}));

// Heavy children, all orthogonal to the chip row under test and each dragging in
// a plugin bundle — the same posture as the sibling create-affordance test on
// this page.
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
ListView: () => null,
}));
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
vi.mock('./CreateViewDialog', () => ({ CreateViewDialog: () => null }));
vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) }));

import { ObjectDataPage, sourceRelationshipField } from './ObjectDataPage';
import { ExpressionProvider } from '../providers/ExpressionProvider';
import { RECORD_TRAIL_PARAM } from '../urlParams';

const h = React.createElement;

const OBJECTS = [
{
name: 'task',
label: 'Task',
pluralLabel: 'Tasks',
managedBy: 'platform',
fields: {
id: { type: 'text', label: 'Id' },
subject: { type: 'text', label: 'Subject' },
project: { type: 'lookup', reference: 'project', label: 'Project' },
status: { type: 'text', label: 'Status' },
},
},
{ name: 'project', label: 'Project', pluralLabel: 'Projects', managedBy: 'platform', fields: { name: { type: 'text', label: 'Name' } } },
];

const TRAIL = encodeURIComponent(JSON.stringify([{ o: 'project', i: 'P-1', t: 'Launch' }]));

function makeDataSource() {
return {
find: vi.fn(async () => ({ data: [], total: 0 })),
findOne: vi.fn(async () => null),
create: vi.fn(async () => ({})),
update: vi.fn(async () => ({})),
delete: vi.fn(async () => ({})),
} as any;
}

function Probe() {
const location = useLocation();
return h('output', { 'data-testid': 'probe' }, `${location.pathname}${location.search}`);
}

function renderAt(search: string) {
return render(
h(ExpressionProvider, {
user: { id: 'u1', name: 'Ada', profile: 'admin' },
children: h(
MemoryRouter,
{ initialEntries: [`/apps/demo/task/data?${search}`] },
h(Routes, null, h(Route, {
path: '/apps/:appName/:objectName/data',
element: h(React.Fragment, null, h(ObjectDataPage, { dataSource: makeDataSource(), objects: OBJECTS }), h(Probe)),
})),
),
}),
);
}

const params = () => new URLSearchParams((screen.getByTestId('probe').textContent ?? '').split('?')[1] ?? '');
const chipText = (field: string) =>
document.querySelector(`[data-testid="object-data-remove-filter-${field}"]`)?.previousElementSibling?.textContent ?? null;
const reset = () => screen.getByTestId('object-data-reset-source') as HTMLButtonElement;

beforeEach(() => {
cleanup();
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'content-type': 'application/json' },
})));
});

afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});

describe('a list opened from a related tab knows its record (objectstack#35601)', () => {
it('the condition tag names the record, and a breadcrumb leads back to it', () => {
renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`);
expect(chipText('project')).toBe('Launch');
const crumbs = screen.getByTestId('object-data-source-crumbs');
expect(crumbs.textContent).toBe('Projects/Launch/Tasks');
expect(screen.getByTestId('object-data-source-record').getAttribute('href')).toContain('/apps/demo/project/record/P-1');
// Already on the sourced condition: nothing to reset.
expect(reset().disabled).toBe(true);
});

it('「重置」 puts the sourced condition back after the reader changed the filters', () => {
renderAt(`filter[project]=P-1&filter[status]=open&${RECORD_TRAIL_PARAM}=${TRAIL}`);
fireEvent.click(screen.getByTestId('object-data-remove-filter-project'));
expect(params().get('filter[project]')).toBeNull();
// The trail outlives the removed condition, so the way back stays.
expect(reset().disabled).toBe(false);
fireEvent.click(reset());
expect(params().get('filter[project]')).toBe('P-1');
expect(params().get('filter[status]')).toBeNull();
expect(params().get(RECORD_TRAIL_PARAM)).not.toBeNull();
expect(reset().disabled).toBe(true);
});

it('New opens the record form as that record\'s child', () => {
renderAt(`filter[project]=P-1&${RECORD_TRAIL_PARAM}=${TRAIL}`);
fireEvent.click(document.querySelector('[data-testid="object-data-new-button"]')!);
expect(params().get('form')).toBe('new');
expect(params().get('formObject')).toBe('task');
expect(params().get('formLink')).toBe('project:P-1');
});

it('CONTROL — the same filter without a trail: the id, no breadcrumb, no reset', () => {
renderAt('filter[project]=P-1');
expect(chipText('project')).toBe('= P-1');
expect(screen.queryByTestId('object-data-source-crumbs')).toBeNull();
expect(screen.queryByTestId('object-data-reset-source')).toBeNull();
});
});

describe('sourceRelationshipField', () => {
it('is the one single-valued relationship to the source object, and none when that is ambiguous', () => {
const source = { o: 'project', i: 'P-1' };
expect(sourceRelationshipField(OBJECTS[0], source)).toBe('project');
expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project' }, b: { type: 'lookup', reference: 'project' } } }, source)).toBeUndefined();
expect(sourceRelationshipField({ fields: { a: { type: 'lookup', reference: 'project', multiple: true } } }, source)).toBeUndefined();
});
});
Loading
Loading