diff --git a/.changeset/34807-draft-preview-list-column.md b/.changeset/34807-draft-preview-list-column.md new file mode 100644 index 00000000000..88f3b71fd02 --- /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`, `$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 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/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..4510c8037a9 --- /dev/null +++ b/ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx @@ -0,0 +1,262 @@ +/** + * 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. */ +type OverlayRead = (type: string, name: string) => Promise; +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 73f69a38413..bf8b94e03b8 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 { 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,50 @@ 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(); + // Read at call time, so neither callback's identity decides the wrapper's. + const getItemRef = useRef(getItem); + getItemRef.current = getItem; + const unpublishedRef = useRef(onUnpublished); + unpublishedRef.current = onUnpublished; + // 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/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 && ( { + 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-state')).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 }); + + 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'); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index 48bc4da498e..90b12d21d74 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -24,6 +24,7 @@ import { useLocalization, type useObjectLabel, type useObjectTranslation } from import { resolveManagedByEmptyState } from '../utils/managedByEmptyState.js'; import { usePreviewDrafts } from '../preview/PreviewModeContext.js'; import { withUnpublishedObjectReads } from '../preview/unpublishedObjectReads.js'; +import { useMetadata } from '../providers/MetadataProvider.js'; import type { DataSource } from '@object-ui/types'; import { isSavedViewId } from '../utils/viewIdentity.js'; import { warnSuppressedListNav } from '../utils/warnSuppressedListNav.js'; @@ -216,18 +217,29 @@ export function useObjectViewListRenderer({ // publish). That is an empty list, not a fault: the wrapper answers it // empty and names the object, and the list says why it is empty. One // wrapper per source, so the list's fetch never sees a new data source. + // + // objectstack#34807 — the same wrapper answers the list's object definition + // with the draft-only fields marked (`readDraftPreviewObjectSchema`, read + // through the provider's overlay), so `ListView` keeps them out of the + // query and draws their columns empty. A new draft-aware `objectDef` (a + // 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 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) => getMetadataItemRef.current('object', name), ); - unpublishedReadsRef.current.set(ds, wrapped); + unpublishedReadsRef.current.set(ds, { revision: objectDef, wrapped }); return wrapped; - }, []); + }, [objectDef]); 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 b8e2d76ac5a..e35d7561b1f 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 19e4ef1d927..ac92e7ffaaf 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 05dc3eac472..93c8bed328a 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 18596c01fb4..6e6d650b60f 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 008363ecffa..1ea46e1d069 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 42ea9c925b3..b4e5611769a 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 6bb204167d0..a702854a34e 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 b4a7a70058a..d39b87c8608 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 ff3b4d5b044..b6a33addd62 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 094504a6ffb..67d1d3a4c67 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 993f6f4677a..c57955658ae 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..81e51912ceb 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,31 @@ 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]); + + /** + * 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 @@ -2252,12 +2380,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 +2791,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 +3409,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 +3458,7 @@ export const ListView = React.forwardRef(({ schema.map, perms, schema.objectName, + draftOnlyFields, ]); /** @@ -3630,7 +3795,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 +3835,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 +3872,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; })(); @@ -4091,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 } : {}), } : {}), }; @@ -4291,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]); // 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 @@ -4717,7 +4890,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) { @@ -4848,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 } : {}), } : {}), @@ -5200,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 } : {}), } : {}), @@ -5390,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 @@ -5557,13 +5730,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 +5836,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 +5861,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 +6034,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 +6059,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, @@ -5889,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, @@ -5972,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]); + }, [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) // @@ -7405,6 +7586,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 @@ -7647,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 45bc257ce6a..158624823d6 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,223 @@ 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('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' }], + }, { + 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 ───────────────────────────────────────────── /**