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/29157-modal-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 `ModalForm` 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 edit dialog seeded its form with `{}` from that answer, so the console's `?form=ID` overlay for a deleted or unknown record opened a blank form with an enabled Update button, and the 404 surfaced only after submit. The dialog now draws the console's record not-found state ("Record not found", the same copy the record page shows) with no fields and no footer, 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.
113 changes: 113 additions & 0 deletions ui/packages/plugin-form/src/ModalForm.recordNotFound-29157.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* 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 `ModalForm` whose record does not exist shows the record not-found
* state, never an empty editable form (objectstack#29157).
*
* The console's `?form=ID` overlay mounts this dialog with `mode: 'edit'` and
* the id from the URL. `DataSource.findOne` answers `null` for a record that is
* not there (the ObjectStack adapter maps the server's 404 to it), and the
* dialog used to seed the form with `{}` from that answer: a blank form with an
* enabled Update button, whose submit then failed against the missing record.
*
* Pinned here: a `null` edit read draws the not-found state (the console's
* shared `empty.recordNotFound` copy) with no field and no Update button, both
* on the first read and on a background re-read that finds the record deleted.
* Controls: a create and a found record still draw the form.
*/
import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor, act } from '@testing-library/react';
import { notifyDataChanged } from '@object-ui/react';
import { registerAllFields } from '@object-ui/fields';
import { ModalForm, type ModalFormProps, type ModalFormSchema } from './ModalForm';

registerAllFields();

function makeDS(record: Record<string, unknown> | null) {
return {
getObjectSchema: vi.fn().mockResolvedValue({
name: 'showcase_category',
fields: { name: { type: 'text', label: 'Name' } },
}),
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 })),
};
}

function open(ds: ReturnType<typeof makeDS>, mode: 'edit' | 'create', recordId?: string) {
const schema: ModalFormSchema = {
type: 'object-form',
formType: 'modal',
objectName: 'showcase_category',
mode,
recordId,
title: mode === 'edit' ? 'Edit Category' : 'New Category',
open: true,
};
render(<ModalForm schema={schema} dataSource={ds as unknown as ModalFormProps['dataSource']} />);
}

const nameBox = () => document.body.querySelector('input[name="name"]') as HTMLInputElement | null;
const submitButton = (label: string) => screen.queryByRole('button', { name: label });

describe('ModalForm — an edit read that finds no record (objectstack#29157)', () => {
it('draws the not-found state with no field and no Update button', async () => {
const ds = makeDS(null);
open(ds, 'edit', 'NOPE_x');

expect(await screen.findByText('Record not found')).toBeInTheDocument();
expect(
screen.getByText(
'The record you are looking for does not exist, may have been deleted, or you may not have access to it.',
),
).toBeInTheDocument();
expect(ds.findOne).toHaveBeenCalledWith('showcase_category', 'NOPE_x');
expect(nameBox()).toBeNull();
expect(submitButton('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: 'c1', name: 'Books' });
open(ds, 'edit', 'c1');
await waitFor(() => expect(nameBox()?.value).toBe('Books'));

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

expect(await screen.findByText('Record not found')).toBeInTheDocument();
expect(nameBox()).toBeNull();
expect(submitButton('Update')).toBeNull();
});

it('control: a found record still draws its form and the Update button', async () => {
const ds = makeDS({ id: 'c1', name: 'Books' });
open(ds, 'edit', 'c1');

await waitFor(() => expect(nameBox()?.value).toBe('Books'));
expect(submitButton('Update')).not.toBeNull();
expect(screen.queryByText('Record not found')).toBeNull();
});

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

await waitFor(() => expect(nameBox()).not.toBeNull());
expect(submitButton('Create')).not.toBeNull();
expect(ds.findOne).not.toHaveBeenCalled();
expect(screen.queryByText('Record not found')).toBeNull();
});
});
22 changes: 22 additions & 0 deletions ui/packages/plugin-form/src/ModalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ import {
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
Empty,
EmptyTitle,
EmptyDescription,
toast,
} from '@object-ui/components';
import { Loader2 } from 'lucide-react';
Expand Down Expand Up @@ -73,6 +76,7 @@ import { usePermissions } from '@object-ui/permissions';
import { useOccSave } from './occSave';
import {
NO_LOAD_FAILURES,
RecordNotFoundError,
beginLoadRun,
shownLoadFailure,
type LoadFailures,
Expand Down Expand Up @@ -109,6 +113,10 @@ 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 @@ -611,6 +619,12 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
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 || {});
Expand Down Expand Up @@ -904,6 +918,14 @@ 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>
);
}
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
Expand Down
14 changes: 14 additions & 0 deletions ui/packages/plugin-form/src/loadFailure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,17 @@ export function beginLoadRun(
export function shownLoadFailure(failures: LoadFailures): Error | null {
return failures.schema || failures.record;
}

/**
* The record read answered "no such record": `DataSource.findOne` resolves
* `null` for it (the ObjectStack adapter maps the server's 404 to that). An
* edit form has nothing to edit then, so the read is a failure like any other,
* drawn as the record not-found state rather than as an empty form whose
* submit can only be refused.
*/
export class RecordNotFoundError extends Error {
constructor(readonly objectName: string, readonly recordId: string) {
super(`Record ${recordId} not found in ${objectName}`);
this.name = 'RecordNotFoundError';
}
}
Loading