diff --git a/.changeset/34807-draft-preview-form-fields.md b/.changeset/34807-draft-preview-form-fields.md new file mode 100644 index 00000000000..1a4f4e56085 --- /dev/null +++ b/.changeset/34807-draft-preview-form-fields.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-form': patch +--- + +fix(console): under draft preview, the New record form draws a field that exists only in the draft, disabled, and never writes it + +Clause-②: no +Metadata-protocol: none + +Under `?preview=draft` the console reads metadata from the draft overlay, so the New record page and the global New/Edit modal listed a field the draft adds. Its definition, though, came from the adapter's published `getObjectSchema`, which does not declare it, so the form dropped it. In draft preview both surfaces now hand the form a data source that answers the published object definition plus each field only the draft declares, with its draft definition and the marker `_draftOnly: true`; the form draws such a field disabled and does not require it (its draft `required` / `requiredWhen` are dropped from that copy, so a required draft field cannot make the save refuse), and the data source leaves it out of the record a create or update sends, so neither a value nor its declared default is written. The data door validates against the published object, and preview keeps the data plane untouched (ADR-0037 Phase 1). Outside preview the form gets the adapter itself, so the published path is unchanged and still reads each object document once. A draft list column on a draft-only field is not covered here. + +`@object-ui/plugin-form`: `ObjectForm` and the shared object-schema field mapping draw a field carrying `_draftOnly: true` disabled, and a form view restating `required` over such a field does not make it required. `_draftOnly` is an underscore-private convention between the console and this package, never an authoring key; nothing new is exported. diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index a7f2bae5226..041af0e3032 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -23,6 +23,7 @@ import { useMetadata } from '../providers/MetadataProvider.js'; import { BUNDLE_MISS, useBundledReads } from '../providers/bundledReads.js'; import { useAdapter } from '../providers/AdapterProvider.js'; import { usePreviewDrafts } from '../preview/PreviewModeContext.js'; +import { usePreviewFormDataSource } from '../utils/previewFormDataSource.js'; import { PreviewDraftEmptyState } from '../preview/PreviewDraftEmptyState.js'; import { ExpressionProvider, @@ -361,6 +362,11 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = // worse answer than the literal it replaced. const homePath = useHomePath(); const previewDrafts = usePreviewDrafts(); + // objectstack#34807 — the global New/Edit modal reads its object definition + // through the draft overlay under preview (a field only the draft declares is + // drawn disabled and left out of every write); outside preview this is + // `dataSource` itself. + const formDataSource = usePreviewFormDataSource(dataSource); const { t, language } = useObjectTranslation(); const { objectLabel, objectPluralLabel } = useObjectLabel(); @@ -1794,7 +1800,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = }, ), }} - dataSource={dataSource} + dataSource={formDataSource ?? undefined} /> )} diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx new file mode 100644 index 00000000000..000bdc22f6b --- /dev/null +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -0,0 +1,297 @@ +/** + * 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. + */ + +/** + * The record form's data source under draft preview (objectstack#34807). + * + * - In preview, `getObjectSchema` answers the published document plus each + * field only the draft overlay declares, marked draft-only; the + * adapter's sortability projection survives the copy, and the proxy's + * writes leave a draft-only name out of the record. + * - The real `ModalForm` (the console's global New/Edit modal) draws such a + * field DISABLED, and Save leaves it out of the create, its declared + * default included. + * - CONTROL: outside preview the hook returns the adapter itself, so the form + * reads the published document through one adapter read (objectui#13044) + * and never draws the draft field. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent, renderHook } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { registerAllFields } from '@object-ui/fields'; +import { ModalForm } from '@object-ui/plugin-form'; +import { MetadataNotFoundError } from '@object-ui/data-objectstack'; +import { PreviewModeProvider } from '../preview/PreviewModeContext'; +import { attachObjectSortability, readObjectSortability } from '@object-ui/core'; +import { + DRAFT_ONLY_FIELD_KEY, + createPreviewFormDataSource, + usePreviewFormDataSource, + withDraftOnlyFields, +} from './previewFormDataSource'; + +registerAllFields(); + +const { GET_ITEM } = vi.hoisted(() => ({ GET_ITEM: { fn: null as null | ((type: string, name: string) => Promise) } })); + +vi.mock('../providers/MetadataProvider', async (importOriginal) => { + const getItem = (type: string, name: string) => GET_ITEM.fn!(type, name); + return { + ...(await importOriginal>()), + useMetadata: () => ({ objects: [], loading: false, getItem }), + }; +}); + +const PUBLISHED = { + name: 'tracker_task', + fields: { title: { type: 'text', label: 'Title' } }, +}; +const OVERLAY = { + name: 'tracker_task', + fields: { + title: { type: 'text', label: 'Task title' }, + priority: { type: 'text', label: 'Priority', defaultValue: 'high' }, + }, +}; +// A draft that adds a REQUIRED field with no default, and a conditional one. +const REQUIRED_OVERLAY = { + name: 'tracker_task', + fields: { + title: { type: 'text', label: 'Task title' }, + due_note: { type: 'text', label: 'Due note', required: true }, + owner_note: { type: 'text', label: 'Owner note', requiredWhen: 'true' }, + }, +}; + +const makeAdapter = () => ({ + getObjectSchema: vi.fn(async (_objectName: string): Promise => structuredClone(PUBLISHED)), + create: vi.fn(async (_object: string, _data: Record) => ({ id: 'r1' })), + update: vi.fn(async (_object: string, _id: string, _data: Record, _opts?: { ifMatch?: string }) => ({ id: 'r1' })), + findOne: vi.fn(async (_object: string, _id: string) => ({ id: 'r1' })), +}); + +afterEach(() => { + cleanup(); + GET_ITEM.fn = null; +}); + +type Doc = { name?: string; fields: Record> }; + +describe('withDraftOnlyFields (objectstack#34807)', () => { + it('adds the draft-only field marked, keeps published definitions, and touches neither input', () => { + const overlay = structuredClone(OVERLAY); + const published = structuredClone(PUBLISHED); + const out = withDraftOnlyFields(published, overlay) as Doc; + expect(out.fields.priority).toEqual({ + type: 'text', label: 'Priority', defaultValue: 'high', [DRAFT_ONLY_FIELD_KEY]: true, + }); + expect(out.fields.title).toEqual({ type: 'text', label: 'Title' }); + expect(overlay).toEqual(OVERLAY); + expect(published).toEqual(PUBLISHED); + }); + + it('a draft-only field drops required and requiredWhen; a published field keeps its own', () => { + const published = { name: 'tracker_task', fields: { title: { type: 'text', required: true } } }; + const out = withDraftOnlyFields(published, structuredClone(REQUIRED_OVERLAY)) as Doc; + expect(out.fields.due_note).toEqual({ type: 'text', label: 'Due note', [DRAFT_ONLY_FIELD_KEY]: true }); + expect(out.fields.owner_note).toEqual({ type: 'text', label: 'Owner note', [DRAFT_ONLY_FIELD_KEY]: true }); + expect(out.fields.title).toEqual({ type: 'text', required: true }); + }); + + it('the copy keeps the published sortability projection', () => { + const published = attachObjectSortability(structuredClone(PUBLISHED), { fields: { title: { sortable: false } } }); + const out = withDraftOnlyFields(published, structuredClone(OVERLAY)); + expect(readObjectSortability(out)).toEqual({ fields: { title: { sortable: false } } }); + }); + + it('with no published document every overlay field is draft-only', () => { + const out = withDraftOnlyFields(null, structuredClone(OVERLAY)) as Doc; + expect(out.fields.title[DRAFT_ONLY_FIELD_KEY]).toBe(true); + expect(out.fields.title.label).toBe('Task title'); + expect(out.fields.priority[DRAFT_ONLY_FIELD_KEY]).toBe(true); + }); + + it('with no overlay document the published one is returned as is', () => { + const published = structuredClone(PUBLISHED); + expect(withDraftOnlyFields(published, null)).toBe(published); + }); +}); + +describe('createPreviewFormDataSource (objectstack#34807)', () => { + it('answers the published document plus the draft-only field', async () => { + const adapter = makeAdapter(); + const ds = createPreviewFormDataSource(adapter, async () => structuredClone(OVERLAY)); + const schema = (await ds.getObjectSchema('tracker_task')) as Doc; + expect(schema.fields.priority[DRAFT_ONLY_FIELD_KEY]).toBe(true); + expect(schema.fields.priority.label).toBe('Priority'); + expect(schema.fields.title.label).toBe('Title'); + }); + + it('a draft-only object (published read absent) answers the overlay with every field draft-only', async () => { + const adapter = makeAdapter(); + adapter.getObjectSchema.mockRejectedValueOnce(new MetadataNotFoundError('tracker_task')); + const ds = createPreviewFormDataSource(adapter, async () => structuredClone(OVERLAY)); + const schema = (await ds.getObjectSchema('tracker_task')) as Doc; + expect(schema.fields.title[DRAFT_ONLY_FIELD_KEY]).toBe(true); + expect(schema.fields.priority[DRAFT_ONLY_FIELD_KEY]).toBe(true); + }); + + it('a published read that fails for another reason fails the read', async () => { + const adapter = makeAdapter(); + const failure = new Error('connection refused'); + adapter.getObjectSchema.mockRejectedValueOnce(failure); + const ds = createPreviewFormDataSource(adapter, async () => structuredClone(OVERLAY)); + await expect(ds.getObjectSchema('tracker_task')).rejects.toBe(failure); + }); + + it('create and update leave the draft-only names the schema read named out of the record', async () => { + const adapter = makeAdapter(); + const ds = createPreviewFormDataSource(adapter, async () => structuredClone(OVERLAY)); + await ds.getObjectSchema('tracker_task'); + await ds.create('tracker_task', { title: 'a', priority: 'high' }); + await ds.update('tracker_task', 'r1', { title: 'b', priority: 'low' }, { ifMatch: 'v1' }); + expect(adapter.create).toHaveBeenCalledWith('tracker_task', { title: 'a' }); + expect(adapter.update).toHaveBeenCalledWith('tracker_task', 'r1', { title: 'b' }, { ifMatch: 'v1' }); + }); + + it('no overlay document: the adapter answer is returned as is', async () => { + const adapter = makeAdapter(); + const ds = createPreviewFormDataSource(adapter, async () => null); + expect(await ds.getObjectSchema('tracker_task')).toEqual(PUBLISHED); + }); + + it('every other member is the adapter own, bound to it, with a stable identity', async () => { + class Adapter { + #writes = 0; + async getObjectSchema() { return PUBLISHED; } + async create(_object: string, data: Record) { this.#writes += 1; return { id: `r${this.#writes}`, ...data }; } + } + const adapter = new Adapter(); + const ds = createPreviewFormDataSource(adapter, async () => null); + expect(ds.create).toBe(ds.create); + expect(await ds.create('tracker_task', { title: 'a' })).toEqual({ id: 'r1', title: 'a' }); + expect(ds).toBeInstanceOf(Adapter); + }); +}); + +describe('usePreviewFormDataSource (objectstack#34807)', () => { + const wrap = (preview: boolean) => ({ children }: { children: React.ReactNode }) => ( + + {children} + + ); + + it('CONTROL: outside preview it is the adapter itself', () => { + const adapter = makeAdapter(); + const { result } = renderHook(() => usePreviewFormDataSource(adapter), { wrapper: wrap(false) }); + expect(result.current).toBe(adapter); + }); + + it('in preview it reads the object document through the metadata provider', async () => { + const adapter = makeAdapter(); + const getItem = vi.fn(async (_type: string, _name: string): Promise => structuredClone(OVERLAY)); + GET_ITEM.fn = getItem; + const { result } = renderHook(() => usePreviewFormDataSource(adapter), { wrapper: wrap(true) }); + expect(result.current).not.toBe(adapter); + await result.current!.getObjectSchema('tracker_task'); + expect(getItem).toHaveBeenCalledWith('object', 'tracker_task'); + }); +}); + +describe('the global New modal under draft preview (objectstack#34807)', () => { + function Modal({ adapter, fields }: { adapter: ReturnType; fields: string[] }) { + const ds = usePreviewFormDataSource(adapter); + return ( + + ); + } + const renderModal = (preview: boolean, adapter: ReturnType, fields = ['title', 'priority']) => + render( + + + + + , + ); + + it('draws the draft-only field disabled, and Save leaves it out of the create', async () => { + const adapter = makeAdapter(); + GET_ITEM.fn = async () => structuredClone(OVERLAY); + renderModal(true, adapter); + await waitFor(() => expect(screen.getByText('Priority')).toBeInTheDocument()); + expect(document.body.querySelector('input[name="priority"]')).toBeDisabled(); + expect(document.body.querySelector('input[name="title"]')).not.toBeDisabled(); + + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(adapter.create).toHaveBeenCalledTimes(1)); + const [object, payload] = adapter.create.mock.calls[0] as unknown as [string, Record]; + expect(object).toBe('tracker_task'); + expect(payload).toMatchObject({ title: 'Ship it' }); + expect(payload).not.toHaveProperty('priority'); + }); + + it('a REQUIRED draft-only field is drawn disabled and does not block Save; the create leaves it out', async () => { + const adapter = makeAdapter(); + GET_ITEM.fn = async () => structuredClone(REQUIRED_OVERLAY); + renderModal(true, adapter, ['title', 'due_note', 'owner_note']); + await waitFor(() => expect(screen.getByText('Due note')).toBeInTheDocument()); + expect(document.body.querySelector('input[name="due_note"]')).toBeDisabled(); + expect(document.body.querySelector('input[name="owner_note"]')).toBeDisabled(); + + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(adapter.create).toHaveBeenCalledTimes(1)); + const [, payload] = adapter.create.mock.calls[0] as unknown as [string, Record]; + expect(payload).toMatchObject({ title: 'Ship it' }); + expect(payload).not.toHaveProperty('due_note'); + expect(payload).not.toHaveProperty('owner_note'); + }); + + it('CONTROL: outside preview a required published field left empty still blocks Save', async () => { + const adapter = makeAdapter(); + adapter.getObjectSchema.mockImplementation(async () => ({ + name: 'tracker_task', + fields: { title: { type: 'text', label: 'Title' }, code: { type: 'text', label: 'Code', required: true } }, + })); + GET_ITEM.fn = async () => structuredClone(OVERLAY); + renderModal(false, adapter, ['title', 'code']); + await waitFor(() => expect(screen.getByText('Code')).toBeInTheDocument()); + expect(document.body.querySelector('input[name="code"]')).not.toBeDisabled(); + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(document.body.querySelector('input[name="code"]')).toHaveAttribute('aria-invalid', 'true')); + expect(adapter.create).not.toHaveBeenCalled(); + }); + + it('CONTROL: outside preview the published document is read once and the draft field is absent', async () => { + const adapter = makeAdapter(); + const getItem = vi.fn(async (_type: string, _name: string): Promise => structuredClone(OVERLAY)); + GET_ITEM.fn = getItem; + renderModal(false, adapter); + await waitFor(() => expect(screen.getByText('Title')).toBeInTheDocument()); + expect(screen.queryByText('Priority')).not.toBeInTheDocument(); + expect(adapter.getObjectSchema).toHaveBeenCalledTimes(1); + expect(adapter.getObjectSchema).toHaveBeenCalledWith('tracker_task'); + expect(getItem).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.ts b/ui/packages/app-shell/src/utils/previewFormDataSource.ts new file mode 100644 index 00000000000..7795004bb00 --- /dev/null +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.ts @@ -0,0 +1,190 @@ +/** + * The record form's data source under draft preview (objectstack#34807, + * ADR-0037 Phase 1). + * + * Under `?preview=draft` the console's metadata reads come from the REST + * `?preview=draft` overlay (`MetadataProvider`, through + * `createConsoleMetadataClient({ previewDrafts: true })`), so a record form's + * field NAMES include a field that exists only in a draft, while its field + * DEFINITIONS come from `dataSource.getObjectSchema`, the adapter's published + * read, which carries no preview flag. `ObjectForm` draws only a name the + * definition declares. + * + * {@link usePreviewFormDataSource} joins the two at the call site, not in the + * form: in preview it hands the form a proxy over the adapter whose + * `getObjectSchema` answers {@link withDraftOnlyFields} over the overlay + * document (the provider's own `getItem('object', name)`, which reads through + * the preview client in preview). Outside preview it returns the adapter + * ITSELF, so the published path keeps its single adapter read per document + * (objectui#13044) unchanged. + * + * Preview stays read-only for data (ADR-0037 Phase 1: the data plane is + * untouched; seat ruling 6946403206). A field the draft adds does not exist in + * the published object the data door validates against, so it carries + * {@link DRAFT_ONLY_FIELD_KEY} and the form draws it DISABLED: visible with its + * draft definition, never fillable (`@object-ui/plugin-form` maps the marker + * onto the field's `disabled`, in `ObjectForm` and in `fromObjectSchema`). As + * the safety net, the proxy's `create` / `update` leave its name out of the + * record they send, so its declared default is never written either. Its + * `required` / `requiredWhen` are dropped from the marked copy: a disabled + * control the form still requires would make every save refuse. + * ⛔ Not `readonly: true`: `filterSystemFields` in `@object-ui/plugin-form` + * drops such a field before render, on create and edit alike, and a create + * form does not evaluate `readonlyWhen` — either would hide the very field + * the preview exists to show, or do nothing. Every other member is the + * adapter's own, bound to it, so a write goes out as it does without preview. + * + * @module utils/previewFormDataSource + */ + +import { useMemo } from 'react'; +import { MetadataNotFoundError } from '@object-ui/data-objectstack'; +import { attachObjectSortability, readObjectSortability } from '@object-ui/core'; +import { useMetadata } from '../providers/MetadataProvider.js'; +import { usePreviewDrafts } from '../preview/PreviewModeContext.js'; + +/** The one adapter member this proxy answers differently. */ +interface SchemaReader { + getObjectSchema(objectName: string): Promise; +} + +type ObjectDocument = { fields?: Record> } & Record; + +function isDocument(value: unknown): value is ObjectDocument { + return value != null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * The undeclared key that marks a field the draft adds: present in the draft + * overlay document, absent from the published one. An underscore-private + * convention between this package and `@object-ui/plugin-form` (which spells + * the same literal and draws a marked field disabled), never an authoring + * key: the copy carrying it is client-side only and never written back. A + * draft-preview reader that must keep such a name out of a data request reads + * it here. + */ +export const DRAFT_ONLY_FIELD_KEY = '_draftOnly'; + +/** The names `schema` marks {@link DRAFT_ONLY_FIELD_KEY}. */ +export function draftOnlyFieldNames(schema: unknown): string[] { + if (!isDocument(schema) || !isDocument(schema.fields)) return []; + return Object.entries(schema.fields) + .filter(([, def]) => isDocument(def) && def[DRAFT_ONLY_FIELD_KEY] === true) + .map(([name]) => name); +} + +/** + * The object definition a draft-preview reader draws: a copy of the published + * document, plus each field only the draft overlay declares, with its draft + * definition, marked {@link DRAFT_ONLY_FIELD_KEY} and without `required` / + * `requiredWhen`: the form draws it disabled, so a requirement would refuse + * the save over a field the viewer cannot fill. Fields the + * published document declares keep their published definition, so what the + * form validates and writes is what the data door accepts. The published + * copy keeps the adapter's per-column sortability projection, which a spread + * would drop. With no published document (a draft-only object) every overlay + * field is draft-only; with no overlay document the published one is returned + * as is. Neither input is touched. + */ +export function withDraftOnlyFields(published: unknown, overlay: unknown): unknown { + if (!isDocument(overlay) || !isDocument(overlay.fields)) return published; + const base: ObjectDocument = isDocument(published) ? published : overlay; + const publishedFields = isDocument(published) && isDocument(published.fields) ? published.fields : {}; + const fields: Record> = { ...publishedFields }; + for (const [name, def] of Object.entries(overlay.fields)) { + if (Object.prototype.hasOwnProperty.call(publishedFields, name)) continue; + const { required: _required, requiredWhen: _requiredWhen, ...drawn } = def; + fields[name] = { ...drawn, [DRAFT_ONLY_FIELD_KEY]: true }; + } + return attachObjectSortability({ ...base, fields }, readObjectSortability(published)); +} + +/** + * {@link withDraftOnlyFields} for one object: the overlay document + * `readOverlay(name)` resolves, over the adapter's published read. A published + * read that fails for any reason but absence fails this read, as it does + * without preview; with no overlay document it is the adapter's read alone. + */ +export async function readDraftPreviewObjectSchema( + adapter: SchemaReader, + readOverlay: (objectName: string) => Promise, + objectName: string, +): Promise { + const overlay = await readOverlay(objectName); + if (!isDocument(overlay)) return adapter.getObjectSchema(objectName); + let published: unknown = null; + try { + published = await adapter.getObjectSchema(objectName); + } catch (err) { + if (!(err instanceof MetadataNotFoundError)) throw err; + } + return withDraftOnlyFields(published, overlay); +} + +/** `data` without the `names` it carries; `data` itself when it carries none. */ +function withoutNames(data: unknown, names: readonly string[] | undefined): unknown { + if (!names || names.length === 0 || !isDocument(data)) return data; + if (!names.some((name) => Object.prototype.hasOwnProperty.call(data, name))) return data; + const out: Record = { ...data }; + for (const name of names) delete out[name]; + return out; +} + +/** + * A proxy over `adapter` whose `getObjectSchema(name)` answers + * {@link readDraftPreviewObjectSchema}, and whose `create` / `update` leave the + * draft-only fields that answer named out of the record they send. Every + * other member is the adapter's own, bound to it. + */ +export function createPreviewFormDataSource( + adapter: T, + readOverlay: (objectName: string) => Promise, +): T { + const draftOnly = new Map(); + const getObjectSchema = async (objectName: string): Promise => { + const schema = await readDraftPreviewObjectSchema(adapter, readOverlay, objectName); + draftOnly.set(objectName, draftOnlyFieldNames(schema)); + return schema; + }; + const writes: Record unknown> = { + create: (resource, data, ...rest) => + (adapter as unknown as { create: (...a: unknown[]) => unknown }) + .create(resource, withoutNames(data, draftOnly.get(resource as string)), ...rest), + update: (resource, id, data, ...rest) => + (adapter as unknown as { update: (...a: unknown[]) => unknown }) + .update(resource, id, withoutNames(data, draftOnly.get(resource as string)), ...rest), + }; + // Bound once per member, so a reader that keys an effect on a method's + // identity sees the same function on every access. + const bound = new Map(); + return new Proxy(adapter, { + get(target, prop) { + if (prop === 'getObjectSchema') return getObjectSchema; + if ((prop === 'create' || prop === 'update') && typeof Reflect.get(target, prop, target) === 'function') { + return writes[prop]; + } + const value = Reflect.get(target, prop, target); + if (typeof value !== 'function') return value; + let fn = bound.get(prop); + if (!fn) { + fn = (value as (...args: unknown[]) => unknown).bind(target); + bound.set(prop, fn); + } + return fn; + }, + }); +} + +/** + * The data source a record form (the New/Edit page and the global modal) + * reads its object definition through: `adapter` itself outside draft + * preview, the {@link createPreviewFormDataSource} proxy inside it. + */ +export function usePreviewFormDataSource(adapter: T | null | undefined): T | null | undefined { + const previewDrafts = usePreviewDrafts(); + const { getItem } = useMetadata(); + return useMemo(() => { + if (!previewDrafts || !adapter) return adapter; + return createPreviewFormDataSource(adapter, (name) => getItem('object', name)); + }, [previewDrafts, adapter, getItem]); +} diff --git a/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx new file mode 100644 index 00000000000..66fff75bf2a --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -0,0 +1,175 @@ +/** + * 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. + */ + +/** + * objectstack#34807 — under `?preview=draft` the full-page New record form + * draws a field that exists only in the draft. + * + * The page's field names come from the metadata provider, which reads the + * draft overlay in preview; the real `ObjectForm` draws only a name its object + * definition declares, and that definition comes from the data source the page + * hands it. In preview that source answers the published document plus the + * draft-only field marked `_draftOnly`, so the field is drawn DISABLED, and + * Save leaves it out of the create, its declared default included. + * + * CONTROL: outside preview the page hands the form the adapter itself — one + * published read (objectui#13044), no overlay read, no draft field. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { registerAllFields } from '@object-ui/fields'; +import { PreviewModeProvider } from '../preview/PreviewModeContext'; +import { RecordFormPage } from './RecordFormPage'; + +registerAllFields(); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ + user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'admin' }, + getAuthConfig: async () => ({ features: {} }), + activeOrganization: null, + }), +})); + +const PUBLISHED = { + name: 'tracker_task', + label: 'Task', + fields: { title: { type: 'text', label: 'Title' } }, +}; +const OVERLAY = { + name: 'tracker_task', + label: 'Task', + fields: { + title: { type: 'text', label: 'Title' }, + priority: { type: 'text', label: 'Priority', defaultValue: 'high' }, + }, +}; + +const { ENV } = vi.hoisted(() => ({ + ENV: { + adapter: null as null | Record>, + getItem: null as null | ReturnType, + objects: [] as unknown[], + }, +})); + +vi.mock('../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ objects: ENV.objects, loading: false, getItem: ENV.getItem }), +})); +vi.mock('../providers/AdapterProvider', () => ({ + useAdapter: () => ENV.adapter, +})); + +// A draft that adds a REQUIRED field with no default. +const REQUIRED_OVERLAY = { + name: 'tracker_task', + label: 'Task', + fields: { + title: { type: 'text', label: 'Title' }, + due_note: { type: 'text', label: 'Due note', required: true }, + }, +}; + +// A draft whose form view restates `required` on the draft-only field. +const VIEW_REQUIRED_OVERLAY = { + ...REQUIRED_OVERLAY, + fields: { title: { type: 'text', label: 'Title' }, due_note: { type: 'text', label: 'Due note' } }, + form: { + type: 'simple', + sections: [{ name: 'main', fields: ['title', { field: 'due_note', required: true }] }], + }, +}; + +function setUp(objects: unknown[], overlay: unknown = OVERLAY) { + ENV.objects = objects; + ENV.getItem = vi.fn(async () => structuredClone(overlay)); + ENV.adapter = { + getObjectSchema: vi.fn(async () => structuredClone(PUBLISHED)), + create: vi.fn(async () => ({ id: 'r1', title: 'Ship it' })), + update: vi.fn(async () => ({ id: 'r1' })), + findOne: vi.fn(async () => ({ id: 'r1' })), + }; + return { adapter: ENV.adapter, getItem: ENV.getItem }; +} + +afterEach(cleanup); + +function renderNew(preview: boolean) { + render( + + + + } /> + + + , + ); +} + +describe('RecordFormPage under draft preview (objectstack#34807)', () => { + it('draws the draft-only field disabled with its draft label, and Save leaves it out of the create', async () => { + const { adapter, getItem } = setUp([OVERLAY]); + renderNew(true); + await waitFor(() => expect(screen.getByText('Priority')).toBeInTheDocument()); + expect(getItem).toHaveBeenCalledWith('object', 'tracker_task'); + expect(document.body.querySelector('input[name="priority"]')).toBeDisabled(); + expect(document.body.querySelector('input[name="title"]')).not.toBeDisabled(); + + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(adapter.create).toHaveBeenCalledTimes(1)); + const [object, payload] = adapter.create.mock.calls[0] as [string, Record]; + expect(object).toBe('tracker_task'); + expect(payload).toMatchObject({ title: 'Ship it' }); + expect(payload).not.toHaveProperty('priority'); + }); + + it('a REQUIRED draft-only field is drawn disabled and does not block Save; the create leaves it out', async () => { + const { adapter } = setUp([REQUIRED_OVERLAY], REQUIRED_OVERLAY); + renderNew(true); + await waitFor(() => expect(screen.getByText('Due note')).toBeInTheDocument()); + expect(document.body.querySelector('input[name="due_note"]')).toBeDisabled(); + + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(adapter.create).toHaveBeenCalledTimes(1)); + const [, payload] = adapter.create.mock.calls[0] as [string, Record]; + expect(payload).toMatchObject({ title: 'Ship it' }); + expect(payload).not.toHaveProperty('due_note'); + }); + + it('a draft form view restating `required` on the draft-only field does not block Save', async () => { + const { adapter } = setUp([VIEW_REQUIRED_OVERLAY], VIEW_REQUIRED_OVERLAY); + renderNew(true); + await waitFor(() => expect(screen.getByText('Due note')).toBeInTheDocument()); + expect(document.body.querySelector('input[name="due_note"]')).toBeDisabled(); + + fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); + fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(adapter.create).toHaveBeenCalledTimes(1)); + const [, payload] = adapter.create.mock.calls[0] as [string, Record]; + expect(payload).toMatchObject({ title: 'Ship it' }); + expect(payload).not.toHaveProperty('due_note'); + }); + + it('CONTROL: outside preview the form reads the published document once and draws no draft field', async () => { + const { adapter, getItem } = setUp([PUBLISHED]); + renderNew(false); + await waitFor(() => expect(screen.getByText('Title')).toBeInTheDocument()); + expect(screen.queryByText('Priority')).not.toBeInTheDocument(); + expect(adapter.getObjectSchema).toHaveBeenCalledTimes(1); + expect(adapter.getObjectSchema).toHaveBeenCalledWith('tracker_task'); + expect(getItem).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordFormPage.tsx b/ui/packages/app-shell/src/views/RecordFormPage.tsx index cfad83523f8..661f587b536 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.tsx @@ -66,6 +66,7 @@ import { ManagedByBadge } from '../components/ManagedByBadge.js'; import { resolveFormViewChrome, selectRecordFormView } from '../utils/recordFormNavigation.js'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; import { readRecordFormAiChanges, readRecordFormAiDraft } from '../utils/recordFormAiDraft.js'; +import { usePreviewFormDataSource } from '../utils/previewFormDataSource.js'; import { useAuth } from '@object-ui/auth'; export interface RecordFormPageProps { @@ -91,6 +92,12 @@ export function RecordFormPage({ mode }: RecordFormPageProps) { const [searchParams] = useSearchParams(); const location = useLocation(); const dataSource = useAdapter(); + // objectstack#34807 — under draft preview the form reads its object + // definition through the draft overlay: a field only the draft declares is + // drawn disabled, and the proxy leaves it out of every create and update. + // Outside preview this is `dataSource` itself. The answer-warning claim below + // keeps the raw adapter. + const formDataSource = usePreviewFormDataSource(dataSource); const { objects, loading: metadataLoading } = useMetadata(); const { t, language } = useObjectTranslation(); const { objectLabel, objectPluralLabel } = useObjectLabel(); @@ -511,7 +518,7 @@ export function RecordFormPage({ mode }: RecordFormPageProps) { onCancel: handleCancel, ...formChrome, }} - dataSource={dataSource ?? undefined} + dataSource={formDataSource ?? undefined} /> diff --git a/ui/packages/plugin-form/src/ObjectForm.test.tsx b/ui/packages/plugin-form/src/ObjectForm.test.tsx index bb15c895d5b..951eca2f47c 100644 --- a/ui/packages/plugin-form/src/ObjectForm.test.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.test.tsx @@ -343,3 +343,38 @@ describe('ObjectForm Integration', () => { expect(screen.getByText('Lines')).toBeTruthy(); }); }); + +// objectstack#34807 — the console's draft preview marks a field only the draft +// declares `_draftOnly: true` (an underscore-private convention with +// `@object-ui/app-shell`, never an authoring key). The form draws it, disabled. +describe('ObjectForm draws a `_draftOnly` field disabled (objectstack#34807)', () => { + const renderCreate = (priority: Record) => { + const ds: any = { + getObjectSchema: vi.fn().mockResolvedValue({ + name: 'tracker_task', + fields: { title: { type: 'text', label: 'Title' }, priority }, + }), + create: vi.fn(), + }; + render( + , + ); + }; + const input = (name: string) => document.querySelector(`input[name="${name}"]`) as HTMLInputElement | null; + + it('a marked field is drawn, and disabled', async () => { + renderCreate({ type: 'text', label: 'Priority', _draftOnly: true }); + await waitFor(() => expect(screen.getByText('Priority')).toBeTruthy()); + expect(input('priority')?.disabled).toBe(true); + expect(input('title')?.disabled).toBe(false); + }); + + it('CONTROL: the same field without the marker is editable', async () => { + renderCreate({ type: 'text', label: 'Priority' }); + await waitFor(() => expect(screen.getByText('Priority')).toBeTruthy()); + expect(input('priority')?.disabled).toBe(false); + }); +}); diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index 0f8a4662f80..178db0a698a 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -1002,7 +1002,9 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource // server resolves it — refusing the submit would leave the user with // nothing sensible to type. required: isRequiredInForm(field, isCreateFormMode(schema)), - disabled: schema.readOnly || schema.mode === 'view' || field.readonly, + // `_draftOnly`: a field only the draft declares, under the console's + // draft preview — drawn, never fillable (see `fromObjectSchema`). + disabled: schema.readOnly || schema.mode === 'view' || field.readonly || field._draftOnly === true, placeholder: field.placeholder, // The help line under the control: the spec's `inlineHelpText`, // else `description`, through the one read `fromObjectSchema` diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index a5e77ffe10a..12e6d6d7808 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -681,6 +681,14 @@ const WRITE_SITES: Record = { outOfFamily("the language switcher changes the session's language locally and persists the caller's OWN sys_user.locale best-effort, a refusal surfacing as a toast"), 'packages/app-shell/src/hooks/useUserLocale.ts :: saveSignInLanguagePick :: update': outOfFamily("the sign-in page saves the language picked on it as the caller's OWN sys_user.locale, only while that column is unset; a refusal leaves the pick on this device and does not hold the sign-in (no CRUD visibility door)"), + // The draft-preview record form's data source (objectstack#34807): a proxy + // over the adapter that forwards the create / update its form hands it, + // minus the draft-only field names. The affordance is the form's own write + // site, entered where the form calls it. + 'packages/app-shell/src/utils/previewFormDataSource.ts :: createPreviewFormDataSource > writes > create :: create': + door('the draft-preview form data source: it forwards the create its form hands it, minus draft-only field names'), + 'packages/app-shell/src/utils/previewFormDataSource.ts :: createPreviewFormDataSource > writes > update :: update': + door('the draft-preview form data source: it forwards the update its form hands it, minus draft-only field names'), // The attachments panel's upload has no data-source write site: the upload's // own completion attaches it (the upload adapter's `attachTo`), so the // `attachmentUpload` row is read where the upload is offered and no diff --git a/ui/packages/plugin-form/src/sectionFields.test.ts b/ui/packages/plugin-form/src/sectionFields.test.ts index 56fc3aa2d83..10753bb58e7 100644 --- a/ui/packages/plugin-form/src/sectionFields.test.ts +++ b/ui/packages/plugin-form/src/sectionFields.test.ts @@ -450,3 +450,41 @@ describe('sectionEntryName', () => { expect(sectionEntryName(null)).toBeUndefined(); }); }); + +// objectstack#34807 — the shared object-schema mapping the modal and drawer +// flat paths and every section body resolve through: the console's draft +// preview marker `_draftOnly` (underscore-private, never an authoring key) +// lands on `disabled`. +describe('a `_draftOnly` field maps to a disabled FormField (objectstack#34807)', () => { + const draftCtx = { + objectSchema: { + name: 'tracker_task', + fields: { + title: { type: 'text', label: 'Title' }, + priority: { type: 'text', label: 'Priority', _draftOnly: true }, + }, + }, + objectName: 'tracker_task', + fieldLabel: (_obj: string, _name: string, fallback?: string) => fallback || _name, + }; + + it('the marked field is disabled', () => { + expect(normalizeSectionField('priority', draftCtx)!.disabled).toBe(true); + }); + + it('CONTROL: an unmarked field is not', () => { + expect(normalizeSectionField('title', draftCtx)!.disabled).toBeFalsy(); + }); + + it('a form view restating `required: true` does not make the marked field required; it stays disabled', () => { + const f = normalizeSectionField({ field: 'priority', required: true } as never, draftCtx)!; + expect(f.required).toBe(false); + expect(f.disabled).toBe(true); + }); + + it('CONTROL: the same view entry over an unmarked field still makes it required', () => { + const f = normalizeSectionField({ field: 'title', required: true } as never, draftCtx)!; + expect(f.required).toBe(true); + expect(f.disabled).toBeFalsy(); + }); +}); diff --git a/ui/packages/plugin-form/src/sectionFields.ts b/ui/packages/plugin-form/src/sectionFields.ts index f253449f3c6..f1a74df5666 100644 --- a/ui/packages/plugin-form/src/sectionFields.ts +++ b/ui/packages/plugin-form/src/sectionFields.ts @@ -336,7 +336,12 @@ export function fromObjectSchema(fieldName: string, ctx: SectionFieldsContext): // (#4069) — the control is deliberately left empty for exactly that // resolution, so refusing the submit would leave nothing to type. required: isRequiredInForm(field, isCreateFormMode(ctx)), - disabled: ctx.readOnly || ctx.mode === 'view' || field.readonly, + // `_draftOnly` is the console's draft-preview marker on a field only the + // draft declares (app-shell `previewFormDataSource`, which also keeps it + // out of every write): an underscore-private convention between two of + // this repository's packages, never an authoring key. It is drawn disabled + // rather than `readonly`, which `filterSystemFields` drops before render. + disabled: ctx.readOnly || ctx.mode === 'view' || field.readonly || field._draftOnly === true, placeholder: field.placeholder, // The help line under the control: the spec's `inlineHelpText`, else // `description`, through the one read `ObjectForm`'s field builder shares @@ -463,7 +468,13 @@ function resolveSectionEntry( // `defaultValue` on the object field, not which layer asserted `required` — // a form view saying `required: true` over `defaultValue: 'NOW()'` makes the // same claim the object schema does, and hits the same wall. - if (fd.required != null) { + // + // Except over a `_draftOnly` field (the console's draft-preview marker, see + // `fromObjectSchema`): it is drawn disabled, so a requirement restated by a + // view would refuse every save over a control the viewer cannot fill. The + // marked copy already carries no `required` of its own. + const draftOnly = ctx.objectSchema?.fields?.[fieldName]?._draftOnly === true; + if (fd.required != null && !draftOnly) { base.required = isRequiredInForm( { required: fd.required, defaultValue: ctx.objectSchema?.fields?.[fieldName]?.defaultValue }, isCreateFormMode(ctx),