From f964b2b19869fd05f56935d2f410d3f4ed980f1b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:27:35 +0000 Subject: [PATCH 1/8] fix(console): draft preview record forms draw draft-only fields read-only Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../app-shell/src/console/AppContent.tsx | 7 +- .../src/utils/previewFormDataSource.test.tsx | 233 ++++++++++++++++++ .../src/utils/previewFormDataSource.ts | 144 +++++++++++ ...RecordFormPage.draftPreview-34807.test.tsx | 124 ++++++++++ .../app-shell/src/views/RecordFormPage.tsx | 8 +- 5 files changed, 514 insertions(+), 2 deletions(-) create mode 100644 ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx create mode 100644 ui/packages/app-shell/src/utils/previewFormDataSource.ts create mode 100644 ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index a7f2bae5226..40f383e6ce2 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,10 @@ 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; outside preview this is + // `dataSource` itself. + const formDataSource = usePreviewFormDataSource(dataSource); const { t, language } = useObjectTranslation(); const { objectLabel, objectPluralLabel } = useObjectLabel(); @@ -1794,7 +1799,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = }, ), }} - dataSource={dataSource} + dataSource={formDataSource} /> )} 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..ecab90dd6f4 --- /dev/null +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -0,0 +1,233 @@ +/** + * 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, read-only and marked draft-only; + * the adapter's sortability projection survives the copy. + * - The real `ModalForm` (the console's global New/Edit modal) draws such a + * field, and Save leaves it out of the create, a 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' }, + }, +}; + +const makeAdapter = () => ({ + getObjectSchema: vi.fn(async () => structuredClone(PUBLISHED)), + create: vi.fn(async () => ({ id: 'r1' })), + update: vi.fn(async () => ({ id: 'r1' })), + findOne: vi.fn(async () => ({ id: 'r1' })), +}); + +afterEach(() => { + cleanup(); + GET_ITEM.fn = null; +}); + +type Doc = { name?: string; fields: Record> }; + +describe('withDraftOnlyFields (objectstack#34807)', () => { + it('adds the draft-only field read-only and 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', readonly: true, [DRAFT_ONLY_FIELD_KEY]: true, + }); + expect(out.fields.title).toEqual({ type: 'text', label: 'Title' }); + expect(overlay).toEqual(OVERLAY); + expect(published).toEqual(PUBLISHED); + }); + + 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.readonly).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, read-only', async () => { + const adapter = makeAdapter(); + const ds = createPreviewFormDataSource(adapter, async () => structuredClone(OVERLAY)); + const schema = (await ds.getObjectSchema('tracker_task')) as Doc; + expect(schema.fields.priority.readonly).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 read-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.readonly).toBe(true); + expect(schema.fields.priority.readonly).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('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 () => 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 }: { adapter: ReturnType }) { + const ds = usePreviewFormDataSource(adapter); + return ( + + ); + } + const renderModal = (preview: boolean, adapter: ReturnType) => + render( + + + + + , + ); + + it('draws the draft-only field, 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()); + + 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('CONTROL: outside preview the published document is read once and the draft field is absent', async () => { + const adapter = makeAdapter(); + const getItem = vi.fn(async () => 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..6a1fa4e2c1b --- /dev/null +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.ts @@ -0,0 +1,144 @@ +/** + * 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 reaches the + * form `readonly: true`: drawn with its draft definition, not editable, and + * left out of every create and update by the form's shared write sanitizer, + * which skips read-only fields (a declared default included). Every member + * other than `getObjectSchema` 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. Client-side only (the copy + * carrying it is 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 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, `readonly: true` and {@link DRAFT_ONLY_FIELD_KEY}. 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; + fields[name] = { ...def, readonly: true, [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); +} + +/** + * A proxy over `adapter` whose `getObjectSchema(name)` answers + * {@link readDraftPreviewObjectSchema}. Every other member is the adapter's + * own, bound to it. + */ +export function createPreviewFormDataSource( + adapter: T, + readOverlay: (objectName: string) => Promise, +): T { + const getObjectSchema = (objectName: string): Promise => + readDraftPreviewObjectSchema(adapter, readOverlay, objectName); + // 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; + 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..a17c77fa22a --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -0,0 +1,124 @@ +/** + * 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, read-only, so the field is drawn and Save leaves it out. + * + * 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, +})); + +function setUp(objects: unknown[]) { + 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 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'); + + 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('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..fe3c55376e6 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,11 @@ 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 (draft-only fields read-only); outside + // preview this is `dataSource` itself. Writes and the answer-warning claim + // below stay on the adapter. + const formDataSource = usePreviewFormDataSource(dataSource); const { objects, loading: metadataLoading } = useMetadata(); const { t, language } = useObjectTranslation(); const { objectLabel, objectPluralLabel } = useObjectLabel(); @@ -511,7 +517,7 @@ export function RecordFormPage({ mode }: RecordFormPageProps) { onCancel: handleCancel, ...formChrome, }} - dataSource={dataSource ?? undefined} + dataSource={formDataSource ?? undefined} /> From 0df3c6e1d239713bdf4e57dae65675790888150b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:38:22 +0000 Subject: [PATCH 2/8] fix(console): keep draft-only fields out of preview record writes Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/utils/previewFormDataSource.test.tsx | 35 +++++++---- .../src/utils/previewFormDataSource.ts | 60 +++++++++++++++---- ...RecordFormPage.draftPreview-34807.test.tsx | 4 +- 3 files changed, 75 insertions(+), 24 deletions(-) diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx index ecab90dd6f4..e6c7f8c6299 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -10,10 +10,12 @@ * 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, read-only and marked draft-only; - * the adapter's sortability projection survives the copy. + * 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, and Save leaves it out of the create, a declared default included. + * field, and Save leaves it out of the create: what the viewer typed into + * it and its declared default alike. * - 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. @@ -75,12 +77,12 @@ afterEach(() => { type Doc = { name?: string; fields: Record> }; describe('withDraftOnlyFields (objectstack#34807)', () => { - it('adds the draft-only field read-only and marked, keeps published definitions, and touches neither input', () => { + 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', readonly: true, [DRAFT_ONLY_FIELD_KEY]: true, + type: 'text', label: 'Priority', defaultValue: 'high', [DRAFT_ONLY_FIELD_KEY]: true, }); expect(out.fields.title).toEqual({ type: 'text', label: 'Title' }); expect(overlay).toEqual(OVERLAY); @@ -95,7 +97,7 @@ describe('withDraftOnlyFields (objectstack#34807)', () => { it('with no published document every overlay field is draft-only', () => { const out = withDraftOnlyFields(null, structuredClone(OVERLAY)) as Doc; - expect(out.fields.title.readonly).toBe(true); + 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); }); @@ -107,22 +109,22 @@ describe('withDraftOnlyFields (objectstack#34807)', () => { }); describe('createPreviewFormDataSource (objectstack#34807)', () => { - it('answers the published document plus the draft-only field, read-only', async () => { + 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.readonly).toBe(true); + 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 read-only', async () => { + 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.readonly).toBe(true); - expect(schema.fields.priority.readonly).toBe(true); + 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 () => { @@ -133,6 +135,16 @@ describe('createPreviewFormDataSource (objectstack#34807)', () => { 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); @@ -209,6 +221,7 @@ describe('the global New modal under draft preview (objectstack#34807)', () => { GET_ITEM.fn = async () => structuredClone(OVERLAY); renderModal(true, adapter); await waitFor(() => expect(screen.getByText('Priority')).toBeInTheDocument()); + fireEvent.change(document.body.querySelector('input[name="priority"]') as HTMLInputElement, { target: { value: 'urgent' } }); fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.ts b/ui/packages/app-shell/src/utils/previewFormDataSource.ts index 6a1fa4e2c1b..1b824dbbfee 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.ts +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.ts @@ -20,12 +20,15 @@ * * 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 reaches the - * form `readonly: true`: drawn with its draft definition, not editable, and - * left out of every create and update by the form's shared write sanitizer, - * which skips read-only fields (a declared default included). Every member - * other than `getObjectSchema` is the adapter's own, bound to it, so a write - * goes out as it does without preview. + * the published object the data door validates against, so the proxy's + * `create` / `update` leave its name out of the record they send: what the + * viewer typed into it, or its declared default, is never written (the draft + * bar above every preview page says nothing there is live until publish). + * ⛔ The field is not locked instead: a create form drops a field declared + * `readonly: true` (`filterCreateModeFields` in `@object-ui/plugin-form`) and + * does not evaluate `readonlyWhen`, so 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 */ @@ -55,10 +58,18 @@ function isDocument(value: unknown): value is ObjectDocument { */ 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, `readonly: true` and {@link DRAFT_ONLY_FIELD_KEY}. Fields the + * definition, marked {@link DRAFT_ONLY_FIELD_KEY}. 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 @@ -73,7 +84,7 @@ export function withDraftOnlyFields(published: unknown, overlay: unknown): unkno const fields: Record> = { ...publishedFields }; for (const [name, def] of Object.entries(overlay.fields)) { if (Object.prototype.hasOwnProperty.call(publishedFields, name)) continue; - fields[name] = { ...def, readonly: true, [DRAFT_ONLY_FIELD_KEY]: true }; + fields[name] = { ...def, [DRAFT_ONLY_FIELD_KEY]: true }; } return attachObjectSortability({ ...base, fields }, readObjectSortability(published)); } @@ -100,23 +111,48 @@ export async function readDraftPreviewObjectSchema( 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}. Every other member is the adapter's - * own, bound to it. + * {@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 getObjectSchema = (objectName: string): Promise => - readDraftPreviewObjectSchema(adapter, readOverlay, objectName); + 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); 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 index a17c77fa22a..bbb1768b21a 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -14,7 +14,8 @@ * 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, read-only, so the field is drawn and Save leaves it out. + * draft-only field, so the field is drawn, and Save leaves it out of the + * create: what the viewer typed into it and its declared default alike. * * CONTROL: outside preview the page hands the form the adapter itself — one * published read (objectui#13044), no overlay read, no draft field. @@ -102,6 +103,7 @@ describe('RecordFormPage under draft preview (objectstack#34807)', () => { renderNew(true); await waitFor(() => expect(screen.getByText('Priority')).toBeInTheDocument()); expect(getItem).toHaveBeenCalledWith('object', 'tracker_task'); + fireEvent.change(document.body.querySelector('input[name="priority"]') as HTMLInputElement, { target: { value: 'urgent' } }); fireEvent.change(document.body.querySelector('input[name="title"]') as HTMLInputElement, { target: { value: 'Ship it' } }); fireEvent.submit(document.body.querySelector('form') as HTMLFormElement); From fbfdc51ad25dd40647a01c6bfa84d9b96cb46aa7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:39:16 +0000 Subject: [PATCH 3/8] chore(changeset): draft preview record form fields Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34807-draft-preview-form-fields.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/34807-draft-preview-form-fields.md diff --git a/.changeset/34807-draft-preview-form-fields.md b/.changeset/34807-draft-preview-form-fields.md new file mode 100644 index 00000000000..1632f50f319 --- /dev/null +++ b/.changeset/34807-draft-preview-form-fields.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(console): under draft preview, the New record form draws a field that exists only in the draft, 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 that leaves those fields out of the record a create or update sends. A value typed into such a field, or its declared default, is never 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. From 1f101631101b43cd62977ae383a66393aa1aa994 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:46:39 +0000 Subject: [PATCH 4/8] fix(console): type the preview form data source at the modal call site Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- ui/packages/app-shell/src/console/AppContent.tsx | 2 +- .../src/utils/previewFormDataSource.test.tsx | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 40f383e6ce2..f27115c2c72 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -1799,7 +1799,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = }, ), }} - dataSource={formDataSource} + 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 index e6c7f8c6299..bd70bb3a454 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -63,10 +63,10 @@ const OVERLAY = { }; const makeAdapter = () => ({ - getObjectSchema: vi.fn(async () => structuredClone(PUBLISHED)), - create: vi.fn(async () => ({ id: 'r1' })), - update: vi.fn(async () => ({ id: 'r1' })), - findOne: vi.fn(async () => ({ id: 'r1' })), + 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(() => { @@ -180,7 +180,7 @@ describe('usePreviewFormDataSource (objectstack#34807)', () => { it('in preview it reads the object document through the metadata provider', async () => { const adapter = makeAdapter(); - const getItem = vi.fn(async () => structuredClone(OVERLAY)); + 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); @@ -234,7 +234,7 @@ describe('the global New modal under draft preview (objectstack#34807)', () => { 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 () => structuredClone(OVERLAY)); + 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()); From 03c259dcff3e740357fa68b768f375553e62a51c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:24:34 +0000 Subject: [PATCH 5/8] fix(console): draw draft-only preview fields disabled in record forms plugin-form maps the underscore-private _draftOnly marker onto a field's disabled in ObjectForm and fromObjectSchema; the preview data source still leaves such fields out of every write. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34807-draft-preview-form-fields.md | 7 ++-- .../app-shell/src/console/AppContent.tsx | 3 +- .../src/utils/previewFormDataSource.test.tsx | 9 ++--- .../src/utils/previewFormDataSource.ts | 29 ++++++++------- ...RecordFormPage.draftPreview-34807.test.tsx | 9 ++--- .../app-shell/src/views/RecordFormPage.tsx | 7 ++-- .../plugin-form/src/ObjectForm.test.tsx | 35 +++++++++++++++++++ ui/packages/plugin-form/src/ObjectForm.tsx | 4 ++- .../plugin-form/src/sectionFields.test.ts | 26 ++++++++++++++ ui/packages/plugin-form/src/sectionFields.ts | 7 +++- 10 files changed, 108 insertions(+), 28 deletions(-) diff --git a/.changeset/34807-draft-preview-form-fields.md b/.changeset/34807-draft-preview-form-fields.md index 1632f50f319..14716c1105f 100644 --- a/.changeset/34807-draft-preview-form-fields.md +++ b/.changeset/34807-draft-preview-form-fields.md @@ -1,10 +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, and never writes it +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 that leaves those fields out of the record a create or update sends. A value typed into such a field, or its declared default, is never 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. +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 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. `_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 f27115c2c72..041af0e3032 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -363,7 +363,8 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = const homePath = useHomePath(); const previewDrafts = usePreviewDrafts(); // objectstack#34807 — the global New/Edit modal reads its object definition - // through the draft overlay under preview; outside preview this is + // 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(); diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx index bd70bb3a454..ed98147275f 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -14,8 +14,8 @@ * 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, and Save leaves it out of the create: what the viewer typed into - * it and its declared default alike. + * 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. @@ -216,12 +216,13 @@ describe('the global New modal under draft preview (objectstack#34807)', () => { , ); - it('draws the draft-only field, and Save leaves it out of the create', async () => { + 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()); - fireEvent.change(document.body.querySelector('input[name="priority"]') as HTMLInputElement, { target: { value: 'urgent' } }); + 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); diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.ts b/ui/packages/app-shell/src/utils/previewFormDataSource.ts index 1b824dbbfee..94007ebf89c 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.ts +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.ts @@ -20,15 +20,17 @@ * * 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 the proxy's - * `create` / `update` leave its name out of the record they send: what the - * viewer typed into it, or its declared default, is never written (the draft - * bar above every preview page says nothing there is live until publish). - * ⛔ The field is not locked instead: a create form drops a field declared - * `readonly: true` (`filterCreateModeFields` in `@object-ui/plugin-form`) and - * does not evaluate `readonlyWhen`, so 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. + * 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. + * ⛔ 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 */ @@ -52,9 +54,12 @@ function isDocument(value: unknown): value is ObjectDocument { /** * The undeclared key that marks a field the draft adds: present in the draft - * overlay document, absent from the published one. Client-side only (the copy - * carrying it is never written back); a draft-preview reader that must keep - * such a name out of a data request reads it here. + * 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'; 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 index bbb1768b21a..2bb26a9ee82 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -14,8 +14,8 @@ * 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, so the field is drawn, and Save leaves it out of the - * create: what the viewer typed into it and its declared default alike. + * 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. @@ -98,12 +98,13 @@ function renderNew(preview: boolean) { } describe('RecordFormPage under draft preview (objectstack#34807)', () => { - it('draws the draft-only field with its draft label, and Save leaves it out of the create', async () => { + 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'); - fireEvent.change(document.body.querySelector('input[name="priority"]') as HTMLInputElement, { target: { value: 'urgent' } }); + 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); diff --git a/ui/packages/app-shell/src/views/RecordFormPage.tsx b/ui/packages/app-shell/src/views/RecordFormPage.tsx index fe3c55376e6..661f587b536 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.tsx @@ -93,9 +93,10 @@ export function RecordFormPage({ mode }: RecordFormPageProps) { const location = useLocation(); const dataSource = useAdapter(); // objectstack#34807 — under draft preview the form reads its object - // definition through the draft overlay (draft-only fields read-only); outside - // preview this is `dataSource` itself. Writes and the answer-warning claim - // below stay on the adapter. + // 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(); 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/sectionFields.test.ts b/ui/packages/plugin-form/src/sectionFields.test.ts index 56fc3aa2d83..6bb615125bb 100644 --- a/ui/packages/plugin-form/src/sectionFields.test.ts +++ b/ui/packages/plugin-form/src/sectionFields.test.ts @@ -450,3 +450,29 @@ 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(); + }); +}); diff --git a/ui/packages/plugin-form/src/sectionFields.ts b/ui/packages/plugin-form/src/sectionFields.ts index f253449f3c6..0775f5a75bf 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 From 9719bf98104b42b343c8d2f02e69b1014b020e22 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:57:10 +0000 Subject: [PATCH 6/8] test(plugin-form): enter the draft-preview form data source writes in the write census Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../plugin-form/src/affordanceGrantMap-12082.test.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) 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 From 1bb765d4af0095aeb6efa18a59498f2f38709c66 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:42:11 +0000 Subject: [PATCH 7/8] fix(console): a required draft-only preview field no longer blocks the record form save Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34807-draft-preview-form-fields.md | 2 +- .../src/utils/previewFormDataSource.test.tsx | 58 +++++++++++++++++-- .../src/utils/previewFormDataSource.ts | 11 +++- ...RecordFormPage.draftPreview-34807.test.tsx | 28 ++++++++- 4 files changed, 89 insertions(+), 10 deletions(-) diff --git a/.changeset/34807-draft-preview-form-fields.md b/.changeset/34807-draft-preview-form-fields.md index 14716c1105f..4f6a519b6eb 100644 --- a/.changeset/34807-draft-preview-form-fields.md +++ b/.changeset/34807-draft-preview-form-fields.md @@ -8,6 +8,6 @@ fix(console): under draft preview, the New record form draws a field that exists 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 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. +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. `_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/utils/previewFormDataSource.test.tsx b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx index ed98147275f..000bdc22f6b 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.test.tsx @@ -61,6 +61,15 @@ const OVERLAY = { 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)), @@ -89,6 +98,14 @@ describe('withDraftOnlyFields (objectstack#34807)', () => { 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)); @@ -190,7 +207,7 @@ describe('usePreviewFormDataSource (objectstack#34807)', () => { }); describe('the global New modal under draft preview (objectstack#34807)', () => { - function Modal({ adapter }: { adapter: ReturnType }) { + function Modal({ adapter, fields }: { adapter: ReturnType; fields: string[] }) { const ds = usePreviewFormDataSource(adapter); return ( { mode: 'create', open: true, title: 'New task', - fields: ['title', 'priority'], + fields, } as never} dataSource={ds as never} /> ); } - const renderModal = (preview: boolean, adapter: ReturnType) => + const renderModal = (preview: boolean, adapter: ReturnType, fields = ['title', 'priority']) => render( - + , ); @@ -233,6 +250,39 @@ describe('the global New modal under draft preview (objectstack#34807)', () => { 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)); diff --git a/ui/packages/app-shell/src/utils/previewFormDataSource.ts b/ui/packages/app-shell/src/utils/previewFormDataSource.ts index 94007ebf89c..7795004bb00 100644 --- a/ui/packages/app-shell/src/utils/previewFormDataSource.ts +++ b/ui/packages/app-shell/src/utils/previewFormDataSource.ts @@ -25,7 +25,9 @@ * 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. + * 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 @@ -74,7 +76,9 @@ export function draftOnlyFieldNames(schema: unknown): string[] { /** * 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}. Fields the + * 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 @@ -89,7 +93,8 @@ export function withDraftOnlyFields(published: unknown, overlay: unknown): unkno const fields: Record> = { ...publishedFields }; for (const [name, def] of Object.entries(overlay.fields)) { if (Object.prototype.hasOwnProperty.call(publishedFields, name)) continue; - fields[name] = { ...def, [DRAFT_ONLY_FIELD_KEY]: true }; + const { required: _required, requiredWhen: _requiredWhen, ...drawn } = def; + fields[name] = { ...drawn, [DRAFT_ONLY_FIELD_KEY]: true }; } return attachObjectSortability({ ...base, fields }, readObjectSortability(published)); } 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 index 2bb26a9ee82..6bd98b2d703 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -71,9 +71,19 @@ vi.mock('../providers/AdapterProvider', () => ({ useAdapter: () => ENV.adapter, })); -function setUp(objects: unknown[]) { +// 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 }, + }, +}; + +function setUp(objects: unknown[], overlay: unknown = OVERLAY) { ENV.objects = objects; - ENV.getItem = vi.fn(async () => structuredClone(OVERLAY)); + ENV.getItem = vi.fn(async () => structuredClone(overlay)); ENV.adapter = { getObjectSchema: vi.fn(async () => structuredClone(PUBLISHED)), create: vi.fn(async () => ({ id: 'r1', title: 'Ship it' })), @@ -115,6 +125,20 @@ describe('RecordFormPage under draft preview (objectstack#34807)', () => { 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('CONTROL: outside preview the form reads the published document once and draws no draft field', async () => { const { adapter, getItem } = setUp([PUBLISHED]); renderNew(false); From 75e777380dffd4f15bcc52f967ff3b3fa8d93ceb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:20:28 +0000 Subject: [PATCH 8/8] fix(plugin-form): a form view's required does not apply to a draft-only preview field Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34807-draft-preview-form-fields.md | 2 +- ...RecordFormPage.draftPreview-34807.test.tsx | 24 +++++++++++++++++++ .../plugin-form/src/sectionFields.test.ts | 12 ++++++++++ ui/packages/plugin-form/src/sectionFields.ts | 8 ++++++- 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/.changeset/34807-draft-preview-form-fields.md b/.changeset/34807-draft-preview-form-fields.md index 4f6a519b6eb..1a4f4e56085 100644 --- a/.changeset/34807-draft-preview-form-fields.md +++ b/.changeset/34807-draft-preview-form-fields.md @@ -10,4 +10,4 @@ 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. `_draftOnly` is an underscore-private convention between the console and this package, never an authoring key; nothing new is exported. +`@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/views/RecordFormPage.draftPreview-34807.test.tsx b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx index 6bd98b2d703..66fff75bf2a 100644 --- a/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx +++ b/ui/packages/app-shell/src/views/RecordFormPage.draftPreview-34807.test.tsx @@ -81,6 +81,16 @@ const REQUIRED_OVERLAY = { }, }; +// 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)); @@ -139,6 +149,20 @@ describe('RecordFormPage under draft preview (objectstack#34807)', () => { 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); diff --git a/ui/packages/plugin-form/src/sectionFields.test.ts b/ui/packages/plugin-form/src/sectionFields.test.ts index 6bb615125bb..10753bb58e7 100644 --- a/ui/packages/plugin-form/src/sectionFields.test.ts +++ b/ui/packages/plugin-form/src/sectionFields.test.ts @@ -475,4 +475,16 @@ describe('a `_draftOnly` field maps to a disabled FormField (objectstack#34807)' 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 0775f5a75bf..f1a74df5666 100644 --- a/ui/packages/plugin-form/src/sectionFields.ts +++ b/ui/packages/plugin-form/src/sectionFields.ts @@ -468,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),