From f964b2b19869fd05f56935d2f410d3f4ed980f1b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:27:35 +0000 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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 04/11] 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 05/11] 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 06/11] 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 4b5b476f7fcb2789d4954c84c35f8af765cbc677 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:28:35 +0000 Subject: [PATCH 07/11] fix(plugin-list): keep draft-only fields out of the list query under draft preview Under ?preview=draft the list data source answers getObjectSchema with the published document plus each draft-only field marked _draftOnly (the form half's readDraftPreviewObjectSchema). ListView leaves those names out of $select, $expand, $filter and $orderby and out of the Filter and Sort pickers, draws the column empty under its draft label, and notes a filter or sort it left out. The same wrap now covers ObjectDataPage and InterfaceListPage in preview. Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX Co-authored-by: Claude --- .../src/preview/unpublishedObjectReads.ts | 63 ++++- .../app-shell/src/views/InterfaceListPage.tsx | 7 +- .../app-shell/src/views/ObjectDataPage.tsx | 7 +- .../src/views/objectViewListRenderer.tsx | 22 +- ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + ui/packages/plugin-list/src/ListView.tsx | 228 ++++++++++++++++-- .../src/__tests__/ListView.harness.test.tsx | 199 +++++++++++++++ 17 files changed, 508 insertions(+), 29 deletions(-) diff --git a/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts b/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts index 73f69a38413..12c7ecbd442 100644 --- a/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts +++ b/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts @@ -27,10 +27,28 @@ * publish sentence. Every other failure (a 403, a 500, a refused `findOne`) * reaches the list unchanged, and outside the preview it is never installed, * so a missing object on the live console is still an error. + * + * objectstack#34807 (ruling 6946403206) — a list column on a field that exists + * only in the draft. The data door validates every `$select`, `$filter` and + * `$orderby` name against the PUBLISHED object, so a draft-only column refused + * the whole list query (`400 INVALID_FIELD`), and the list read its object + * definition from the adapter's published `getObjectSchema`, which does not + * know the field at all. Given the provider's overlay read, this wrapper's + * `getObjectSchema` answers {@link readDraftPreviewObjectSchema}: the + * published document plus each draft-only field with its draft label, marked + * `_draftOnly` (the form half's convention, `utils/previewFormDataSource.ts`), + * with the published sortability projection kept. `@object-ui/plugin-list` + * reads the marker and keeps those names out of every data request, drawing + * the column empty under its draft label. The data contract is unchanged: + * data reads never see a draft schema. */ +import { useMemo, useRef } from 'react'; import { answeredLoadFailure } from '@object-ui/react'; import type { DataSource } from '@object-ui/types'; +import { useMetadata } from '../providers/MetadataProvider.js'; +import { readDraftPreviewObjectSchema } from '../utils/previewFormDataSource.js'; +import { usePreviewDrafts } from './PreviewModeContext.js'; /** The data engine's answer for an object it has not registered. */ export const UNPUBLISHED_OBJECT_CODE = 'OBJECT_NOT_FOUND'; @@ -44,12 +62,19 @@ export function isUnpublishedObjectRefusal(err: unknown): boolean { * `ds`, except that a `find` the data engine refuses with * {@link UNPUBLISHED_OBJECT_CODE} answers an empty page and reports the * object through `onUnpublished`, so the caller can say why the list is empty. - * Every other member is the source's own, bound to it. + * Given `readOverlay` (the draft overlay's read of one object document), + * `getObjectSchema` answers {@link readDraftPreviewObjectSchema} over the + * source's own published read. Every other member is the source's own, bound + * to it. */ export function withUnpublishedObjectReads( ds: DataSource, onUnpublished: (objectName: string) => void, + readOverlay?: (objectName: string) => Promise, ): DataSource { + const getObjectSchema = readOverlay && typeof ds.getObjectSchema === 'function' + ? (objectName: string) => readDraftPreviewObjectSchema(ds, readOverlay, objectName) + : undefined; return new Proxy(ds, { get(target, prop, receiver) { if (prop === 'find') { @@ -63,8 +88,44 @@ export function withUnpublishedObjectReads( } }; } + if (prop === 'getObjectSchema' && getObjectSchema) return getObjectSchema; const value = Reflect.get(target, prop, receiver); return typeof value === 'function' ? value.bind(target) : value; }, }); } + +const IGNORE_UNPUBLISHED = (): void => {}; + +/** + * The data source a list page hands `ListView`: `ds` itself outside draft + * preview; inside it, {@link withUnpublishedObjectReads} over `ds`, reading + * draft-only fields through the provider's overlay (`useMetadata().getItem`, + * which reads through the preview client in preview). + * + * `revision` is the page's own draft-aware definition of the object (the + * provider's `objects` entry): a new one means the draft changed, and only + * then is a new wrapper made, so the list re-reads its definition when a + * field is drafted and otherwise keeps one data source identity. A page with + * no publish sentence of its own passes no `onUnpublished`. + */ +export function usePreviewListDataSource( + ds: T, + revision?: unknown, + onUnpublished: (objectName: string) => void = IGNORE_UNPUBLISHED, +): T { + const previewDrafts = usePreviewDrafts(); + const { getItem } = useMetadata(); + const unpublishedRef = useRef(onUnpublished); + unpublishedRef.current = onUnpublished; + return useMemo(() => { + if (!previewDrafts || !ds) return ds; + return withUnpublishedObjectReads( + ds, + (name) => unpublishedRef.current(name), + (name) => getItem('object', name), + ) as T; + // `revision` is read for its identity only: see the doc above. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [previewDrafts, ds, getItem, revision]); +} diff --git a/ui/packages/app-shell/src/views/InterfaceListPage.tsx b/ui/packages/app-shell/src/views/InterfaceListPage.tsx index 2259e27cadf..d2680a7dfc9 100644 --- a/ui/packages/app-shell/src/views/InterfaceListPage.tsx +++ b/ui/packages/app-shell/src/views/InterfaceListPage.tsx @@ -38,6 +38,7 @@ import { usePermissions } from '@object-ui/permissions'; import type { ActionBarSchema, ListViewSchema } from '@object-ui/types'; import { useMetadata } from '../providers/MetadataProvider.js'; import { metadataText } from '../hooks/useNavTargetLabel.js'; +import { usePreviewListDataSource } from '../preview/unpublishedObjectReads.js'; import { useTenancyPosture } from '../hooks/useTenancyPosture.js'; import { useNavigationContext } from '../context/NavigationContext.js'; import { matchAppBySegment } from '../utils/index.js'; @@ -318,6 +319,10 @@ export function InterfaceListPage({ page, className, onConfigChange, reserveEdit : metadata.objects || []; // Not memoised: the scope's list is read afresh each render, as `objects` was. const objectDef = sourceObjects.find((o: any) => o?.name === cfg.source); + // objectstack#34807 — in the draft preview the list reads its object + // definition with the draft-only fields marked, so a column on one is drawn + // empty instead of refusing the whole list query; outside it, the adapter. + const listDataSource = usePreviewListDataSource(dataSource, objectDef); const resolvedView = React.useMemo( () => resolveSourceView(objectDef, cfg.sourceView), [objectDef, cfg.sourceView], @@ -684,7 +689,7 @@ export function InterfaceListPage({ page, className, onConfigChange, reserveEdit
onConfigChange({ sort }) : undefined} diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.tsx index ba7c0bf25c8..c82e168c527 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.tsx @@ -78,6 +78,7 @@ import { PREVIEW_QUERY_FLAG, PREVIEW_QUERY_VALUE, } from '../preview/PreviewModeContext.js'; +import { usePreviewListDataSource } from '../preview/unpublishedObjectReads.js'; import { useTenancyPosture } from '../hooks/useTenancyPosture.js'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; import type { RowCrudPredicates } from '../utils/crudAffordances.js'; @@ -262,6 +263,10 @@ export function ObjectDataPage({ dataSource, objects }: any) { () => (objects || []).find((o: any) => o.name === objectName), [objects, objectName], ); + // objectstack#34807 — in the draft preview the list reads its object + // definition with the draft-only fields marked, so a column on one is drawn + // empty instead of refusing the whole list query; outside it, the adapter. + const listDataSource = usePreviewListDataSource(dataSource, objectDef); // ADR-0047 filter persistence — same wiring as InterfaceListPage: restore // `uf_*` once at mount, mirror selection changes back (replace, no history @@ -711,7 +716,7 @@ export function ObjectDataPage({ dataSource, objects }: any) { {schema && ( >(() => new Set()); - const unpublishedReadsRef = useRef(new WeakMap()); + const unpublishedReadsRef = useRef(new WeakMap()); const previewDataSource = useCallback((ds: DataSource): DataSource => { const cached = unpublishedReadsRef.current.get(ds); - if (cached) return cached; - const wrapped = withUnpublishedObjectReads(ds, (name) => - setUnpublishedObjects((prev) => (prev.has(name) ? prev : new Set(prev).add(name))), + if (cached && cached.revision === objectDef) return cached.wrapped; + const wrapped = withUnpublishedObjectReads( + ds, + (name) => setUnpublishedObjects((prev) => (prev.has(name) ? prev : new Set(prev).add(name))), + (name) => getMetadataItem('object', name), ); - unpublishedReadsRef.current.set(ds, wrapped); + unpublishedReadsRef.current.set(ds, { revision: objectDef, wrapped }); return wrapped; - }, []); + }, [objectDef, getMetadataItem]); const renderListView = useCallback(({ schema: listSchema, dataSource: rawDs, onEdit: editHandler, className, refreshKey: pluginRefreshKey }: any) => { const ds = previewDrafts && rawDs ? previewDataSource(rawDs) : rawDs; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 6c1b37e4d93..d7d054ab3da 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1043,6 +1043,7 @@ const ar = { removeGroup: "إزالة", groupingUnstoredNotice: "لا يمكن تجميع هذه القائمة حسب {{fields}}: تُحسب القيمة عند العرض ولا تُخزَّن. تُعرض القائمة دون هذا التجميع.", groupingUnstoredRemove: "إزالة من التجميع", + draftOnlyQueryDropped: "لم تتم التصفية أو الفرز حسب {{fields}}: هذا الحقل موجود في المسودة فقط حتى النشر.", inlineEditShort: "تحرير مضمّن", inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", }, diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index e13a0334a49..0c3e94aa9b5 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -934,6 +934,7 @@ const de = { removeGroup: "Entfernen", groupingUnstoredNotice: "Diese Liste kann nicht nach {{fields}} gruppiert werden: Der Wert wird bei der Anzeige berechnet und nicht gespeichert. Die Liste wird ohne diese Gruppierung angezeigt.", groupingUnstoredRemove: "Aus Gruppierung entfernen", + draftOnlyQueryDropped: "Nicht nach {{fields}} gefiltert oder sortiert: Das Feld existiert bis zur Veröffentlichung nur im Entwurf.", inlineEditShort: "Inline bearbeiten", inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", }, diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 05de0782a93..59bb29d7ee4 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1223,6 +1223,7 @@ const en = { removeGroup: 'Remove', groupingUnstoredNotice: 'This list cannot be grouped by {{fields}}: its value is calculated when shown, not stored. The list is shown without that grouping.', groupingUnstoredRemove: 'Remove from grouping', + draftOnlyQueryDropped: 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', inlineEditShort: 'Edit inline', inlineEditLabel: 'Edit records inline (click a cell to edit)', }, diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 29a924f63e9..60dfe2f15ce 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -964,6 +964,7 @@ const es = { removeGroup: "Eliminar", groupingUnstoredNotice: "Esta lista no se puede agrupar por {{fields}}: su valor se calcula al mostrarse y no se almacena. La lista se muestra sin esa agrupación.", groupingUnstoredRemove: "Quitar de la agrupación", + draftOnlyQueryDropped: "Sin filtrar ni ordenar por {{fields}}: solo existe en el borrador hasta que publiques.", inlineEditShort: "Edición en línea", inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", }, diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d8267583b7a..546bb62f97e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -959,6 +959,7 @@ const fr = { removeGroup: "Supprimer", groupingUnstoredNotice: "Cette liste ne peut pas être regroupée par {{fields}} : sa valeur est calculée à l’affichage et n’est pas stockée. La liste est affichée sans ce regroupement.", groupingUnstoredRemove: "Retirer du regroupement", + draftOnlyQueryDropped: "Non filtré ni trié par {{fields}} : ce champ n’existe que dans le brouillon jusqu’à la publication.", inlineEditShort: "Édition en ligne", inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", }, diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 69b4c36ae06..2e92e1fb3c0 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -934,6 +934,7 @@ const ja = { removeGroup: "削除", groupingUnstoredNotice: "{{fields}} ではこの一覧をグループ化できません。値は表示時に計算され、保存されていません。このグループ化を除いて一覧を表示しています。", groupingUnstoredRemove: "グループ化から削除", + draftOnlyQueryDropped: "{{fields}} での絞り込みと並べ替えは行われていません。下書きにのみ存在し、公開後に有効になります。", inlineEditShort: "インライン編集", inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", }, diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a390244a8b2..3d9f7b5a9cb 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -934,6 +934,7 @@ const ko = { removeGroup: "제거", groupingUnstoredNotice: "{{fields}} 기준으로 이 목록을 그룹화할 수 없습니다. 값이 표시될 때 계산되며 저장되지 않습니다. 해당 그룹화 없이 목록을 표시합니다.", groupingUnstoredRemove: "그룹화에서 제거", + draftOnlyQueryDropped: "{{fields}} 기준 필터와 정렬이 적용되지 않았습니다. 초안에만 있으며 게시 후 적용됩니다.", inlineEditShort: "인라인 편집", inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", }, diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index e229bb8cb57..9208302cd6a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -959,6 +959,7 @@ const pt = { removeGroup: "Remover", groupingUnstoredNotice: "Esta lista não pode ser agrupada por {{fields}}: o valor é calculado ao ser exibido e não é armazenado. A lista é exibida sem esse agrupamento.", groupingUnstoredRemove: "Remover do agrupamento", + draftOnlyQueryDropped: "Sem filtrar nem ordenar por {{fields}}: existe apenas no rascunho até você publicar.", inlineEditShort: "Edição em linha", inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", }, diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 2b96fe82ee3..665ce883fed 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -990,6 +990,7 @@ const ru = { removeGroup: "Удалить", groupingUnstoredNotice: "Этот список нельзя сгруппировать по полю {{fields}}: его значение вычисляется при отображении и не хранится. Список показан без этой группировки.", groupingUnstoredRemove: "Убрать из группировки", + draftOnlyQueryDropped: "Без фильтрации и сортировки по {{fields}}: поле есть только в черновике до публикации.", inlineEditShort: "Встроенное редактирование", inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", }, diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f3936cb8be0..bac7e1210f2 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -961,6 +961,7 @@ const zh = { removeGroup: '删除', groupingUnstoredNotice: '无法按 {{fields}} 分组:它的值在显示时计算,并未存储。列表已暂不按它分组显示。', groupingUnstoredRemove: '从分组中移除', + draftOnlyQueryDropped: '未按 {{fields}} 筛选或排序:它仅存在于草稿中,发布后才生效。', inlineEditShort: '行内编辑', inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', }, diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index bb963982c9f..58b801c4f34 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -961,6 +961,7 @@ const zhHant = { removeGroup: '刪除', groupingUnstoredNotice: '無法按 {{fields}} 分組:它的值在顯示時計算,並未儲存。列表已暫不按它分組顯示。', groupingUnstoredRemove: '從分組中移除', + draftOnlyQueryDropped: '未按 {{fields}} 篩選或排序:它僅存在於草稿中,釋出後才生效。', inlineEditShort: '行內編輯', inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', }, diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index f62cd135210..1fb8ed75e0e 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -1005,12 +1005,30 @@ export function normalizeFilters(filters: any[]): any[] { * `filter`, and its last fallback was `table.defaultFilters`, declared * `Record` (retired since objectui#12030; `table.filter` takes * the same object). `toFilterNode` now converts it instead. + * + * `draftOnly` (objectstack#34807): the fields the object definition marks as + * existing only in the draft preview. Every comparison on one is left out of + * the merged node, whichever of the sources carried it, since the data door + * refuses the name and with it the whole list. Empty outside the preview, + * where the node is exactly what it was. */ export function buildEffectiveFilter( baseFilter: unknown, currentFilters: FilterBuilderRowGroup, userFilterConditions: any[], queueSittingConditions: ReadonlyArray = NO_QUEUE_SITTING_CONDITIONS, + draftOnly: ReadonlySet = NO_DRAFT_ONLY_FIELDS, +): any[] | Record | undefined { + const merged = mergeEffectiveFilterSources(baseFilter, currentFilters, userFilterConditions, queueSittingConditions); + if (draftOnly.size === 0) return merged; + return omitDraftOnlyFilterFields(merged, draftOnly, new Set()) as any[] | Record | undefined; +} + +function mergeEffectiveFilterSources( + baseFilter: unknown, + currentFilters: FilterBuilderRowGroup, + userFilterConditions: any[], + queueSittingConditions: ReadonlyArray, ): any[] | Record | undefined { const userFilter = convertFilterGroupToAST(currentFilters); return mergeFilterNodes( @@ -1460,6 +1478,8 @@ export const LIST_DEFAULT_TRANSLATIONS: Record = { 'list.recordOpenPage': 'Full page', 'list.recordOpenNote': 'Your own preference, not part of the object’s declaration. A record’s ↗ always opens the full page.', 'list.recordOpenDeclaredPage': 'This object is declared to open as a full page', + // The draft preview's note on a sort or filter it left out (objectstack#34807). + 'list.draftOnlyQueryDropped': 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', // Heading of the record-detail overlay this view opens when a child view's // row is clicked (objectui#3426). Borrowed from the `detail.*` namespace // rather than minted as `list.recordDetail`: `NavigationOverlay` already @@ -1819,6 +1839,89 @@ function describeRefusedPageSize( ); } +/** + * objectstack#34807 (ruling 6946403206) — the fields an object definition + * marks as existing only in the DRAFT. Under the console's draft preview + * (`?preview=draft`) the host's data source answers `getObjectSchema` with the + * published document plus each field only the draft declares, carrying this + * undeclared key. The data door validates every `$select`, `$expand`, + * `$filter` and `$orderby` name against the PUBLISHED object and answers + * `400 INVALID_FIELD` for one it does not know, so a single draft-only column + * used to refuse the whole list. Such a name is left out of every request this + * component makes and of the Filter and Sort pickers; its column is drawn + * empty under the field's draft label, and a filter or sort that names it is + * left out with a note (`list.draftOnlyQueryDropped`). + * + * An underscore-private convention between `@object-ui/app-shell`, which sets + * it, and this package: never an authoring key, never declared, never written + * back. Outside the preview no definition carries it, and every reader below + * answers exactly as it did before. + */ +const DRAFT_ONLY_FIELD_KEY = '_draftOnly'; +const NO_DRAFT_ONLY_FIELDS: ReadonlySet = new Set(); +const NO_DRAFT_ONLY_QUERY_DROPS: readonly string[] = []; + +/** The names `objectDef` marks {@link DRAFT_ONLY_FIELD_KEY}, in either field-map shape. */ +function readDraftOnlyFieldNames(objectDef: unknown): ReadonlySet { + const raw = (objectDef as { fields?: unknown } | null | undefined)?.fields; + if (!raw || typeof raw !== 'object') return NO_DRAFT_ONLY_FIELDS; + const entries: Array<[unknown, unknown]> = Array.isArray(raw) + ? raw.map((f) => [(f as { name?: unknown } | null)?.name, f]) + : Object.entries(raw as Record); + const names = new Set(); + for (const [name, def] of entries) { + if (typeof name === 'string' && !!def && typeof def === 'object' + && (def as Record)[DRAFT_ONLY_FIELD_KEY] === true) names.add(name); + } + return names.size > 0 ? names : NO_DRAFT_ONLY_FIELDS; +} + +/** Whether a field reference (`owner` or a dotted `owner.name`) starts at a draft-only field. */ +function refersToDraftOnlyField(ref: unknown, draftOnly: ReadonlySet): ref is string { + return typeof ref === 'string' && draftOnly.has(ref.split('.')[0]); +} + +/** `fields` (either field-map shape) without the draft-only ones. */ +function withoutDraftOnlyFields(fields: unknown, draftOnly: ReadonlySet): any { + if (Array.isArray(fields)) { + return fields.filter((f) => !draftOnly.has((f as { name?: unknown } | null)?.name as string)); + } + if (!fields || typeof fields !== 'object') return fields; + return Object.fromEntries(Object.entries(fields as Record).filter(([name]) => !draftOnly.has(name))); +} + +/** + * The array filter AST without every comparison on a draft-only field, or + * `undefined` when nothing is left. The shapes are the ones the server reads: + * an `and` / `or` group, a flat list (implicit AND) and a 2- or 3-element + * comparison. A group left with one child becomes that child. Anything else is + * returned as it came. The names removed are added to `dropped`. + */ +function omitDraftOnlyFilterFields(node: unknown, draftOnly: ReadonlySet, dropped: Set): unknown { + if (!Array.isArray(node) || node.length === 0) return node; + const head = node[0]; + const keyword = typeof head === 'string' ? head.toLowerCase() : undefined; + if (keyword === 'and' || keyword === 'or') { + const kept = node.slice(1) + .map((child) => omitDraftOnlyFilterFields(child, draftOnly, dropped)) + .filter((child) => child !== undefined); + if (kept.length === 0) return undefined; + return kept.length === 1 ? kept[0] : [head, ...kept]; + } + if (Array.isArray(head)) { + const kept = node + .map((child) => omitDraftOnlyFilterFields(child, draftOnly, dropped)) + .filter((child) => child !== undefined); + return kept.length === 0 ? undefined : kept; + } + if (typeof head === 'string' && typeof node[1] === 'string' && node.length <= 3 + && refersToDraftOnlyField(head, draftOnly)) { + dropped.add(head.split('.')[0]); + return undefined; + } + return node; +} + /** * Field-level READ for the field lists the toolbar offers: the Filter panel's * (`filterFields`, objectui#11925), the Sort picker's (`sortFields`, @@ -2131,6 +2234,16 @@ export const ListView = React.forwardRef(({ [objectDef], ); + /** + * objectstack#34807 — the fields `objectDef` marks as existing only in the + * draft preview (see `readDraftOnlyFieldNames`). Read once, beside the + * definition, for every leg that keeps them out of a request: the + * projection, `$expand`, the filter (`buildEffectiveFilter`), the sort + * (`serverSort`) and the Filter and Sort pickers. One shared empty set + * outside the preview, so no dependency list sees a new identity there. + */ + const draftOnlyFields = React.useMemo(() => readDraftOnlyFieldNames(objectDef), [objectDef]); + /** * objectui#12966 — the object's `search` resolves to no field, so the server * refuses any term with `400 INVALID_FIELD`: no quick-search box, and a term @@ -2252,12 +2365,17 @@ export const ListView = React.forwardRef(({ * the next write. No signal served ⇒ sent unchanged, as before * objectstack#10235, because there is no verdict to filter by. */ - const serverSort = React.useMemo( - () => (platformSortability + const serverSort = React.useMemo(() => { + const sortable = platformSortability ? filterPlatformSortableSort(currentSort, platformSortability) - : currentSort), - [currentSort, platformSortability], - ); + : currentSort; + // objectstack#34807 — a draft-only field is not sortable by the data door + // whatever the projection served (the published one does not name it, and + // an older deployment or a never-published object serves none at all). + return draftOnlyFields.size > 0 + ? sortable.filter((item) => !refersToDraftOnlyField(item.field, draftOnlyFields)) + : sortable; + }, [currentSort, platformSortability, draftOnlyFields]); /** * The view's DECLARED sort, for the "reset to default" affordance @@ -2658,6 +2776,32 @@ export const ListView = React.forwardRef(({ ? QUEUE_SITTING_CONDITIONS : NO_QUEUE_SITTING_CONDITIONS; + /** + * objectstack#34807 — the draft-only fields a sort or filter on this list + * names, each left out of the request (`serverSort`, `buildEffectiveFilter`) + * because the data door refuses it. Said in one line above the rows + * (`list.draftOnlyQueryDropped`) while it is true, so the rows are not read + * as filtered or sorted by it. Empty outside the draft preview. + */ + const draftOnlyQueryDrops = React.useMemo(() => { + if (draftOnlyFields.size === 0) return NO_DRAFT_ONLY_QUERY_DROPS; + const dropped = new Set(); + for (const item of currentSort) { + if (refersToDraftOnlyField(item.field, draftOnlyFields)) dropped.add(item.field.split('.')[0]); + } + try { + omitDraftOnlyFilterFields( + mergeEffectiveFilterSources(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions), + draftOnlyFields, + dropped, + ); + } catch (error) { + // A malformed filter is the fetch's own load error to raise, not this line's. + if (!(error instanceof FilterOperatorError)) throw error; + } + return dropped.size > 0 ? Array.from(dropped) : NO_DRAFT_ONLY_QUERY_DROPS; + }, [draftOnlyFields, currentSort, authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions]); + // User filters render ONLY when explicitly configured (ADR-0047 §data // mode): saved list views already act as the preset switcher, so an // unconfigured view keeps a clean toolbar instead of growing auto-derived @@ -3250,7 +3394,12 @@ export const ListView = React.forwardRef(({ if (read.expand) collected.add(read.field); } const augmented = collected.size > 0 ? Array.from(collected) : undefined; - const expandable = buildExpandFields(objectDef?.fields, augmented); + // objectstack#34807 — a draft-only lookup is not expanded: the data door + // refuses a relation the published object does not declare. + const expandable = buildExpandFields( + draftOnlyFields.size > 0 ? withoutDraftOnlyFields(objectDef?.fields, draftOnlyFields) : objectDef?.fields, + augmented, + ); // [objectui#7215] FIELD-LEVEL SECURITY ON `$expand`, the half objectui#6898 // left open on both projection sites. `$select` on a denied lookup asks for // its BARE FOREIGN KEY; `$expand` asks the server to RESOLVE it and return @@ -3294,6 +3443,7 @@ export const ListView = React.forwardRef(({ schema.map, perms, schema.objectName, + draftOnlyFields, ]); /** @@ -3630,7 +3780,7 @@ export const ListView = React.forwardRef(({ try { // Construct filter — shared with the export path so the file a user // downloads is built from the same three sources as the rows on screen. - const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions); + const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); // Convert sort to query format // Use array format to ensure order is preserved (Object keys are not guaranteed ordered) @@ -3670,9 +3820,15 @@ export const ListView = React.forwardRef(({ // `addSpeculative`) — the shape `ObjectGrid` (`ensureId([])` keeps // `['id']`) and `RelatedList` (objectui#10186) send. if (rawCols.length === 0) return undefined; - const cols = (perms?.isLoaded && schema.objectName) - ? rawCols.filter(c => perms.checkField(schema.objectName!, c, 'read')) + // objectstack#34807 — a column on a draft-only field is drawn (empty, + // under its draft label) but never asked for: the data door knows + // only the published object and refuses the whole query for it. + const servedCols = draftOnlyFields.size > 0 + ? rawCols.filter(c => !refersToDraftOnlyField(c, draftOnlyFields)) : rawCols; + const cols = (perms?.isLoaded && schema.objectName) + ? servedCols.filter(c => perms.checkField(schema.objectName!, c, 'read')) + : servedCols; // Don't speculatively add `_id` / `name` — some backends reject // unknown select keys with an empty result set rather than // ignoring them. Stick to the user-requested columns plus the @@ -3701,7 +3857,9 @@ export const ListView = React.forwardRef(({ const names = Array.isArray(f) ? (f as any[]).map(x => x?.name).filter((n): n is string => typeof n === 'string') : Object.keys(f); - const s = new Set(names); + // objectstack#34807 — a draft-only field is no real field of the + // object the data door reads, so no speculative binding asks for it. + const s = new Set(names.filter((n) => !draftOnlyFields.has(n))); s.add('id'); s.add('created_at'); s.add('updated_at'); return s; })(); @@ -4291,7 +4449,7 @@ export const ListView = React.forwardRef(({ // silently un-suppresses nothing, because the finding it was suppressing // simply moves elsewhere. Add prose ABOVE this point, never below it. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, schema.searchableFields, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on + }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, schema.searchableFields, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, draftOnlyFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on // Any change to the result-defining inputs (object, filters, sort, search, // grouping, page size) invalidates the current page number — snap back to @@ -4717,7 +4875,7 @@ export const ListView = React.forwardRef(({ let selfQueryFilter: unknown = authoredFilter; if (currentView === 'gantt' || currentView === 'tree' || currentView === 'chart' || gridOwnsGroupedFetch || kanbanLanesPaged) { try { - const value = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions); + const value = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); const key = JSON.stringify(value ?? null); const cached = selfQueryFilterRef.current; if (cached && cached.key === key) { @@ -5557,13 +5715,17 @@ export const ListView = React.forwardRef(({ return candidateFields .filter((f) => canReadField(perms, schema.objectName, f.value)) .filter((f) => !isHidden(f.value) || held.has(f.value)) + // objectstack#34807 — a draft-only field cannot filter the list (the + // data door refuses it), so it is not offered; a held condition naming + // one keeps its row, so it can be removed. + .filter((f) => !draftOnlyFields.has(f.value) || held.has(f.value)) .map((field, index) => ({ field, index, tier: tierOf(field.value) })) .sort((a, b) => a.tier - b.tier || (a.tier === 0 ? columnRank.get(a.field.value)! - columnRank.get(b.field.value)! : a.index - b.index), ) .map(({ field }) => field); - }, [candidateFields, currentFilters.conditions, effectiveFields, objectDef, schema.objectName, perms]); + }, [candidateFields, currentFilters.conditions, effectiveFields, objectDef, schema.objectName, perms, draftOnlyFields]); // Sort candidates: ALL fields the view can name, minus the ones the sort // cannot honestly reach (objectui#4243 — previously ⊂ filter candidates). @@ -5659,9 +5821,11 @@ export const ListView = React.forwardRef(({ const offered = canReadField(perms, schema.objectName, field.value) && !isDeclaredHidden(defs, field.value); if (!offered && !inUse.has(field.value)) continue; const relational = EXPANDABLE_FIELD_TYPES.has(field.type); - const platformSortable = platformSortability + // A draft-only field (objectstack#34807) is never sortable: the data + // door refuses it, whatever the projection says. + const platformSortable = !draftOnlyFields.has(field.value) && (platformSortability ? isPlatformSortableField(platformSortability, field.value) - : !UNMATERIALIZED_FIELD_TYPES.has(field.type); + : !UNMATERIALIZED_FIELD_TYPES.has(field.type)); // `type` lets the picker name a date's direction as time // (objectstack#27520): "Oldest → Newest", not "A → Z". if (offered && !relational && platformSortable) { @@ -5682,7 +5846,7 @@ export const ListView = React.forwardRef(({ if (relational) excluded = true; } return { sortFields: fields, sortHasRelationalField: excluded, sortPicksRelationalField: picked }; - }, [candidateFields, currentSort, t, platformSortability, perms, schema.objectName, objectDef]); + }, [candidateFields, currentSort, t, platformSortability, perms, schema.objectName, objectDef, draftOnlyFields]); /** * [#6455] THE persist boundary: what this picker LISTS is not what it @@ -5855,9 +6019,11 @@ export const ListView = React.forwardRef(({ && !!schema.objectName && exportConfig?.streaming !== false; if (serverEligible) { - const fields = effectiveFields + // A draft-only column (objectstack#34807) is drawn empty, never asked for. + const fields = (effectiveFields .map((f: any) => columnIdentity(f)) - .filter(Boolean) as string[]; + .filter(Boolean) as string[]) + .filter((f) => !refersToDraftOnlyField(f, draftOnlyFields)); // The rows on screen were asked for with `serverSort`, so the file is too: // a refused entry would fail the export the way it failed the list. @@ -5878,7 +6044,7 @@ export const ListView = React.forwardRef(({ // file, no message. Here it lands in the catch below, which names it // in the toolbar the way the data fetch's own `try` names it in the // load-error panel — and nothing is exported unfiltered. - const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions); + const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); const blob = await dataSource!.exportDownload!(schema.objectName!, { format: format as 'csv' | 'xlsx' | 'json', fields: fields.length ? fields : undefined, @@ -5972,7 +6138,7 @@ export const ListView = React.forwardRef(({ setShowExport(false); // `searchTerm` / `searchableFields` belong here: the export now narrows by // the active search, so a stale closure would export the wrong row set. - }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, schema.searchableFields, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t]); + }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, schema.searchableFields, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t, draftOnlyFields]); // All available fields for hide/show (with i18n) // @@ -7405,6 +7571,28 @@ export const ListView = React.forwardRef(({
)} + {/* objectstack#34807 — a sort or filter naming a field that exists only + in the draft preview is left out of the query (see + `draftOnlyQueryDrops`); this line says so, instead of the data door + refusing the whole list. */} + {draftOnlyQueryDrops.length > 0 && ( +
+
+ )} + {/* View Content */}
{/* Re-fetch indicator: thin top progress bar shown when refreshing diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 45bc257ce6a..509b42e5b48 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -1851,6 +1851,205 @@ describe('ListView.refusedSortNotSent-30024', () => { }); }); +// ── ListView.draftOnlyColumn-34807 ─────────────────────────────────────────── + +/** + * objectstack#34807 (ruling 6946403206) — under the console's draft preview a + * list column on a field that exists only in the draft made the data door + * refuse the whole list query (`400 INVALID_FIELD`): it validates every + * `$select`, `$filter` and `$orderby` name against the PUBLISHED object. + * + * In the preview the host's data source answers `getObjectSchema` with the + * published document plus each draft-only field, marked with the + * underscore-private `_draftOnly` key (`@object-ui/app-shell`'s + * `preview/unpublishedObjectReads.ts` sets it; the literal is pinned here and + * there). `ListView` keeps such a name out of every request and out of the + * Filter and Sort pickers, draws the column empty under the draft label, and + * says in one line that a filter or sort on it was left out. + * + * The data source below answers as the data door does: any request that names + * `priority` is refused with `400 INVALID_FIELD`. CONTROL: the same view with + * `priority` published (no marker) asks for it exactly as before, with no note. + */ +describe('ListView.draftOnlyColumn-34807', () => { + restoreAfterBlock(); + + const OBJECT = 'tracker_task'; + const PUBLISHED_FIELDS = { + title: { name: 'title', type: 'text', label: 'Title' }, + status: { name: 'status', type: 'select', label: 'Status', options: [{ label: 'Open', value: 'open' }] }, + }; + /** The field the draft adds: its draft definition, marked by the preview's data source. */ + const DRAFT_PRIORITY = { + name: 'priority', + type: 'select', + label: 'Priority (draft)', + options: [{ label: 'High', value: 'high' }], + _draftOnly: true, + }; + + function makeDataSource(opts: { draft: boolean; servesSignal?: boolean }) { + const published = opts.draft + ? PUBLISHED_FIELDS + : { ...PUBLISHED_FIELDS, priority: { name: 'priority', type: 'select', label: 'Priority', options: DRAFT_PRIORITY.options } }; + return { + find: vi.fn(async (_object: string, params: Record) => { + if (opts.draft && JSON.stringify(params ?? {}).includes('"priority')) { + throw Object.assign(new Error(`Unknown field 'priority' on object '${OBJECT}'`), { + status: 400, + code: 'INVALID_FIELD', + }); + } + return { data: [{ id: 't1', title: 'Write the spec', status: 'open' }], total: 1 }; + }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => { + const schema = { + name: OBJECT, + label: 'Task', + fields: opts.draft ? { ...published, priority: { ...DRAFT_PRIORITY } } : published, + }; + // The published projection: it names no draft-only field. + if (opts.servesSignal) attachObjectSortability(schema, resolveObjectSortability({ name: OBJECT, fields: published } as any)); + return schema; + }), + }; + } + + async function mountList( + opts: { draft: boolean; servesSignal?: boolean }, + schemaExtra: Record = {}, + props: Record = {}, + ) { + const dataSource = makeDataSource(opts); + const schema = { + type: 'list-view', + objectName: OBJECT, + viewType: 'grid', + columns: ['title', 'priority'], + compactToolbar: false, + ...schemaExtra, + } as unknown as ListViewSchema; + render( + + + , + ); + await screen.findByText('Write the spec'); + await Promise.allSettled(dataSource.find.mock.results.map((r: any) => r.value)); + const lastParams = () => (dataSource.find.mock.calls.at(-1)?.[1] ?? {}) as Record; + return { dataSource, lastParams }; + } + + const notice = () => screen.queryByTestId('list-draft-only-query-notice'); + const everyRequestOmitsPriority = (dataSource: ReturnType) => { + expect(dataSource.find).toHaveBeenCalled(); + for (const [, params] of dataSource.find.mock.calls) { + expect(JSON.stringify(params ?? {})).not.toContain('"priority'); + } + }; + + const text = (el: Element | null | undefined) => el?.textContent?.trim() ?? ''; + async function comboboxOptions(trigger: HTMLElement): Promise { + fireEvent.click(trigger); + const listbox = await screen.findByRole('listbox'); + const labels = within(listbox).getAllByRole('option').map(text); + fireEvent.keyDown(listbox, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull()); + return labels; + } + async function popoverFirstComboboxOptions(name: RegExp): Promise { + const trigger = screen.getByRole('button', { name }); + fireEvent.click(trigger); + await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'true')); + const content = document.getElementById(trigger.getAttribute('aria-controls') ?? ''); + if (!content) throw new Error(`no popover content for "${text(trigger)}"`); + try { + return await comboboxOptions(within(content).getAllByRole('combobox')[0]); + } finally { + fireEvent.click(trigger); + await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'false')); + } + } + + beforeEach(() => vi.clearAllMocks()); + afterEach(() => cleanup()); + + it('draws the draft-only column empty under its draft label, and never asks for it', async () => { + const { dataSource, lastParams } = await mountList({ draft: true }); + expect(screen.queryByTestId('list-error-state')).toBeNull(); + expect(screen.getAllByText('Priority (draft)').length).toBeGreaterThan(0); + everyRequestOmitsPriority(dataSource); + expect(lastParams().$select).toEqual(['id', 'title']); + expect(notice()).toBeNull(); + }); + + it('leaves a viewer filter on it out of $filter, keeps the rest, and says so', async () => { + const { dataSource, lastParams } = await mountList({ draft: true }, {}, { + initialFilters: { + id: 'root', + logic: 'and', + conditions: [ + { id: 'c1', field: 'priority', operator: 'equals', value: 'high' }, + { id: 'c2', field: 'title', operator: 'contains', value: 'spec' }, + ], + }, + }); + expect(screen.queryByTestId('list-error-state')).toBeNull(); + everyRequestOmitsPriority(dataSource); + expect(JSON.stringify(lastParams().$filter)).toContain('"title"'); + expect(notice()).not.toBeNull(); + expect(text(notice())).toContain('Priority (draft)'); + }); + + it('leaves a sort on it out of $orderby with no projection served, and says so', async () => { + const { dataSource, lastParams } = await mountList({ draft: true }, { + sort: [{ field: 'priority', order: 'desc' }, { field: 'title', order: 'asc' }], + }); + expect(screen.queryByTestId('list-error-state')).toBeNull(); + everyRequestOmitsPriority(dataSource); + expect(lastParams().$orderby).toEqual([{ field: 'title', order: 'asc' }]); + expect(text(notice())).toContain('Priority (draft)'); + }); + + it('the served published projection refuses it too: the sort leaves it out (readObjectSortability)', async () => { + const { dataSource, lastParams } = await mountList({ draft: true, servesSignal: true }, { + sort: [{ field: 'priority', order: 'desc' }, { field: 'title', order: 'asc' }], + }); + everyRequestOmitsPriority(dataSource); + expect(lastParams().$orderby).toEqual([{ field: 'title', order: 'asc' }]); + }); + + it('offers it in neither the Filter panel nor the Sort picker', async () => { + await mountList({ draft: true }, { sort: [{ field: 'title', order: 'asc' }] }, { + initialFilters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'title', operator: 'contains', value: 'a' }] }, + }); + const filterOptions = await popoverFirstComboboxOptions(/^filter/i); + expect(filterOptions).toContain('Title'); + expect(filterOptions).not.toContain('Priority (draft)'); + const sortOptions = await popoverFirstComboboxOptions(/^sort/i); + expect(sortOptions).toContain('Title'); + expect(sortOptions).not.toContain('Priority (draft)'); + }); + + it('CONTROL: the same view with the field published asks for it as before, with no note', async () => { + const { lastParams } = await mountList({ draft: false }, { + sort: [{ field: 'priority', order: 'desc' }], + }, { + initialFilters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'priority', operator: 'equals', value: 'high' }] }, + }); + expect(lastParams().$select).toEqual(['id', 'title', 'priority']); + expect(lastParams().$orderby).toEqual([{ field: 'priority', order: 'desc' }]); + expect(JSON.stringify(lastParams().$filter)).toContain('"priority"'); + expect(notice()).toBeNull(); + const filterOptions = await popoverFirstComboboxOptions(/^filter/i); + expect(filterOptions).toContain('Priority'); + }); +}); + // ── ListView.switcherChrome-7547 ───────────────────────────────────────────── /** From dc2020954775c48b20ea2c53b138d6e53fc12a92 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:32:34 +0000 Subject: [PATCH 08/11] test(app-shell): pin the draft-preview list wrapper and its call sites; key the wrapper on its inputs Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX Co-authored-by: Claude --- .changeset/34807-draft-preview-list-column.md | 16 ++ ...lishedObjectReads.draftOnly-34807.test.tsx | 261 ++++++++++++++++++ .../src/preview/unpublishedObjectReads.ts | 28 +- .../ObjectView.draftOnlyColumn-34807.test.tsx | 184 ++++++++++++ .../src/views/objectViewListRenderer.tsx | 6 +- 5 files changed, 482 insertions(+), 13 deletions(-) create mode 100644 .changeset/34807-draft-preview-list-column.md create mode 100644 ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx create mode 100644 ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx diff --git a/.changeset/34807-draft-preview-list-column.md b/.changeset/34807-draft-preview-list-column.md new file mode 100644 index 00000000000..5d1415d821b --- /dev/null +++ b/.changeset/34807-draft-preview-list-column.md @@ -0,0 +1,16 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(console): under draft preview, a list column on a field that exists only in the draft no longer makes the whole list fail + +Clause-②: yes (widening — one new @object-ui/i18n `list.*` key only; no exported prop, no typed interface member; the `_draftOnly` field marker is an internal undeclared key on an untyped value) +Metadata-protocol: none + +Under `?preview=draft` a list view may show a column on a field the draft adds. The data door validates every `$select`, `$filter` and `$orderby` name against the published object, so that one column made it refuse the whole list query with `400 INVALID_FIELD`. In draft preview the console's list pages (the object view, `/:objectName/data` and interface list pages) now hand the list a data source whose `getObjectSchema` answers the published object definition plus each draft-only field, with its draft label and the marker `_draftOnly: true`, the published sortability projection kept. Outside preview they hand the list the adapter itself, unchanged. The data contract is unchanged: data reads never see a draft schema. + +`@object-ui/plugin-list`: `ListView` leaves a field marked `_draftOnly` out of `$select`, `$expand`, `$filter` and `$orderby` (and out of a server export's fields), and out of the Filter panel and Sort picker. Its column is drawn empty under the field's draft label. A sort or filter that names such a field is left out of the request, and one line above the rows says so (`list.draftOnlyQueryDropped`). `_draftOnly` is an underscore-private convention between the console and this package, never an authoring key; nothing new is exported. + +`@object-ui/i18n`: new key `list.draftOnlyQueryDropped` in every locale. diff --git a/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx b/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx new file mode 100644 index 00000000000..f6b86045815 --- /dev/null +++ b/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx @@ -0,0 +1,261 @@ +/** + * 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 (ruling 6946403206) — the list half: under `?preview=draft` + * a list column on a field that exists only in the draft made the data door + * refuse the whole list query (`400 INVALID_FIELD`), because the list read its + * object definition from the adapter's PUBLISHED `getObjectSchema`, which does + * not know the field, and sent every column. + * + * Pinned here, on the app-shell side: + * 1. `withUnpublishedObjectReads`, given the overlay read, answers + * `getObjectSchema` with the published document plus each draft-only field + * under its draft label, marked with the underscore-private literal + * `_draftOnly` (`@object-ui/plugin-list` reads the same literal; its own + * pin is the `ListView.draftOnlyColumn-34807` block of its harness), with + * the published sortability projection kept. CONTROL: without the overlay + * read the source's own `getObjectSchema` answers. + * 2. `usePreviewListDataSource`: the adapter ITSELF outside the preview; one + * wrapper per draft revision inside it. + * 3. The `ObjectDataPage` (`/:objectName/data`) and `InterfaceListPage` call + * sites hand `ListView` that wrapper in the preview and the adapter itself + * outside it. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, renderHook, cleanup, waitFor } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { attachObjectSortability, readObjectSortability } from '@object-ui/core'; + +/** The overlay read the provider's `getItem('object', name)` answers in these cases. */ +const OVERLAY: { doc: unknown; getItem: ReturnType } = { + doc: null, + getItem: vi.fn(), +}; + +vi.mock('../../providers/MetadataProvider', async (importOriginal) => { + const actual = await importOriginal>(); + const getItem = (type: string, name: string) => OVERLAY.getItem(type, name); + return { + ...actual, + useMetadata: () => ({ objects: LIST_PAGE.objects, loading: false, getItem }), + }; +}); + +/** What the pages under test hand `ListView`. */ +const CAPTURED: { dataSource: any } = { dataSource: undefined }; +vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ + ...(await importOriginal()), + ListView: (props: { dataSource: unknown }) => { + CAPTURED.dataSource = props.dataSource; + return null; + }, +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () => null })); +vi.mock('../../views/CreateViewDialog', () => ({ CreateViewDialog: () => null })); +vi.mock('../../views/metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) })); + +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => LIST_PAGE.dataSource, +})); + +import { withUnpublishedObjectReads, usePreviewListDataSource } from '../unpublishedObjectReads'; +import { PreviewModeProvider } from '../PreviewModeContext'; +import { ObjectDataPage } from '../../views/ObjectDataPage'; +import { InterfaceListPage } from '../../views/InterfaceListPage'; +import { ExpressionProvider } from '../../providers/ExpressionProvider'; + +const OBJECT = 'tracker_task'; + +/** The published document the adapter serves, with its sortability projection. */ +function publishedDocument() { + const doc = { + name: OBJECT, + label: 'Task', + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, + }; + return attachObjectSortability(doc, { fields: { title: { sortable: true } } }); +} + +/** The draft overlay's document: the published field plus the drafted one. */ +const DRAFT_DOCUMENT = { + name: OBJECT, + label: 'Task', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + priority: { name: 'priority', type: 'select', label: 'Priority (draft)' }, + }, + listViews: { all: { name: 'all', label: 'All', type: 'grid', columns: ['title', 'priority'] } }, +}; + +function makeAdapter() { + return { + find: vi.fn(async () => ({ data: [], total: 0 })), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => publishedDocument()), + } as any; +} + +const LIST_PAGE: { dataSource: any; objects: any[] } = { dataSource: undefined, objects: [] }; + +beforeEach(() => { + OVERLAY.doc = DRAFT_DOCUMENT; + OVERLAY.getItem = vi.fn(async () => OVERLAY.doc); + CAPTURED.dataSource = undefined; + LIST_PAGE.dataSource = makeAdapter(); + LIST_PAGE.objects = [DRAFT_DOCUMENT]; + // The pages' permission reads go to the network; answer them empty. + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }))); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('withUnpublishedObjectReads: the list definition under draft preview (objectstack#34807)', () => { + it('answers the published document plus the draft-only field, marked `_draftOnly`, under its draft label', async () => { + const adapter = makeAdapter(); + const ds = withUnpublishedObjectReads(adapter, () => {}, (name) => OVERLAY.getItem('object', name)); + const def: any = await ds.getObjectSchema(OBJECT); + expect(OVERLAY.getItem).toHaveBeenCalledWith('object', OBJECT); + expect(adapter.getObjectSchema).toHaveBeenCalledWith(OBJECT); + expect(def.fields.priority).toMatchObject({ label: 'Priority (draft)', _draftOnly: true }); + // The published field keeps its published definition, unmarked. + expect(def.fields.title._draftOnly).toBeUndefined(); + // The published sortability projection rides along: it names no draft-only field. + expect(readObjectSortability(def)?.fields).toEqual({ title: { sortable: true } }); + }); + + it('CONTROL: without the overlay read, the source answers its own definition', async () => { + const adapter = makeAdapter(); + const ds = withUnpublishedObjectReads(adapter, () => {}); + const def: any = await ds.getObjectSchema(OBJECT); + expect(def.fields.priority).toBeUndefined(); + expect(OVERLAY.getItem).not.toHaveBeenCalled(); + }); +}); + +describe('usePreviewListDataSource (objectstack#34807)', () => { + const wrapper = (preview: boolean) => + function Wrapper({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); + }; + + it('CONTROL: outside the preview it is the adapter itself', () => { + const adapter = makeAdapter(); + const { result } = renderHook(() => usePreviewListDataSource(adapter, DRAFT_DOCUMENT), { wrapper: wrapper(false) }); + expect(result.current).toBe(adapter); + }); + + it('in the preview it wraps the adapter, once per draft revision', async () => { + const adapter = makeAdapter(); + let revision: unknown = DRAFT_DOCUMENT; + const { result, rerender } = renderHook(() => usePreviewListDataSource(adapter, revision), { wrapper: wrapper(true) }); + const first = result.current; + expect(first).not.toBe(adapter); + expect(((await first.getObjectSchema(OBJECT)) as any).fields.priority._draftOnly).toBe(true); + rerender(); + expect(result.current).toBe(first); + revision = { ...DRAFT_DOCUMENT }; + rerender(); + expect(result.current).not.toBe(first); + }); +}); + +describe('the list pages hand ListView the preview wrapper (objectstack#34807)', () => { + function renderDataPage(preview: boolean) { + return render( + + + + + } + /> + + + + , + ); + } + + function renderInterfacePage(preview: boolean) { + const page = { + name: 'my_tasks', + label: 'My Tasks', + interfaceConfig: { source: OBJECT, sourceView: 'all' }, + }; + return render( + + + + + , + ); + } + + for (const [name, renderPage] of [ + ['ObjectDataPage', renderDataPage], + ['InterfaceListPage', renderInterfacePage], + ] as const) { + it(`${name}: in the preview, ListView reads the draft-only field marked`, async () => { + renderPage(true); + await waitFor(() => expect(CAPTURED.dataSource).toBeDefined()); + expect(CAPTURED.dataSource).not.toBe(LIST_PAGE.dataSource); + const def: any = await CAPTURED.dataSource.getObjectSchema(OBJECT); + expect(def.fields.priority).toMatchObject({ label: 'Priority (draft)', _draftOnly: true }); + }); + + it(`${name} CONTROL: outside the preview, ListView gets the adapter itself`, async () => { + renderPage(false); + await waitFor(() => expect(CAPTURED.dataSource).toBeDefined()); + expect(CAPTURED.dataSource).toBe(LIST_PAGE.dataSource); + expect(OVERLAY.getItem).not.toHaveBeenCalled(); + }); + } +}); diff --git a/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts b/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts index 12c7ecbd442..bf8b94e03b8 100644 --- a/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts +++ b/ui/packages/app-shell/src/preview/unpublishedObjectReads.ts @@ -43,7 +43,7 @@ * data reads never see a draft schema. */ -import { useMemo, useRef } from 'react'; +import { useRef } from 'react'; import { answeredLoadFailure } from '@object-ui/react'; import type { DataSource } from '@object-ui/types'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -116,16 +116,22 @@ export function usePreviewListDataSource { - if (!previewDrafts || !ds) return ds; - return withUnpublishedObjectReads( - ds, - (name) => unpublishedRef.current(name), - (name) => getItem('object', name), - ) as T; - // `revision` is read for its identity only: see the doc above. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [previewDrafts, ds, getItem, revision]); + // Cached on the inputs the wrapper is made of (the source and the payload + // `revision`), not on a memo's identity (ui/AGENTS.md #10). + const cache = useRef<{ ds: DataSource; revision: unknown; wrapped: DataSource } | null>(null); + if (!previewDrafts || !ds) return ds; + const held = cache.current; + if (held && held.ds === ds && held.revision === revision) return held.wrapped as T; + const wrapped = withUnpublishedObjectReads( + ds, + (name) => unpublishedRef.current(name), + (name) => getItemRef.current('object', name), + ); + cache.current = { ds, revision, wrapped }; + return wrapped as T; } diff --git a/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx b/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx new file mode 100644 index 00000000000..ea052b1cded --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx @@ -0,0 +1,184 @@ +/** + * 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 (ruling 6946403206) — the list half, through the real + * `ObjectView` and the real `ListView`: under `?preview=draft` a list column on + * a field that exists only in the draft made the data door refuse the whole + * list query (`400 INVALID_FIELD`, it validates against the PUBLISHED object). + * + * The object view's list wrapper (`objectViewListRenderer`) now answers the + * list's object definition through the provider's overlay read, with the + * draft-only field marked, so `ListView` draws its column empty under the + * draft label and never asks for it. The data source answers as the data door + * does: any request naming `priority` is refused. CONTROL: outside the preview + * nothing changes, so the same view still sends the column and is refused. + */ + +// Paid at collection, not inside a case's clock (check:test-source-alias): +// ObjectView reaches `import('@objectstack/lint')` through the CEL editor. +import '@objectstack/lint'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, screen } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { createI18n, I18nProvider } from '@object-ui/i18n'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + // Stable identities — `ListView` names `perms` in its fetch dependencies. + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRealtimeSubscription: () => ({ lastMessage: null }), + useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }), +})); + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); + +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => ({ save: vi.fn(async () => ({})), get: vi.fn(async () => null) }), +})); + + +/** The overlay read (`useMetadata().getItem`), answered by the drafted document. */ +const GET_ITEM = vi.fn(); +vi.mock('../providers/MetadataProvider', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useMetadata: () => ({ ...actual.useMetadata(), getItem: (type: string, name: string) => GET_ITEM(type, name) }), + }; +}); + +import { ObjectView } from './ObjectView'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; +import { PreviewModeProvider } from '../preview/PreviewModeContext'; + +const PUBLISHED_FIELDS = { + id: { type: 'text', label: 'Id' }, + title: { type: 'text', label: 'Title' }, +}; + +/** The object as the draft overlay serves it: the drafted field and a list column on it. */ +const DRAFT_TASK = { + name: 'tracker_task', + label: 'Task', + pluralLabel: 'Tasks', + fields: { + ...PUBLISHED_FIELDS, + priority: { type: 'select', label: 'Priority (draft)', options: [{ label: 'High', value: 'high' }] }, + }, + listViews: { + all: { name: 'all', label: 'All', type: 'grid', columns: ['title', 'priority'] }, + }, +}; + +afterEach(() => { + cleanup(); + GET_ITEM.mockReset(); +}); + +function mount(opts: { preview: boolean }) { + GET_ITEM.mockImplementation(async (type: string, name: string) => + type === 'object' && name === 'tracker_task' ? DRAFT_TASK : null); + const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + const find = vi.fn(async (_object: string, params: unknown) => { + if (JSON.stringify(params ?? {}).includes('"priority')) { + throw Object.assign(new Error("Unknown field 'priority' on object 'tracker_task'"), { + httpStatus: 400, + code: 'INVALID_FIELD', + }); + } + return { data: [{ id: 't1', title: 'Write the spec' }], total: 1 }; + }); + const dataSource = { + find, + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + // The adapter's PUBLISHED read: it does not know the drafted field. + getObjectSchema: vi.fn(async () => ({ name: 'tracker_task', label: 'Task', fields: PUBLISHED_FIELDS })), + } as never; + render( + + + + + + {}} />} + /> + + + + + , + ); + return { find }; +} + +describe('objectstack#34807 — a list column on a draft-only field in the draft preview', () => { + it('draws the list with the column empty under its draft label, never asking for it', async () => { + const { find } = mount({ preview: true }); + + await screen.findByText('Write the spec', undefined, { timeout: 5000 }); + expect(screen.getAllByText('Priority (draft)').length).toBeGreaterThan(0); + expect(screen.queryByTestId('list-error-code')).toBeNull(); + expect(GET_ITEM).toHaveBeenCalledWith('object', 'tracker_task'); + expect(find).toHaveBeenCalled(); + for (const [, params] of find.mock.calls) { + expect(JSON.stringify(params ?? {})).not.toContain('"priority'); + } + }); + + it('control: outside the preview the column is still sent, and the data door refuses it', async () => { + const { find } = mount({ preview: false }); + + const code = await screen.findByTestId('list-error-code', undefined, { timeout: 5000 }); + expect(code.textContent).toBe('INVALID_FIELD'); + expect(JSON.stringify(find.mock.calls.at(-1)?.[1] ?? {})).toContain('"priority"'); + expect(GET_ITEM).not.toHaveBeenCalledWith('object', 'tracker_task'); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index 520ca47f935..90b12d21d74 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -225,6 +225,8 @@ export function useObjectViewListRenderer({ // field drafted) makes a new wrapper, so the list re-reads its definition. const previewDrafts = usePreviewDrafts(); const { getItem: getMetadataItem } = useMetadata(); + const getMetadataItemRef = useRef(getMetadataItem); + getMetadataItemRef.current = getMetadataItem; const [unpublishedObjects, setUnpublishedObjects] = useState>(() => new Set()); const unpublishedReadsRef = useRef(new WeakMap()); const previewDataSource = useCallback((ds: DataSource): DataSource => { @@ -233,11 +235,11 @@ export function useObjectViewListRenderer({ const wrapped = withUnpublishedObjectReads( ds, (name) => setUnpublishedObjects((prev) => (prev.has(name) ? prev : new Set(prev).add(name))), - (name) => getMetadataItem('object', name), + (name) => getMetadataItemRef.current('object', name), ); unpublishedReadsRef.current.set(ds, { revision: objectDef, wrapped }); return wrapped; - }, [objectDef, getMetadataItem]); + }, [objectDef]); const renderListView = useCallback(({ schema: listSchema, dataSource: rawDs, onEdit: editHandler, className, refreshKey: pluginRefreshKey }: any) => { const ds = previewDrafts && rawDs ? previewDataSource(rawDs) : rawDs; From 704c8740cf472063955584e48590dc795abb2a8e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:39:54 +0000 Subject: [PATCH 09/11] test(app-shell): the outside-preview control reads the list's error state Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX Co-authored-by: Claude --- .../src/views/ObjectView.draftOnlyColumn-34807.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx b/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx index ea052b1cded..6df288b6c47 100644 --- a/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx @@ -165,7 +165,7 @@ describe('objectstack#34807 — a list column on a draft-only field in the draft await screen.findByText('Write the spec', undefined, { timeout: 5000 }); expect(screen.getAllByText('Priority (draft)').length).toBeGreaterThan(0); - expect(screen.queryByTestId('list-error-code')).toBeNull(); + expect(screen.queryByTestId('list-error-state')).toBeNull(); expect(GET_ITEM).toHaveBeenCalledWith('object', 'tracker_task'); expect(find).toHaveBeenCalled(); for (const [, params] of find.mock.calls) { @@ -176,8 +176,8 @@ describe('objectstack#34807 — a list column on a draft-only field in the draft it('control: outside the preview the column is still sent, and the data door refuses it', async () => { const { find } = mount({ preview: false }); - const code = await screen.findByTestId('list-error-code', undefined, { timeout: 5000 }); - expect(code.textContent).toBe('INVALID_FIELD'); + await screen.findByTestId('list-error-state', undefined, { timeout: 5000 }); + expect(screen.queryByText('Write the spec')).toBeNull(); expect(JSON.stringify(find.mock.calls.at(-1)?.[1] ?? {})).toContain('"priority"'); expect(GET_ITEM).not.toHaveBeenCalledWith('object', 'tracker_task'); }); From a0777bd542348198557fa85b159673f114dba201 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:07:45 +0000 Subject: [PATCH 10/11] test(app-shell): type the overlay read mock Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX Co-authored-by: Claude --- .../unpublishedObjectReads.draftOnly-34807.test.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx b/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx index f6b86045815..4510c8037a9 100644 --- a/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx @@ -35,9 +35,10 @@ import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { attachObjectSortability, readObjectSortability } from '@object-ui/core'; /** The overlay read the provider's `getItem('object', name)` answers in these cases. */ -const OVERLAY: { doc: unknown; getItem: ReturnType } = { +type OverlayRead = (type: string, name: string) => Promise; +const OVERLAY: { doc: unknown; getItem: ReturnType> } = { doc: null, - getItem: vi.fn(), + getItem: vi.fn(), }; vi.mock('../../providers/MetadataProvider', async (importOriginal) => { @@ -137,7 +138,7 @@ const LIST_PAGE: { dataSource: any; objects: any[] } = { dataSource: undefined, beforeEach(() => { OVERLAY.doc = DRAFT_DOCUMENT; - OVERLAY.getItem = vi.fn(async () => OVERLAY.doc); + OVERLAY.getItem = vi.fn(async () => OVERLAY.doc); CAPTURED.dataSource = undefined; LIST_PAGE.dataSource = makeAdapter(); LIST_PAGE.objects = [DRAFT_DOCUMENT]; From 509f3eab7949a4985b1de87a19504d6e46026713 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:21:45 +0000 Subject: [PATCH 11/11] fix(plugin-list): keep draft-only names out of the searchFields a search sends Under draft preview a view whose searchableFields names a draft-only field sent it as $searchFields with every search term, and the data door refuses an undeclared search field with 400 INVALID_FIELD (checked whether or not a term rides). ListView now sends the declared list less the marked names, on its own fetch, the grouped grid, gantt, the server export and kanban lane paging. Pinned in the harness with a published control. Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX Co-authored-by: Claude --- .changeset/34807-draft-preview-list-column.md | 4 +- ui/packages/plugin-list/src/ListView.tsx | 41 +++++++++++++------ .../src/__tests__/ListView.harness.test.tsx | 18 ++++++++ 3 files changed, 48 insertions(+), 15 deletions(-) diff --git a/.changeset/34807-draft-preview-list-column.md b/.changeset/34807-draft-preview-list-column.md index 5d1415d821b..88f3b71fd02 100644 --- a/.changeset/34807-draft-preview-list-column.md +++ b/.changeset/34807-draft-preview-list-column.md @@ -9,8 +9,8 @@ fix(console): under draft preview, a list column on a field that exists only in Clause-②: yes (widening — one new @object-ui/i18n `list.*` key only; no exported prop, no typed interface member; the `_draftOnly` field marker is an internal undeclared key on an untyped value) Metadata-protocol: none -Under `?preview=draft` a list view may show a column on a field the draft adds. The data door validates every `$select`, `$filter` and `$orderby` name against the published object, so that one column made it refuse the whole list query with `400 INVALID_FIELD`. In draft preview the console's list pages (the object view, `/:objectName/data` and interface list pages) now hand the list a data source whose `getObjectSchema` answers the published object definition plus each draft-only field, with its draft label and the marker `_draftOnly: true`, the published sortability projection kept. Outside preview they hand the list the adapter itself, unchanged. The data contract is unchanged: data reads never see a draft schema. +Under `?preview=draft` a list view may show a column on a field the draft adds. The data door validates every `$select`, `$filter`, `$orderby` and `$searchFields` name against the published object, so that one column made it refuse the whole list query with `400 INVALID_FIELD`. In draft preview the console's list pages (the object view, `/:objectName/data` and interface list pages) now hand the list a data source whose `getObjectSchema` answers the published object definition plus each draft-only field, with its draft label and the marker `_draftOnly: true`, the published sortability projection kept. Outside preview they hand the list the adapter itself, unchanged. The data contract is unchanged: data reads never see a draft schema. -`@object-ui/plugin-list`: `ListView` leaves a field marked `_draftOnly` out of `$select`, `$expand`, `$filter` and `$orderby` (and out of a server export's fields), and out of the Filter panel and Sort picker. Its column is drawn empty under the field's draft label. A sort or filter that names such a field is left out of the request, and one line above the rows says so (`list.draftOnlyQueryDropped`). `_draftOnly` is an underscore-private convention between the console and this package, never an authoring key; nothing new is exported. +`@object-ui/plugin-list`: `ListView` leaves a field marked `_draftOnly` out of `$select`, `$expand`, `$filter` and `$orderby` (and out of the `$searchFields` it sends with a search term, and a server export's fields), and out of the Filter panel and Sort picker. Its column is drawn empty under the field's draft label. A sort or filter that names such a field is left out of the request, and one line above the rows says so (`list.draftOnlyQueryDropped`). `_draftOnly` is an underscore-private convention between the console and this package, never an authoring key; nothing new is exported. `@object-ui/i18n`: new key `list.draftOnlyQueryDropped` in every locale. diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 1fb8ed75e0e..81e51912ceb 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -2244,6 +2244,21 @@ export const ListView = React.forwardRef(({ */ const draftOnlyFields = React.useMemo(() => readDraftOnlyFieldNames(objectDef), [objectDef]); + /** + * objectstack#34807 — the view's `searchableFields` as every query this list + * makes or hands down sends them: without a draft-only field, which the data + * door refuses as `$searchFields` (`400 INVALID_FIELD`, an unknown field) + * and with it the whole list. The authored list itself outside the preview, + * or when it names none. When every entry is draft-only nothing is sent, and + * the term searches the object's default fields. + */ + const searchFieldsSent = React.useMemo(() => { + const declared = schema.searchableFields; + if (!declared || draftOnlyFields.size === 0) return declared; + const kept = declared.filter((f) => !refersToDraftOnlyField(f, draftOnlyFields)); + return kept.length === declared.length ? declared : kept; + }, [schema.searchableFields, draftOnlyFields]); + /** * objectui#12966 — the object's `search` resolves to no field, so the server * refuses any term with `400 INVALID_FIELD`: no quick-search box, and a term @@ -4249,8 +4264,8 @@ export const ListView = React.forwardRef(({ ...(expandFields.length > 0 ? { $expand: expandFields } : {}), ...(searchTerm ? { $search: searchTerm, - ...(schema.searchableFields && schema.searchableFields.length > 0 - ? { $searchFields: schema.searchableFields } + ...(searchFieldsSent && searchFieldsSent.length > 0 + ? { $searchFields: searchFieldsSent } : {}), } : {}), }; @@ -4449,7 +4464,7 @@ export const ListView = React.forwardRef(({ // silently un-suppresses nothing, because the finding it was suppressing // simply moves elsewhere. Add prose ABOVE this point, never below it. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, schema.searchableFields, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, draftOnlyFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on + }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, searchFieldsSent, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, draftOnlyFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on // Any change to the result-defining inputs (object, filters, sort, search, // grouping, page size) invalidates the current page number — snap back to @@ -5006,8 +5021,8 @@ export const ListView = React.forwardRef(({ ...(gridOwnsGroupedFetch ? { filter: selfQueryFilter, - ...(schema.searchableFields && schema.searchableFields.length > 0 - ? { searchableFields: schema.searchableFields } + ...(searchFieldsSent && searchFieldsSent.length > 0 + ? { searchableFields: searchFieldsSent } : {}), } : {}), @@ -5358,8 +5373,8 @@ export const ListView = React.forwardRef(({ ...(ganttSearchTerm ? { search: ganttSearchTerm, - ...(schema.searchableFields && schema.searchableFields.length > 0 - ? { searchableFields: schema.searchableFields } + ...(searchFieldsSent && searchFieldsSent.length > 0 + ? { searchableFields: searchFieldsSent } : {}), } : {}), @@ -5548,7 +5563,7 @@ export const ListView = React.forwardRef(({ // asynchronously (`/me/permissions`) and `objectDef` loads into state, so a // grid schema built before either resolved must be rebuilt when they do — // otherwise `editable` keeps the pre-verdict answer for the session. - }, [currentView, schema, authoredFilter, serverSort, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEdit, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged]); + }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEdit, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged]); // The count the toolbar shows: a record-mode amount's code condition is // part of its amount row (objectstack#27188), not a filter of its own, and a @@ -6055,8 +6070,8 @@ export const ListView = React.forwardRef(({ // with objectstack#4230; older ones ignore it and behave as before. ...(searchTerm ? { search: searchTerm, - ...(schema.searchableFields && schema.searchableFields.length > 0 - ? { searchFields: schema.searchableFields } + ...(searchFieldsSent && searchFieldsSent.length > 0 + ? { searchFields: searchFieldsSent } : {}), } : {}), sort, @@ -6138,7 +6153,7 @@ export const ListView = React.forwardRef(({ setShowExport(false); // `searchTerm` / `searchableFields` belong here: the export now narrows by // the active search, so a stale closure would export the wrong row set. - }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, schema.searchableFields, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t, draftOnlyFields]); + }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, searchFieldsSent, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t, draftOnlyFields]); // All available fields for hide/show (with i18n) // @@ -7835,8 +7850,8 @@ export const ListView = React.forwardRef(({ ? { lanePaging: { search: searchTerm, - ...(schema.searchableFields && schema.searchableFields.length > 0 - ? { searchFields: schema.searchableFields } + ...(searchFieldsSent && searchFieldsSent.length > 0 + ? { searchFields: searchFieldsSent } : {}), reloadKey: `${refreshKey}:${String(schema.refreshTrigger ?? '')}`, }, diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 509b42e5b48..158624823d6 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -2035,6 +2035,24 @@ describe('ListView.draftOnlyColumn-34807', () => { expect(sortOptions).not.toContain('Priority (draft)'); }); + it('leaves it out of $searchFields, keeping the search and the rest of the declared fields', async () => { + const { dataSource, lastParams } = await mountList({ draft: true }, { searchableFields: ['title', 'priority'] }, { + initialSearchTerm: 'spec', + }); + expect(screen.queryByTestId('list-error-state')).toBeNull(); + everyRequestOmitsPriority(dataSource); + expect(lastParams().$search).toBe('spec'); + expect(lastParams().$searchFields).toEqual(['title']); + }); + + it('CONTROL: with the field published, $searchFields carries it as declared', async () => { + const { lastParams } = await mountList({ draft: false }, { searchableFields: ['title', 'priority'] }, { + initialSearchTerm: 'spec', + }); + expect(lastParams().$search).toBe('spec'); + expect(lastParams().$searchFields).toEqual(['title', 'priority']); + }); + it('CONTROL: the same view with the field published asks for it as before, with no note', async () => { const { lastParams } = await mountList({ draft: false }, { sort: [{ field: 'priority', order: 'desc' }],