Skip to content

Commit afd3b4c

Browse files
committed
test(console): pin the form view's buttons, layout, defaults and tab keys on every form entry point
Claude-Session: https://claude.ai/code/session_01JQwxbabN2bfLWeaoNk6Jue Co-authored-by: Claude <noreply@anthropic.com>
1 parent 38c8664 commit afd3b4c

5 files changed

Lines changed: 823 additions & 0 deletions

File tree

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack-ai/objectstack#26843 — the form page renders the form view's
5+
* `buttons` and `defaults`, which it never read.
6+
*
7+
* - `buttons.submit` / `buttons.cancel`: an authored `label` replaces the
8+
* page's own, an authored `show: false` removes the button. The public
9+
* route still draws no Cancel at all.
10+
* - `defaults`: a create opens with them, over the object's own field
11+
* defaults and under a `?prefill_` param; an edit never reads them.
12+
*
13+
* CONTROL: a form view authoring neither keeps the page's own `Submit` /
14+
* `Cancel` and opens blank.
15+
*/
16+
17+
import { describe, expect, it, vi, afterEach } from 'vitest';
18+
import { render, screen, waitFor, cleanup } from '@testing-library/react';
19+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
20+
import { createI18n } from '@object-ui/i18n';
21+
import { FormPage, readFormButton, readPrefill } from './FormPage';
22+
23+
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
24+
25+
const OBJECT_SCHEMA = {
26+
name: 'showcase_inquiry',
27+
fields: {
28+
title: { type: 'text', label: 'Title' },
29+
channel: { type: 'text', label: 'Channel', defaultValue: 'phone' },
30+
},
31+
};
32+
33+
function viewBody(form: Record<string, unknown>) {
34+
return {
35+
name: 'showcase_inquiry.intake',
36+
object: 'showcase_inquiry',
37+
viewKind: 'form',
38+
label: 'Intake',
39+
config: { type: 'simple', sections: [{ fields: ['title', 'channel'] }], ...form },
40+
};
41+
}
42+
43+
function stubFetch(form: Record<string, unknown>) {
44+
return vi.fn(async (url: string) => {
45+
const path = String(url);
46+
const body = path.includes('/meta/view/')
47+
? viewBody(form)
48+
: path.includes('/meta/object/')
49+
? OBJECT_SCHEMA
50+
: path.includes('/forms/intake')
51+
? { slug: 'intake', object: 'showcase_inquiry', form: viewBody(form).config, objectSchema: OBJECT_SCHEMA }
52+
: path.includes('/data/showcase_inquiry/r1')
53+
? { record: { id: 'r1', title: 'Stored', channel: 'email' } }
54+
: null;
55+
if (!body) throw new Error(`unstubbed fetch: ${path}`);
56+
return {
57+
ok: true,
58+
status: 200,
59+
statusText: 'OK',
60+
json: async () => body,
61+
text: async () => JSON.stringify(body),
62+
} as unknown as Response;
63+
});
64+
}
65+
66+
function renderAt(url: string, mode: 'internal' | 'public') {
67+
createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false });
68+
return render(
69+
<MemoryRouter initialEntries={[url]}>
70+
<Routes>
71+
<Route path="/forms/:name" element={<FormPage mode="internal" />} />
72+
<Route path="/f/:slug" element={<FormPage mode="public" />} />
73+
</Routes>
74+
</MemoryRouter>,
75+
);
76+
}
77+
78+
const input = (name: string) => document.querySelector(`[name="${name}"]`) as HTMLInputElement | null;
79+
80+
afterEach(() => {
81+
cleanup();
82+
vi.unstubAllGlobals();
83+
});
84+
85+
describe('FormPage renders the form view\'s buttons (#26843)', () => {
86+
it('internal: the authored submit label shows, and a hidden cancel is gone', async () => {
87+
vi.stubGlobal('fetch', stubFetch({ buttons: { submit: { label: 'File inquiry' }, cancel: { show: false } } }));
88+
renderAt('/forms/showcase_inquiry.intake', 'internal');
89+
expect(await screen.findByRole('button', { name: 'File inquiry' })).toBeInTheDocument();
90+
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
91+
});
92+
93+
it('internal: an authored cancel label shows; a hidden submit is gone', async () => {
94+
vi.stubGlobal('fetch', stubFetch({ buttons: { submit: { show: false }, cancel: { label: 'Back' } } }));
95+
const { container } = renderAt('/forms/showcase_inquiry.intake', 'internal');
96+
expect(await screen.findByRole('button', { name: 'Back' })).toBeInTheDocument();
97+
expect(container.querySelector('button[type="submit"]')).toBeNull();
98+
});
99+
100+
it('public: the authored submit label shows, and there is still no Cancel', async () => {
101+
vi.stubGlobal('fetch', stubFetch({ buttons: { submit: { label: 'Send' }, cancel: { label: 'Back' } } }));
102+
renderAt('/f/intake', 'public');
103+
expect(await screen.findByRole('button', { name: 'Send' })).toBeInTheDocument();
104+
expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
105+
});
106+
107+
it('CONTROL: no `buttons` — the page\'s own Submit and Cancel', async () => {
108+
vi.stubGlobal('fetch', stubFetch({}));
109+
renderAt('/forms/showcase_inquiry.intake', 'internal');
110+
expect(await screen.findByRole('button', { name: 'Submit' })).toBeInTheDocument();
111+
expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument();
112+
});
113+
});
114+
115+
describe('FormPage seeds a create with the form view\'s defaults (#26843)', () => {
116+
it('a create opens with them, over the object\'s own field default', async () => {
117+
vi.stubGlobal('fetch', stubFetch({ defaults: { title: 'Website lead', channel: 'web' } }));
118+
renderAt('/forms/showcase_inquiry.intake', 'internal');
119+
await waitFor(() => expect(input('title')?.value).toBe('Website lead'));
120+
expect(input('channel')?.value).toBe('web');
121+
});
122+
123+
it('a `prefill_` param still wins per field', async () => {
124+
vi.stubGlobal('fetch', stubFetch({ defaults: { title: 'Website lead', channel: 'web' } }));
125+
renderAt('/forms/showcase_inquiry.intake?prefill_channel=chat', 'internal');
126+
await waitFor(() => expect(input('channel')?.value).toBe('chat'));
127+
expect(input('title')?.value).toBe('Website lead');
128+
});
129+
130+
it('an edit reads the stored record, never the defaults', async () => {
131+
vi.stubGlobal('fetch', stubFetch({ defaults: { title: 'Website lead', channel: 'web' } }));
132+
renderAt('/forms/showcase_inquiry.intake?recordId=r1', 'internal');
133+
await waitFor(() => expect(input('title')?.value).toBe('Stored'));
134+
expect(input('channel')?.value).toBe('email');
135+
});
136+
137+
it('CONTROL: no defaults — the object\'s own field default, else blank', async () => {
138+
vi.stubGlobal('fetch', stubFetch({}));
139+
renderAt('/forms/showcase_inquiry.intake', 'internal');
140+
await waitFor(() => expect(input('channel')?.value).toBe('phone'));
141+
expect(input('title')?.value).toBe('');
142+
});
143+
});
144+
145+
describe('the two helpers, directly', () => {
146+
it('readFormButton: shown unless `show: false`; a per-locale label resolves', () => {
147+
expect(readFormButton(undefined, 'en')).toStrictEqual({ show: true, label: '' });
148+
expect(readFormButton({ show: false }, 'en').show).toBe(false);
149+
expect(readFormButton({ label: { en: 'Send', 'zh-CN': '发送' } }, 'zh-CN').label).toBe('发送');
150+
});
151+
152+
it('readPrefill: defaults only for a field the form draws, and never on an edit', () => {
153+
const fields = [{ name: 'title' }, { name: 'channel', defaultValue: 'phone' }] as any;
154+
const search = new URLSearchParams();
155+
expect(readPrefill(fields, search, null, { title: 'T', unknown_field: 'x' })).toStrictEqual({ title: 'T', channel: 'phone' });
156+
expect(readPrefill(fields, search, { title: 'Stored' }, { title: 'T' })).toStrictEqual({ title: 'Stored', channel: 'phone' });
157+
});
158+
});
Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
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-ai/objectstack#26843 — the console's New / Edit dialog hands the
11+
* selected form view's `buttons`, `layout`, `defaults`, `defaultTab` and
12+
* `tabPosition` to the `ModalForm`, instead of setting `showSubmit: true`, its
13+
* own labels and `layout: 'vertical'` over them.
14+
*
15+
* The `ModalForm` is a probe recording each schema it is handed; one cell
16+
* renders the real one to show the authored label on the dialog's button.
17+
* CONTROL: an object whose form view authors none of the keys keeps the
18+
* dialog's own labels, both buttons and the vertical layout.
19+
*/
20+
21+
import '@testing-library/jest-dom/vitest';
22+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
23+
import React from 'react';
24+
import { render, cleanup, waitFor, screen } from '@testing-library/react';
25+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
26+
import { registerAllFields } from '@object-ui/fields';
27+
28+
registerAllFields();
29+
30+
const probe = vi.hoisted(() => ({
31+
/** Every schema the global record-form modal was rendered with. */
32+
modalSchemas: [] as any[],
33+
/** Render the real `ModalForm` under the probe. */
34+
realModal: false,
35+
/** The real `ModalForm`, for cells that render a schema of their own. */
36+
RealModalForm: null as null | React.ComponentType<any>,
37+
}));
38+
39+
vi.mock('@object-ui/plugin-form', async (importOriginal) => {
40+
const actual = await importOriginal<Record<string, any>>();
41+
const RealModalForm = actual.ModalForm;
42+
probe.RealModalForm = RealModalForm;
43+
return {
44+
...actual,
45+
ModalForm: (props: any) => {
46+
probe.modalSchemas.push(props.schema);
47+
return probe.realModal ? <RealModalForm {...props} /> : <div data-testid="modal-form" />;
48+
},
49+
};
50+
});
51+
52+
vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
53+
...(await importOriginal<typeof import('@object-ui/plugin-designer')>()),
54+
CreateAppPage: () => <div data-testid="create-app-page" />,
55+
EditAppPage: () => <div data-testid="edit-app-page" />,
56+
DashboardDesignPage: () => <div data-testid="dashboard-design-page" />,
57+
}));
58+
59+
vi.mock('../../layout/ConsoleLayout', () => ({
60+
ConsoleLayout: ({ children }: { children?: React.ReactNode }) => (
61+
<div data-testid="console-layout">{children}</div>
62+
),
63+
}));
64+
vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
65+
vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
66+
vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
67+
vi.mock('../../views/ObjectView', () => ({ ObjectView: () => <div data-testid="object-view" /> }));
68+
vi.mock('../../views/RecordFormPage', () => ({
69+
RecordFormPage: () => <div data-testid="record-form-page" />,
70+
}));
71+
72+
vi.mock('@object-ui/auth', async (importOriginal) => ({
73+
...(await importOriginal<Record<string, unknown>>()),
74+
useAuth: () => ({
75+
user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'user' },
76+
getAuthConfig: async () => ({ features: {} }),
77+
activeOrganization: null,
78+
}),
79+
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
80+
}));
81+
82+
const FIELDS = {
83+
subject: { type: 'text', label: 'Subject' },
84+
status: { type: 'text', label: 'Status' },
85+
account: { type: 'text', label: 'Account' },
86+
};
87+
88+
const AUTHORED = {
89+
name: 'crm_case',
90+
label: 'Case',
91+
fields: FIELDS,
92+
form: {
93+
type: 'tabbed',
94+
layout: 'horizontal',
95+
defaultTab: 'more',
96+
tabPosition: 'left',
97+
buttons: { submit: { label: 'File case' }, cancel: { show: false } },
98+
defaults: { status: 'new', account: 'acct-default' },
99+
sections: [
100+
{ name: 'main', label: 'Main', fields: ['subject'] },
101+
{ name: 'more', label: 'More', fields: ['status', 'account'] },
102+
],
103+
},
104+
};
105+
const PLAIN = { name: 'crm_note', label: 'Note', fields: FIELDS, form: { type: 'simple' } };
106+
const OBJECTS = [AUTHORED, PLAIN];
107+
108+
const dataSourceStub = {
109+
onConnectionStateChange: () => () => {},
110+
getConnectionState: () => 'connected',
111+
getObjectSchema: vi.fn(async (name: string) => OBJECTS.find((o) => o.name === name)),
112+
findOne: vi.fn(async () => ({ id: 'r1' })),
113+
find: vi.fn(async () => ({ data: [] })),
114+
create: vi.fn(),
115+
update: vi.fn(),
116+
};
117+
vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
118+
...(await importOriginal<Record<string, unknown>>()),
119+
useAdapter: () => dataSourceStub,
120+
}));
121+
122+
const APPS = [{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] }];
123+
124+
// One value for the whole run: effects key on these members.
125+
const METADATA = {
126+
apps: APPS,
127+
objects: OBJECTS,
128+
loading: false,
129+
ensureType: undefined,
130+
error: null,
131+
refresh: async () => {},
132+
};
133+
vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({
134+
...(await importOriginal<Record<string, unknown>>()),
135+
useMetadata: () => METADATA,
136+
}));
137+
138+
const ACTION_RUNNER = { execute: () => {}, runner: { registerHandler: () => {}, getContext: () => ({}) } };
139+
vi.mock('@object-ui/react', async (importOriginal) => ({
140+
...(await importOriginal<Record<string, unknown>>()),
141+
useActionRunner: () => ACTION_RUNNER,
142+
useGlobalUndo: () => {},
143+
useMutationInvalidationBridge: () => {},
144+
}));
145+
146+
import { AppContent } from '../AppContent';
147+
148+
const lastModal = () => probe.modalSchemas[probe.modalSchemas.length - 1];
149+
150+
/** Open the record dialog at `url` and return the schema it was handed. */
151+
async function openAt(url: string, objectName: string) {
152+
render(
153+
<MemoryRouter initialEntries={[url]}>
154+
<Routes>
155+
<Route path="/apps/:appName/*" element={<AppContent />} />
156+
</Routes>
157+
</MemoryRouter>,
158+
);
159+
await waitFor(() => expect(lastModal()?.open).toBe(true));
160+
expect(lastModal().objectName).toBe(objectName);
161+
return lastModal();
162+
}
163+
164+
beforeEach(() => {
165+
probe.modalSchemas.length = 0;
166+
probe.realModal = false;
167+
vi.clearAllMocks();
168+
});
169+
afterEach(cleanup);
170+
171+
describe('#26843 — the New dialog renders the form view\'s buttons, layout and defaults', () => {
172+
it('the authored submit label and hidden cancel reach the ModalForm', async () => {
173+
const schema = await openAt('/apps/crm/crm_case?form=new', 'crm_case');
174+
expect(schema).toMatchObject({ showSubmit: true, submitText: 'File case', showCancel: false });
175+
});
176+
177+
it('the authored horizontal layout reaches the ModalForm', async () => {
178+
expect((await openAt('/apps/crm/crm_case?form=new', 'crm_case')).layout).toBe('horizontal');
179+
});
180+
181+
it('defaults seed the create', async () => {
182+
expect((await openAt('/apps/crm/crm_case?form=new', 'crm_case')).initialValues)
183+
.toStrictEqual({ status: 'new', account: 'acct-default' });
184+
});
185+
186+
it('a parent pre-link wins per field over the defaults, and the seed keeps its identity across renders', async () => {
187+
const schema = await openAt('/apps/crm/crm_note?form=new&formObject=crm_case&formLink=account:acct-parent', 'crm_case');
188+
expect(schema.initialValues).toStrictEqual({ status: 'new', account: 'acct-parent' });
189+
const seeds = new Set(probe.modalSchemas.filter((s) => s.open && s.objectName === 'crm_case').map((s) => s.initialValues));
190+
expect(seeds.size).toBe(1);
191+
});
192+
193+
it('the tabbed form view\'s defaultTab and tabPosition reach the ModalForm', async () => {
194+
expect(await openAt('/apps/crm/crm_case?form=new', 'crm_case'))
195+
.toMatchObject({ contentLayout: 'tabbed', defaultTab: 'more', tabPosition: 'left' });
196+
});
197+
198+
it('an edit keeps the buttons and layout and reads no defaults', async () => {
199+
const schema = await openAt('/apps/crm/crm_case?form=r1', 'crm_case');
200+
expect(schema).toMatchObject({ mode: 'edit', submitText: 'File case', showCancel: false, layout: 'horizontal' });
201+
expect(schema.initialValues).toBeUndefined();
202+
});
203+
204+
it('the real dialog draws the authored label and no Cancel', async () => {
205+
probe.realModal = true;
206+
await openAt('/apps/crm/crm_case?form=new', 'crm_case');
207+
const dialog = await screen.findByRole('dialog', undefined, { timeout: 5000 });
208+
await waitFor(() => expect(dialog.querySelector('[data-testid="modal-form-footer"]')).not.toBeNull(), { timeout: 5000 });
209+
expect(screen.getByRole('button', { name: 'File case' })).toBeInTheDocument();
210+
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
211+
});
212+
213+
it('CONTROL: a form view authoring none of them keeps the dialog\'s own chrome', async () => {
214+
const schema = await openAt('/apps/crm/crm_note?form=new', 'crm_note');
215+
expect(schema).toMatchObject({ showSubmit: true, submitText: 'Create', showCancel: true, layout: 'vertical' });
216+
expect(schema.initialValues).toBeUndefined();
217+
expect(schema.contentLayout).toBeUndefined();
218+
});
219+
});

0 commit comments

Comments
 (0)