Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/29354-object-form-record-not-found.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/plugin-form': patch
---

fix(plugin-form): an edit `ObjectForm` in its default layout whose record does not exist shows the record not-found state instead of an empty editable form

Clause-②: no
Metadata-protocol: none

`DataSource.findOne` answers `null` for a record that does not exist (the ObjectStack adapter maps the server's 404 to it). The default `object-form` layout seeded its form from that answer, so editing a deleted or unknown record opened a blank form with an enabled Update button, and the 404 surfaced only after submit. It now draws the record not-found state ("Record not found", the same copy the record page and the modal, drawer, tabbed and wizard forms show) with no fields and no submit, both on the first read and when a background re-read finds the record deleted. Create, and an edit of a record that exists, are unchanged.
27 changes: 22 additions & 5 deletions ui/examples/schema-catalog/test/catalog-gallery-render.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1081,24 +1081,40 @@ describe('objectui#6024 — the derivation this pin is built on', () => {
* it newly admits are admitted by relaxation.
*
* The control is the `plugin-form` entries' own shape with ONE thing changed:
* a `recordId` the fixture does not serve. Same renderer, same object, same
* mode, same harness — so what it measures is the record and nothing else.
* Its controls still render, which is asserted first: without that, a form
* that painted nothing would satisfy the line below while measuring nothing.
* a `recordId` whose record holds none of the fixture's values. Same
* renderer, same object, same mode, same harness — so what it measures is the
* record and nothing else. Its controls still render, which is asserted
* first: without that, a form that painted nothing would satisfy the line
* below while measuring nothing.
*
* That record is an EMPTY one, answered by `findOne` for this case's id only.
* It cannot be a record the fixture lacks: `findOne` answers `null` for such
* an id, and an edit form draws the record not-found state for `null`
* (objectstack#29354), with no controls to measure.
*
* (`mode: 'create'` was tried first and is NOT usable here: it paints its
* shell before the object schema resolves, so `renderEntry` — which settles
* on "something was drawn" — returns with zero controls. The edit path holds
* its first paint until the fetch lands, which is why this shape settles.)
*/
it('the provenance instrument still fails on a surface with no record behind it', async () => {
// An empty record for this case's id alone; every other id reads the fixture.
// Typed as a fixture row because the spy keeps `findOne`'s signature; it
// carries none of a row's values, which is the point.
const findOne = galleryDataSource.findOne;
const EMPTY_RECORD = {} as (typeof USERS_ROWS)[number];
const emptyRecord = vi
.spyOn(galleryDataSource, 'findOne')
.mockImplementation(async (objectName, id) =>
String(id) === 'empty-record' ? EMPTY_RECORD : findOne(objectName, id),
);
// The entries' spelling: the props in the `properties` bag (objectui#10859 batch 4).
const r = await renderEntry({
type: 'object-form',
properties: {
objectName: 'users',
mode: 'edit',
recordId: 'no-such-record',
recordId: 'empty-record',
fields: ['name', 'email', 'department'],
},
});
Expand All @@ -1111,6 +1127,7 @@ describe('objectui#6024 — the derivation this pin is built on', () => {
expect(carriesFixtureRecord(r)).toBe(false);
} finally {
teardown(r);
emptyRecord.mockRestore();
}
});

Expand Down
131 changes: 131 additions & 0 deletions ui/packages/plugin-form/src/ObjectForm.recordNotFound-29354.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* 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.
*/

/**
* An edit `ObjectForm` in its default (`simple`) layout whose record does not
* exist shows the record not-found state, never an empty editable form
* (objectstack#29354; the four other record layouts got the same state in
* objectstack#29157 and objectstack#29247, `recordNotFound-29247.test.tsx`).
*
* `DataSource.findOne` answers `null` for a record that is not there (the
* ObjectStack adapter maps the server's 404 to it). This layout used to seed
* its form from that answer: a blank form with an enabled Update button, whose
* submit then failed against the missing record.
*
* Pinned on the flat and the sectioned render paths: a `null` edit read draws
* the not-found state (the console's shared `empty.recordNotFound` copy) with
* no field and no Update button, on the first read and on a background re-read
* that finds the record deleted. Controls: a found record and a create still
* draw the form.
*/
import React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, act, cleanup } from '@testing-library/react';
import { notifyDataChanged } from '@object-ui/react';
import { registerAllFields } from '@object-ui/fields';
import type { DataSource } from '@object-ui/types';
import { ObjectForm, type ObjectFormComponentProps } from './ObjectForm';

registerAllFields();

afterEach(() => cleanup());

const NOT_FOUND_TITLE = 'Record not found';
const NOT_FOUND_DESCRIPTION =
'The record you are looking for does not exist, may have been deleted, or you may not have access to it.';

function makeDS(record: Record<string, unknown> | null) {
return {
getObjectSchema: vi.fn().mockResolvedValue({
name: 'task',
fields: { title: { type: 'text', label: 'Title' } },
}),
findOne: vi.fn().mockResolvedValue(record),
find: vi.fn().mockResolvedValue({ data: [] }),
create: vi.fn(async (_o: string, d: Record<string, unknown>) => ({ id: 'n1', ...d })),
update: vi.fn(async (_o: string, id: string, d: Record<string, unknown>) => ({ id, ...d })),
};
}

// The default layout draws a flat field list, or its sections when it has any.
const SHAPES = [
['flat', {}],
['sectioned', { sections: [{ name: 'basics', label: 'Basics', fields: ['title'] }] }],
] as const;

function open(
shape: Record<string, unknown>,
ds: ReturnType<typeof makeDS>,
mode: 'edit' | 'create',
recordId?: string,
) {
const schema = {
type: 'object-form',
objectName: 'task',
mode,
recordId,
fields: ['title'],
...shape,
};
render(<ObjectForm schema={schema as ObjectFormComponentProps['schema']} dataSource={ds as unknown as DataSource} />);
}

const titleBox = () =>
document.body.querySelector<HTMLInputElement>('[data-field="title"] input');
const button = (label: string) => screen.queryByRole('button', { name: label });

describe.each(SHAPES)('ObjectForm (%s) — an edit read that finds no record (objectstack#29354)', (_name, shape) => {
it('draws the not-found state with no field and no Update button', async () => {
const ds = makeDS(null);
open(shape, ds, 'edit', 'NOPE_x');

expect(await screen.findByText(NOT_FOUND_TITLE)).toBeInTheDocument();
expect(screen.getByText(NOT_FOUND_DESCRIPTION)).toBeInTheDocument();
expect(screen.getByTestId('simple-form-record-not-found')).toBeInTheDocument();
expect(ds.findOne).toHaveBeenCalledWith('task', 'NOPE_x');
expect(titleBox()).toBeNull();
expect(button('Update')).toBeNull();
// Not the generic load-failure screen: nothing failed to load.
expect(screen.queryByText('Error loading form')).toBeNull();
});

it('draws the not-found state when a background re-read finds the record deleted', async () => {
const ds = makeDS({ id: 't1', title: 'Write report' });
open(shape, ds, 'edit', 't1');
await waitFor(() => expect(titleBox()?.value).toBe('Write report'));

ds.findOne.mockResolvedValue(null);
await act(async () => {
notifyDataChanged({ objectName: 'task', recordId: 't1' });
});

expect(await screen.findByText(NOT_FOUND_TITLE)).toBeInTheDocument();
expect(titleBox()).toBeNull();
expect(button('Update')).toBeNull();
});

it('control: a found record still draws its form and the Update button', async () => {
const ds = makeDS({ id: 't1', title: 'Write report' });
open(shape, ds, 'edit', 't1');

await waitFor(() => expect(titleBox()?.value).toBe('Write report'));
expect(button('Update')).not.toBeNull();
expect(screen.queryByText(NOT_FOUND_TITLE)).toBeNull();
});

it('control: a create draws an empty form, with no read', async () => {
const ds = makeDS(null);
open(shape, ds, 'create');

await waitFor(() => expect(titleBox()).not.toBeNull());
expect(titleBox()?.value).toBe('');
expect(button('Create')).not.toBeNull();
expect(ds.findOne).not.toHaveBeenCalled();
expect(screen.queryByText(NOT_FOUND_TITLE)).toBeNull();
});
});
13 changes: 13 additions & 0 deletions ui/packages/plugin-form/src/ObjectForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ import {
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -859,6 +861,14 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
try {
const data = await dataSource.findOne(schema.objectName, schema.recordId);
if (cancelled) return;
// `findOne` answers `null` for a record that does not exist: there is
// nothing to edit, so the read failed, and the form is not seeded. On a
// bus re-read this is the record deleted while the form is open, drawn
// the same way.
if (data == null) {
run.fail(new RecordNotFoundError(schema.objectName, schema.recordId));
return;
}
// Tagged with the object and record it was read for, so a save that
// runs against a different one finds no baseline and sends everything.
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
Expand Down Expand Up @@ -1500,6 +1510,9 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});

// Render error state
if (error instanceof RecordNotFoundError) {
return <RecordNotFoundState testId="simple-form-record-not-found" />;
}
if (error) {
return (
<div className="p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md">
Expand Down
4 changes: 2 additions & 2 deletions ui/packages/plugin-form/src/loadFailure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ const useRecordNotFoundTranslation = createSafeTranslation(
* What a record form draws in place of its form for a `RecordNotFoundError`:
* the record not-found state, never the "Error loading form" box (nothing
* failed to load) and never an empty form. One drawing for every layout that
* reads a record (`ModalForm`, `DrawerForm`, `TabbedForm`, `WizardForm`), so
* each host shows the same state. The caller draws no footer or submit beside
* reads a record (`ObjectForm`'s default arm, `ModalForm`, `DrawerForm`,
* `TabbedForm`, `WizardForm`), so each host shows the same state. The caller draws no footer or submit beside
* it: each already keeps those off while a load failure is shown.
*/
export function RecordNotFoundState({ testId }: { testId: string }): ReactElement {
Expand Down
Loading