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
14 changes: 14 additions & 0 deletions .changeset/29021-unknown-section-field-draws-nothing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/plugin-form': patch
---

fix(plugin-form): a form section naming a field the object does not have draws no control

Clause-②: no
Metadata-protocol: none

A form view section that names a field the object does not declare (a typo, or a field deleted later) used to draw a live text box labelled with the raw name on the `tabbed`, `wizard`, `drawer` and `modal` layouts. Whatever the user typed there was never saved: the record save writes only declared fields, so the value was dropped behind a successful save. Those layouts now draw nothing for such a name, which is what the `form-field-unknown` lint already says ("never renders on the form") and what the default (`simple`) layout already did.

A `customFields` member or a self-describing inline field (one carrying its own `name`) is still drawn, as before. A form with no object schema at all, such as one mounted without a data source whose `submitHandler` owns the write, keeps its bare input for a named field: there is no object to call the name unknown. A section whose every field is unknown is left empty, and each layout treats it as it already treats an empty section.

Fix the field name in the form view, or add the field to the object, to bring the control back.
Original file line number Diff line number Diff line change
Expand Up @@ -236,47 +236,45 @@ describe('normalizeSectionField decides the widget from the effective pair (obje
};

it('a string shorthand for a multi select resolves to the multi widget', () => {
expect(normalizeSectionField('regions', ctx).type).toBe('field:multiselect');
expect(normalizeSectionField('regions', ctx)!.type).toBe('field:multiselect');
});

it('a spec field def naming a multi select resolves to the multi widget', () => {
expect(normalizeSectionField({ field: 'regions' }, ctx).type).toBe('field:multiselect');
expect(normalizeSectionField({ field: 'regions' }, ctx)!.type).toBe('field:multiselect');
});

it('a view that restates only `multiple: true` moves the widget too', () => {
// The second door onto the same defect: `multiple` is a spec FormField key,
// so a view can turn a single-value object field into a multi one without
// restating `type`. Resolving the id from `fd.type` before `multiple` had
// been merged would have left this on the single-value widget.
expect(normalizeSectionField({ field: 'stage', multiple: true }, ctx).type).toBe('field:multiselect');
expect(normalizeSectionField({ field: 'stage', multiple: true }, ctx)!.type).toBe('field:multiselect');
});

it('a view that restates only `multiple: false` moves it BACK', () => {
// The inverse, which the same single computation buys: an object-level multi
// field narrowed by the view must land on the single-value widget, whose
// label association is the `for` one.
const f = normalizeSectionField({ field: 'regions', multiple: false }, ctx);
const f = normalizeSectionField({ field: 'regions', multiple: false }, ctx)!;
expect(f.type).toBe('field:select');
expect(f.multiple).toBe(false);
});

it('a view restating both keys agrees with the mapper', () => {
expect(normalizeSectionField({ field: 'stage', type: 'select', multiple: true }, ctx).type).toBe(
expect(normalizeSectionField({ field: 'stage', type: 'select', multiple: true }, ctx)!.type).toBe(
mapFieldTypeToFormType('select', { multiple: true }),
);
});

it('a single-value select is untouched', () => {
expect(normalizeSectionField({ field: 'stage' }, ctx).type).toBe('field:select');
expect(normalizeSectionField('stage', ctx).type).toBe('field:select');
expect(normalizeSectionField({ field: 'stage' }, ctx)!.type).toBe('field:select');
expect(normalizeSectionField('stage', ctx)!.type).toBe('field:select');
});

it('a spec field naming nothing in the object schema keeps its fallback type', () => {
// `fromObjectSchema`'s `input` fallback, unchanged: with no type on either
// side there is nothing to decide, and `multiple` alone must not conjure a
// widget id.
const f = normalizeSectionField({ field: 'ghost', multiple: true }, ctx);
expect(f.type).toBe('input');
expect(f.multiple).toBe(true);
it('a spec field naming nothing in the object schema builds no field at all', () => {
// `fromObjectSchema` no longer falls back to an untyped `input` stub for a
// name the object does not declare (objectstack#29021): `multiple` alone
// must not conjure a widget id, nor a control.
expect(normalizeSectionField({ field: 'ghost', multiple: true }, ctx)).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* 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.
*
* A form view section naming a field the object does not have draws NOTHING
* for it (objectstack#29021).
*
* ## What went wrong
*
* `fromObjectSchema` (`sectionFields.ts`) answered a name the object does not
* declare with a bare `{ name, label: name, type: 'input' }` stub. Every arm
* that builds a section without a field pool — `tabbed`, `wizard`, `drawer`,
* `modal` — drew it as a live text box labelled with the raw name, so a form
* view naming a mistyped or deleted field showed the user an editable box.
* Whatever was typed there never reached the record: the save writes only
* declared fields, so it was dropped behind a 200 with no error. The lint
* already calls such an entry `FORM_FIELD_UNKNOWN` — "silently skipped and
* never renders on the form" — and the default arm's pool already dropped it;
* these four arms disagreed with both.
*
* ## The rows
*
* Per arm, on an EDIT form of a real record, a section listing a known field
* beside an unknown one in BOTH named shapes (a bare name and the spec
* `{ field }` object):
*
* 1. only the known field is drawn — no control, no label for the unknown
* name (the known field's own input is the non-vacuity control);
* 2. editing the known field and saving sends no key for the unknown name,
* and the known field's edit does arrive.
*
* A section whose EVERY member is unknown builds no field; what each arm does
* with an empty section is its own existing behaviour and not re-pinned here.
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, waitFor, fireEvent, screen, cleanup } from '@testing-library/react';
import React from 'react';
import { registerAllFields } from '@object-ui/fields';
import { ObjectFormContainer } from '../ObjectFormContainer';
import '../index';

vi.mock('@object-ui/components/ui/sonner', async (orig) => {
const actual = await (orig as any)();
return { ...actual, toast: { ...actual.toast, success: vi.fn(), error: vi.fn() } };
});

registerAllFields();

const TASK_OBJECT = {
name: 'task',
fields: {
title: { type: 'text', label: 'Title' },
notes: { type: 'text', label: 'Notes' },
},
};

const RECORD = { id: 't1', title: 'Old title', notes: 'kept' };

/** The four arms that build a section with no field pool. */
const ARMS = ['tabbed', 'wizard', 'drawer', 'modal'] as const;

let dataSource: any;

beforeEach(() => {
dataSource = {
getObjectSchema: vi.fn().mockResolvedValue(TASK_OBJECT),
find: vi.fn().mockResolvedValue({ data: [] }),
findOne: vi.fn().mockResolvedValue({ ...RECORD }),
create: vi.fn().mockResolvedValue({ id: 't1' }),
update: vi.fn().mockResolvedValue({ ...RECORD }),
delete: vi.fn(),
bulk: vi.fn(),
};
});

afterEach(() => {
cleanup();
vi.restoreAllMocks();
});

function renderArm(formType: (typeof ARMS)[number]) {
render(
<ObjectFormContainer
schema={{
type: 'object-form',
objectName: 'task',
mode: 'edit',
recordId: 't1',
formType,
open: true,
submitText: 'Save Now',
sections: [
{
name: 'overview',
label: 'Overview',
fields: ['title', 'no_such_field', { field: 'other_ghost', label: 'Other ghost' }],
},
],
} as any}
dataSource={dataSource}
/>,
);
}

async function knownInput(): Promise<HTMLInputElement> {
return waitFor(() => {
const el = document.querySelector('input[name="title"]') as HTMLInputElement | null;
if (!el) throw new Error('the known field never rendered — the absences below would pass vacuously');
expect(el.value).toBe('Old title');
return el;
});
}

describe.each(ARMS)('formType `%s`: a section member the object does not have', (formType) => {
it('draws only the known field — no control and no label for the unknown names', async () => {
renderArm(formType);
await knownInput();

expect(document.querySelector('[name="no_such_field"]')).toBeNull();
expect(document.querySelector('[name="other_ghost"]')).toBeNull();
expect(screen.queryByText('no_such_field')).toBeNull();
expect(screen.queryByText('Other ghost')).toBeNull();
});

it('editing and saving the record sends no key for the unknown names', async () => {
renderArm(formType);
const title = await knownInput();

fireEvent.change(title, { target: { value: 'New title' } });
fireEvent.click(screen.getByRole('button', { name: /save now/i }));

await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1));
const [objectName, id, payload] = dataSource.update.mock.calls[0];
expect(objectName).toBe('task');
expect(id).toBe('t1');
expect(payload).toMatchObject({ title: 'New title' });
expect(payload).not.toHaveProperty('no_such_field');
expect(payload).not.toHaveProperty('other_ghost');
});
});
13 changes: 8 additions & 5 deletions ui/packages/plugin-form/src/flatFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export interface FlatFieldsContext extends SectionFieldsContext {
* fields flat (no sections).
*
* Fields the object schema does not declare are SKIPPED — the flat containers
* have always dropped them rather than rendering `fromObjectSchema`'s bare
* `input` stub, and a whitelist naming a field the object does not have is an
* have always dropped them (`fromObjectSchema` builds nothing for them, and
* the sectioned arms drop them too), and a whitelist naming a field the object does not have is an
* authoring error the form should not paper over with an untyped control. A
* `customFields` member naming such a field is drawn in its place: the member
* is a whole definition, not an untyped stub.
Expand All @@ -81,11 +81,14 @@ export function buildFlatFields(ctx: FlatFieldsContext): FormField[] {
}

return mergeCustomFields(names, ctx.customFields, (name) => {
const field = ctx.objectSchema?.fields?.[name];
if (!field) return undefined;
// `fromObjectSchema` answers `undefined` for a name the object does not
// declare, so the skip below is its own answer, not a second check.
const built = fromObjectSchema(name, ctx);
if (!built) return undefined;
const field = ctx.objectSchema.fields[name];

return {
...fromObjectSchema(name, ctx),
...built,
// Field-group membership (Field.group → object.fieldGroups[].key), read
// by `deriveFieldGroupSections` for the fieldGroups fallback. Carried
// HERE and not in `fromObjectSchema` because that fallback only ever runs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const CHAINS: Array<readonly [string, (pred: unknown, name: string) => ReturnTyp
describe.each(CHAINS)('attachVisibility via %s (objectui#11262, ADR-0137 D4)', (_chain, build) => {
it.each(BLANKS)('%s: no gate on the runtime field, as before — and a [blank] report naming the field', (_label, pred) => {
const name = fresh('blank');
const f = build(pred, name);
const f = build(pred, name)!;
expect(f.name).toBe(name);
expect((f as { visibleOn?: unknown }).visibleOn).toBeUndefined();
const lines = blankLines();
Expand Down Expand Up @@ -139,7 +139,7 @@ describe.each([
...BLANKS,
] as const)('%s: no view-level gate on the runtime field, and silent', (_label, pred) => {
const name = fresh('retired');
const f = normalizeSectionField(name, ctxWith(name, { [key]: pred }));
const f = normalizeSectionField(name, ctxWith(name, { [key]: pred }))!;
expect(f.name).toBe(name);
expect((f as { visibleOn?: unknown }).visibleOn).toBeUndefined();
expect(warn).not.toHaveBeenCalled();
Expand Down
13 changes: 9 additions & 4 deletions ui/packages/plugin-form/src/sectionFields.spec-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ const objectSchema = {
label: 'Industry',
options: [{ label: 'Tech', value: 'tech' }],
},
// A bare declared field: no label, options, help or rules of its own, so
// every override below lands on it verbatim. A name the object does not
// declare builds no field at all (objectstack#29021), so it cannot be the
// blank slate this table writes on.
plain: { type: 'number' },
},
};

Expand All @@ -60,10 +65,10 @@ const ctx = {
fieldLabel: (_obj: string, _name: string, fallback: string) => fallback || _name,
};

/** Normalize a spec field def against a schema that does NOT define `ghost`,
* so every override is observable verbatim (no object-metadata interference). */
/** Normalize a spec field def onto the bare declared `plain` field, so every
* override is observable verbatim (no object-metadata interference). */
const norm = (def: Record<string, unknown>) =>
normalizeSectionField({ field: 'ghost', ...def }, ctx) as any;
normalizeSectionField({ field: 'plain', ...def }, ctx) as any;

/**
* One row per spec FormFieldSchema key: sample authored value → where the
Expand Down Expand Up @@ -109,7 +114,7 @@ const TABLE: Record<string, (f: (def: Record<string, unknown>) => any) => void>
immutable: (f) => {
// Locked once the record exists: an edit form draws it disabled, a create
// form leaves it editable, and no `immutable` key is carried (objectstack#25923).
const edit = normalizeSectionField({ field: 'ghost', immutable: true }, { ...ctx, mode: 'edit', recordId: 'r1' }) as any;
const edit = normalizeSectionField({ field: 'plain', immutable: true }, { ...ctx, mode: 'edit', recordId: 'r1' }) as any;
expect(edit.disabled).toBe(true);
expect(edit.immutable).toBeUndefined();
expect(f({ immutable: true }).disabled).toBeFalsy();
Expand Down
Loading
Loading