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/29247-record-forms-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 `DrawerForm`, `TabbedForm` or `WizardForm` 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 drawer, tabbed and wizard form layouts seeded their form with `{}` 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. They now draw the record not-found state ("Record not found", the same copy the record page and the `ModalForm` overlay show) with no fields and no submit, both on the first read and when a background re-read finds the record deleted. All four record form layouts draw that state from one shared private component. Create, and an edit of a record that exists, are unchanged.
13 changes: 12 additions & 1 deletion ui/packages/plugin-form/src/DrawerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ import { usePermissions } from '@object-ui/permissions';
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -443,9 +445,15 @@ const DrawerFormBody: React.FC<DrawerFormProps> = ({
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.
if (data == null) {
run.fail(new RecordNotFoundError(schema.objectName, schema.recordId));
return;
}
loadedRecordIdRef.current = schema.recordId;
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
setFormData(data || {});
setFormData(data);
// The record on screen is the one this run read, so an earlier record
// read's failure no longer describes it. A schema failure stays: this
// read says nothing about the object's fields.
Expand Down Expand Up @@ -775,6 +783,9 @@ const DrawerFormBody: React.FC<DrawerFormProps> = ({
};

const renderContent = () => {
if (error instanceof RecordNotFoundError) {
return <RecordNotFoundState testId="drawer-form-record-not-found" />;
}
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
Expand Down
15 changes: 2 additions & 13 deletions ui/packages/plugin-form/src/ModalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ import {
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
Empty,
EmptyTitle,
EmptyDescription,
toast,
} from '@object-ui/components';
import { Loader2 } from 'lucide-react';
Expand Down Expand Up @@ -77,6 +74,7 @@ import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -113,10 +111,6 @@ const useDiscardTranslation = createSafeTranslation(
// The footer's declared Reset button (objectstack#27247).
'common.reset': 'Reset',
'form.errorLoading': 'Error loading form',
// The record not-found state, the console's shared copy (the same keys and
// values `RecordDetailView` draws), for an edit read that finds no record.
'empty.recordNotFound': 'Record not found',
'empty.recordNotFoundDescription': 'The record you are looking for does not exist, may have been deleted, or you may not have access to it.',
},
'form.discardTitle',
);
Expand Down Expand Up @@ -919,12 +913,7 @@ const ModalFormBody: React.FC<ModalFormProps> = ({

const renderContent = () => {
if (error instanceof RecordNotFoundError) {
return (
<Empty data-testid="modal-form-record-not-found">
<EmptyTitle>{t('empty.recordNotFound')}</EmptyTitle>
<EmptyDescription>{t('empty.recordNotFoundDescription')}</EmptyDescription>
</Empty>
);
return <RecordNotFoundState testId="modal-form-record-not-found" />;
}
if (error) {
return (
Expand Down
13 changes: 12 additions & 1 deletion ui/packages/plugin-form/src/TabbedForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { sectionedGridLayout } from './autoLayout';
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -410,9 +412,15 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
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.
if (data == null) {
run.fail(new RecordNotFoundError(schema.objectName, schema.recordId));
return;
}
loadedRecordIdRef.current = schema.recordId;
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
setFormData(data || {});
setFormData(data);
// The record on screen is the one this run read, so an earlier record
// read's failure no longer describes it. A schema failure stays: this
// read says nothing about the object's fields.
Expand Down Expand Up @@ -581,6 +589,9 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
return section.name || section.label || `tab-${index}`;
};

if (error instanceof RecordNotFoundError) {
return <RecordNotFoundState testId="tabbed-form-record-not-found" />;
}
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
Expand Down
15 changes: 13 additions & 2 deletions ui/packages/plugin-form/src/WizardForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import {
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
RecordNotFoundState,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -673,10 +675,16 @@ export const WizardForm: React.FC<WizardFormProps> = ({
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.
if (data == null) {
run.fail(new RecordNotFoundError(schema.objectName, schema.recordId));
return;
}
loadedRecordIdRef.current = schema.recordId;
loadedRecordRef.current = snapshotLoadedRecord(schema, data);
setFormData(data || {});
setPersistedRecord(data || {});
setFormData(data);
setPersistedRecord(data);
// What the wizard holds is now the record as read: no step's answer is
// unsaved (objectui#10715).
unsavedStepValuesRef.current = false;
Expand Down Expand Up @@ -1198,6 +1206,9 @@ export const WizardForm: React.FC<WizardFormProps> = ({
}
}, [canOpenStep, goToStep]);

if (error instanceof RecordNotFoundError) {
return <RecordNotFoundState testId="wizard-form-record-not-found" />;
}
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
Expand Down
44 changes: 43 additions & 1 deletion ui/packages/plugin-form/src/loadFailure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,16 @@
*
* Private to this package: no form's props or schema change.
*/
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
import {
createElement,
type ComponentProps,
type Dispatch,
type MutableRefObject,
type ReactElement,
type SetStateAction,
} from 'react';
import { Empty, EmptyTitle, EmptyDescription } from '@object-ui/components';
import { createSafeTranslation } from '@object-ui/i18n';

/** The two reads a record form makes before it can draw. */
export type LoadSource = 'schema' | 'record';
Expand Down Expand Up @@ -97,3 +106,36 @@ export class RecordNotFoundError extends Error {
this.name = 'RecordNotFoundError';
}
}

// The record not-found copy: the console's shared keys, with the values
// `RecordDetailView` draws. A provider-less host (a standalone embed, this
// package's own tests) reads this table; `pnpm check:i18n-keys` holds it to the
// `en` pack.
const useRecordNotFoundTranslation = createSafeTranslation(
{
'empty.recordNotFound': 'Record not found',
'empty.recordNotFoundDescription': 'The record you are looking for does not exist, may have been deleted, or you may not have access to it.',
},
'empty.recordNotFound',
);

/**
* 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
* it: each already keeps those off while a load failure is shown.
*/
export function RecordNotFoundState({ testId }: { testId: string }): ReactElement {
const { t } = useRecordNotFoundTranslation();
// A `data-*` attribute is legal on the `div` that `Empty` renders, but only
// JSX spells it without a declared prop: named in the props type here.
const props: ComponentProps<typeof Empty> & { 'data-testid': string } = { 'data-testid': testId };
return createElement(
Empty,
props,
createElement(EmptyTitle, null, t('empty.recordNotFound')),
createElement(EmptyDescription, null, t('empty.recordNotFoundDescription')),
);
}
145 changes: 145 additions & 0 deletions ui/packages/plugin-form/src/recordNotFound-29247.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/**
* 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 `DrawerForm`, `TabbedForm` or `WizardForm` whose record does not
* exist shows the record not-found state, never an empty editable form
* (objectstack#29247; `ModalForm` got the same state in objectstack#29157).
*
* `DataSource.findOne` answers `null` for a record that is not there (the
* ObjectStack adapter maps the server's 404 to it). Each of these layouts used
* to seed its form with `{}` from that answer: a blank form with an enabled
* Update button, whose submit then failed against the missing record.
*
* Pinned per layout: 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 { DrawerForm } from './DrawerForm';
import { TabbedForm } from './TabbedForm';
import { WizardForm } from './WizardForm';

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 layouts under test, as one type. They share no props base (each schema
* is pinned to its own `formType` literal), so the parametrised surface is
* named here: the same two props against each, `schema` deliberately `any`,
* with the `formType` each case passes checked by the tuple below. The same
* shape and reason as `recordSwapLoading.test.tsx`.
*/
type RecordFormLayout = React.ComponentType<{ schema: any; dataSource?: DataSource }>;

const LAYOUTS: ReadonlyArray<readonly [string, RecordFormLayout, 'drawer' | 'tabbed' | 'wizard']> = [
['DrawerForm', DrawerForm, 'drawer'],
['TabbedForm', TabbedForm, 'tabbed'],
// A wizard step is a section, so the one section is its one step.
['WizardForm', WizardForm, 'wizard'],
];

function open(
Form: RecordFormLayout,
formType: 'drawer' | 'tabbed' | 'wizard',
ds: ReturnType<typeof makeDS>,
mode: 'edit' | 'create',
recordId?: string,
) {
const schema = {
type: 'object-form',
formType,
objectName: 'task',
mode,
recordId,
sections: [{ name: 'basics', label: 'Basics', fields: ['title'] }],
// The drawer only.
open: true,
onOpenChange: vi.fn(),
};
render(<Form schema={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(LAYOUTS)('%s — an edit read that finds no record (objectstack#29247)', (_name, Form, formType) => {
it('draws the not-found state with no field and no Update button', async () => {
const ds = makeDS(null);
open(Form, formType, ds, 'edit', 'NOPE_x');

expect(await screen.findByText(NOT_FOUND_TITLE)).toBeInTheDocument();
expect(screen.getByText(NOT_FOUND_DESCRIPTION)).toBeInTheDocument();
expect(screen.getByTestId(`${formType}-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(Form, formType, 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(Form, formType, 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(Form, formType, 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();
});
});
Loading