Skip to content

Commit 4aeeca5

Browse files
fix(console): under draft preview a list column on a draft-only field no longer makes the whole list fail (#34936)
repo:objectstack#3 · os-support-ai · session_01WGufzg2evNa1V3zxrQq3KX Fixes #34807 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 Premise corrected: 6946635368 Ruling-ref: 6946403206 Surface-amendment: 6946712960 This PR ships the **list half** of the card. The form half landed as #34843 (13e0305); this branch was cut from it and has merged `origin/main` since, so the diff below is the list half alone. ## 维护者速读 - **改了什么**:草稿预览(`?preview=draft`)里,列表视图如果有一列是只存在于草稿中的字段,现在列表照常显示:这一列用草稿里的标签画出来、内容为空;查询、筛选、排序、搜索字段都不再带上这个字段。若用户的筛选或排序用到了它,列表上方会有一行说明「这个字段只在草稿中,发布前不参与筛选/排序」。 - **为什么改**:数据接口按已发布的对象校验字段名,草稿新增的字段一旦出现在查询里,整个列表就返回 400,预览里看到的是报错而不是 AI 刚加好的列,用户会以为 AI 做坏了。 - **风险与回滚**:只在预览模式下生效;预览之外列表拿到的仍是原来的 adapter 本身,`ListView` 读到的标记集合为空,所有请求逐字节不变(对照测试钉住)。回滚即 revert 本 PR。 - **先看**:`ui/packages/plugin-list/src/ListView.tsx`(`omitDraftOnlyFilterFields` 剔除筛选条件、`servedCols` 投影与 `searchFieldsSent` 三处,影响已发布包);`ui/packages/app-shell/src/preview/unpublishedObjectReads.ts`(`usePreviewListDataSource` 与 `getObjectSchema` 的预览读取);`ui/packages/app-shell/src/views/objectViewListRenderer.tsx`(包装缓存按 objectDef 失效)。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/plugin-list/src/__tests__/ListView.harness.test.tsx packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx`,预期 3 个文件、116 个测试全部通过。 - **需要你做的**:无,席位落地。 ## What changes - `@object-ui/app-shell`, `preview/unpublishedObjectReads.ts`: - `withUnpublishedObjectReads(ds, onUnpublished, readOverlay?)`: given the overlay read, its `getObjectSchema` answers the form half's `readDraftPreviewObjectSchema`. That is the **published** object document plus each field only the draft declares, under its draft label, marked `_draftOnly: true`, with the published sortability projection kept. Without the overlay read it behaves as before. - New hook `usePreviewListDataSource(ds, revision)` (module-level, not exported from the package): the adapter **itself** outside preview; inside preview, one wrapper per data source and revision. It caches on its inputs through a ref, not on a memo identity (ui/AGENTS.md #10). - `objectViewListRenderer.tsx` passes the metadata provider's `getItem` (read through a ref) as the overlay read. It keeps one wrapper per data source per draft-aware `objectDef`, so a newly drafted field makes the list re-read its definition. `ObjectDataPage` and `InterfaceListPage` hand `ListView` `usePreviewListDataSource(dataSource, objectDef)`. - `@object-ui/plugin-list`, `ListView`: - It reads the marker once (`draftOnlyFields`, a shared empty set outside preview). - It leaves marked names out of the authored `$select` columns, the speculative field harvest, `$expand`, and the server export's fields. - It leaves them out of `$filter`: `buildEffectiveFilter` gains an optional `draftOnly` argument that strips every comparison on such a field from the merged node. This applies in the fetch, the child-view node and the export. - It leaves them out of `$orderby` (`serverSort`), and out of the `$searchFields` it sends with a search term. - It keeps them out of the Filter panel (kept only while a held condition names it, like hidden fields) and the Sort picker (listed disabled only while the current sort names it). - The column is drawn empty under the draft label. A sort or filter that names such a field is left out, and one status line says so: new key `list.draftOnlyQueryDropped`. - The `$searchFields` strip (`searchFieldsSent`) covers the list's own fetch and every place the view's `searchableFields` is handed on: the grouped grid's node, gantt, the server export and kanban lane paging. - `@object-ui/i18n`: `list.draftOnlyQueryDropped` in all 11 locales (zh-Hant regenerated by `scripts/gen-zh-hant.mjs`), and in `LIST_DEFAULT_TRANSLATIONS`. - Nothing is exported. No server, protocol or REST change; the data contract is unchanged by ruling 6946403206. ## Why 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` (premise 6946635368). Preview stays read-only for data (ruling 6946403206, ADR-0037 Phase 1). The list therefore draws the draft column empty instead of asking the server for a field the server does not have. **$searchFields, measured.** The data door checks `searchFields` whether or not a search term rides (the comment beside `host.assertSearchFieldsAreSearchable` in `protocol-data-crud.ts` says so). A temporary probe calling `findData` with `{ $search: 'spec', $searchFields: ['title', 'priority'] }` answered `{ code: INVALID_FIELD, status: 400, field: priority, param: $searchFields }`. The string form gave the same answer. The control `['title']` was served. So the strip goes in the same `ListView` helper (`refersToDraftOnlyField`). **Why the list strips the sort itself.** `readObjectSortability` drops a field with no projection entry only when the published read **served** a projection. An older deployment, or a never-published object, serves none, so `ListView` strips a draft-only sort explicitly (pinned both ways). `_draftOnly` is the form half's underscore-private convention between `@object-ui/app-shell` (which sets it) and the plugins (which read it). It is never an authoring key and is never persisted. ## Tests - `ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx`, new top-level describe `ListView.draftOnlyColumn-34807` (8 tests, per the shared-harness rule). Its data source refuses any request naming `priority` with `400 INVALID_FIELD`, as the data door does. - The column is drawn under "Priority (draft)", `$select` is exactly `['id','title']`, and there is no error. - A viewer filter on it is dropped, the `title` condition is kept, and the note is shown. - A sort on it is dropped, both with no projection and with the published projection served. - The Filter panel and Sort picker do not offer it. - With `searchableFields: ['title','priority']` and a search term, `$search` is kept and `$searchFields` is `['title']`. CONTROL: with the field published, it is `['title','priority']`. - CONTROL: with the field published, `$select`, `$orderby` and `$filter` carry it and there is no note. - `ui/packages/app-shell/src/preview/__tests__/unpublishedObjectReads.draftOnly-34807.test.tsx`: - The wrapper answers `_draftOnly` under the draft label and keeps the projection. CONTROL: no overlay read. - The hook is the adapter itself outside preview, and one wrapper per revision inside. - `ObjectDataPage` and `InterfaceListPage` hand `ListView` the wrapper in preview and the adapter itself outside it. - `ui/packages/app-shell/src/views/ObjectView.draftOnlyColumn-34807.test.tsx`: the real `ObjectView` and `ListView` under preview draw the list with the draft column, and no request names `priority`. CONTROL: outside preview the request still sends it, and the list shows the error state. <details> <summary>Ablation 1 (one-shot, restored): the projection strip removed</summary> Committed first. `node scripts/ablation-replace.mjs` replaced `? rawCols.filter(c => !refersToDraftOnlyField(c, draftOnlyFields))` with `? [...rawCols]` (anchor x1 to x0, blob 1fb8ed7 to 6eb1ac8619d8). ``` Tests 6 failed | 100 passed (106) ``` The failures were the ObjectView preview test and the 5 draft-mode plugin-list pins; both controls stayed green. Restored: blob == HEAD (1fb8ed7), `git diff HEAD` empty. A first attempt was a no-op (the replacement `? rawCols` was already inside the anchor), which the tool refused; nothing ran, then the run above. </details> <details> <summary>Ablation 2 (one-shot, restored, head 509f3ea): the $searchFields strip removed</summary> `node scripts/ablation-replace.mjs` replaced `const kept = declared.filter((f) => !refersToDraftOnlyField(f, draftOnlyFields));` with `const kept = [...declared];` (anchor x1 to x0, blob 81e5191 to f39dd3325865), then ran the harness file. ``` × leaves it out of $searchFields, keeping the search and the rest of the declared fields Tests 1 failed | 105 passed (106) ablation-replace: blob after restore 81e5191 ablation-replace: blob at HEAD 81e5191 ablation-replace: git diff HEAD empty ``` The published control stayed green under the mutation. </details> ## Acceptance notes - **Grouped grid: not covered here, carried by #34898** (seat ruling A: `plugin-grid` reads `_draftOnly`). `plugin-grid` is outside this PR's surface. The grid builds its own `$select` and `groupBy` from the object definition, and in preview that definition declares the draft-only field, so it passes the grid's declared-field gates (`passesProjectionGate`, `isProjectableField`). Measured with the real `ListView` and `object-grid` over a data source that refuses any request naming `priority`: - Columns `[title, priority]`, grouped by the published `status`: `ListView`'s own fetch sent `$select [id,title,status]` and was clean, and the header query sent `groupBy [status]` and was clean. Each group's row page sent `$select [id,title,priority,status]` and drew `INVALID_FIELD` inside the group. - Columns `[title]`, grouped by the draft-only `priority`: the header query sent `{ groupBy: ['priority'] }`, and the grid drew "Error loading grid". The data door's `assertGroupByFieldsExist` answers an unknown `groupBy` name with `400 INVALID_FIELD`, `param: 'groupBy'`. - The grouped grid's other inputs are clean from this PR: `ListView` hands it the stripped filter and the stripped `searchableFields`. - **$searchFields: fixed here** (see Why: measured 400, stripped, pinned, ablated). - **Design note: what dropping a draft-only comparison does to the filter's meaning (`or` groups).** A comparison on a draft-only field is removed from wherever it sits in the filter tree. A group left with one child becomes that child, and a group left with none disappears. Inside an `and` group, or at the top level, the removal **widens** the result, because one fewer condition must hold. Inside an `or` group it **narrows** that group (`A or D` becomes `A`), so rows only `D` would have matched are not shown. An `or` group whose every child was draft-only disappears, which widens the result again. None of these matches what the draft would answer once it is published. It happens only in preview, and the note line names the field that was left out. An earlier report from this run called this simply the `or`-group widening; the narrowing half is the correction. Treating the dropped comparison as true would widen an `or` group to every row, which seemed worse than showing fewer rows with the note. - **Never-published object.** For an object that has no published version yet, the list now reads the draft definition, with every field marked draft-only. Before, the published read failed and the list had no definition. The data read still answers through `withUnpublishedObjectReads`'s unpublished path, so the empty state keeps its publish sentence. A view sort on such an object also shows the dropped-sort note. - Draft edits to a field the published object already declares (a relabel, a new option) are not shown in the list; those fields keep their published definition, as in the form half. - i18n budget: `i18n-locale-en` reads 61,878 of 62,000 gzip bytes on the merged tree (122 B headroom), so the key stays in the eager en pack. The ceiling was not touched. ## Verification <details> <summary>Targeted tests, type-check and lint, head c34be37 (merged with origin/main 13e0305)</summary> ``` pnpm --workspace-concurrency=2 --filter '@object-ui/app-shell^...' build -> VERDICT command-exit 0 pnpm --dir ui exec vitest run --maxWorkers=2 (ListView.harness, unpublishedObjectReads.draftOnly-34807, ObjectView.draftOnlyColumn-34807, RecordFormPage.draftPreview-34807, previewFormDataSource.test) Test Files 5 passed (5) Tests 137 passed (137) os-verify-lock: VERDICT command-exit 0 pnpm --filter @object-ui/plugin-list run type-check -> 0 error TS, VERDICT command-exit 0 pnpm --filter @object-ui/app-shell run type-check -> 0 error TS, VERDICT command-exit 0 pnpm --filter @object-ui/i18n run type-check -> 0 error TS, VERDICT command-exit 0 npx eslint --no-inline-config (the 19 changed .ts/.tsx files) -> 0 errors, 374 warnings (pre-existing lines) pnpm --dir ui run check:new-line-citations -> VERDICT new-cross-file-line-citations: 0 new citation(s) -> exit 0 ``` Earlier, before the merge (704c874): `packages/plugin-list/` plus `packages/i18n/` gave Test Files 276 passed (276), Tests 3768 passed | 13 skipped. The 139 app-shell files that import the touched views or the wrapper gave Test Files 139 passed (139), Tests 1326 passed. </details> <details> <summary>Derived gate families (dispatch-gates --commands, 41), --ran reconciliation, head c34be37</summary> All 41 were run, each with its exit code captured before any pipe: all exit 0. `pnpm --dir ui exec vitest run scripts/` gave Test Files 171 passed | 2 skipped (173), Tests 5077 passed | 2 skipped (5079). ``` Run reconciliation — 41 derived, 41 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 41 derived famil(ies) accounted for — 41 run, 0 NOT-MEASURED (a DERIVED zero — all 41 recorded an exit code and none of them is 3). ``` </details> <details> <summary>i18n eager budget, merged tree c34be37</summary> The merged tree includes #34850 and #34851, which add en keys of their own. Under the verify lock: `pnpm install --frozen-lockfile`, then `VITE_BASE_PATH=/console/ vite build` in `ui/apps/console`, then `node scripts/check-eager-closure-budget.mjs`. All three exited 0. ``` ✅ chunk `i18n-locale-en` 60.4 KB measured / 60.5 KB ceiling (headroom 0.1 KB) [PER_CHUNK_GZIP_CEILINGS['i18n-locale-en']] eager-closure.json: {"name":"i18n-locale-en","bytes":201577,"gzipBytes":61878} ``` </details> - `node scripts/pm/overlap-check.mjs --branch=claude/issue-34807-draft-preview-list`, run alone before every push. Last result: VERDICT clean exit 0, at c34be37 against origin/main 189358f and open PRs #34914, #34925, #34929 and #34930. #34925 shares `objectViewListRenderer.tsx`, and all of them share locale files; every one merges cleanly. - Changeset `.changeset/34807-draft-preview-list-column.md`: patch bumps for `@object-ui/plugin-list`, `@object-ui/app-shell` and `@object-ui/i18n`, with both declaration lines. - NOT MEASURED: - a live run on `com.example.tracker` under `?preview=draft`; - the full app-shell suite (left to CI's Test UI); - dogfood (n/a: no `!` in the title, no narrowing arm). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [ ] 3. No formatter ran; `pnpm lint` passes. (No formatter ran. eslint on the changed files: 0 errors; the repo-wide `pnpm lint` is CI's, not measured locally.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (Series branch on the form half, merged with `main`.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The maintainer quick-read section is in Chinese, per the dispatch contract.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzg2evNa1V3zxrQq3KX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c81f498 commit 4aeeca5

20 files changed

Lines changed: 1022 additions & 40 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@object-ui/plugin-list': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
fix(console): under draft preview, a list column on a field that exists only in the draft no longer makes the whole list fail
8+
9+
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)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
`@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.
15+
16+
`@object-ui/i18n`: new key `list.draftOnlyQueryDropped` in every locale.
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#34807 (ruling 6946403206) — the list half: under `?preview=draft`
11+
* a list column on a field that exists only in the draft made the data door
12+
* refuse the whole list query (`400 INVALID_FIELD`), because the list read its
13+
* object definition from the adapter's PUBLISHED `getObjectSchema`, which does
14+
* not know the field, and sent every column.
15+
*
16+
* Pinned here, on the app-shell side:
17+
* 1. `withUnpublishedObjectReads`, given the overlay read, answers
18+
* `getObjectSchema` with the published document plus each draft-only field
19+
* under its draft label, marked with the underscore-private literal
20+
* `_draftOnly` (`@object-ui/plugin-list` reads the same literal; its own
21+
* pin is the `ListView.draftOnlyColumn-34807` block of its harness), with
22+
* the published sortability projection kept. CONTROL: without the overlay
23+
* read the source's own `getObjectSchema` answers.
24+
* 2. `usePreviewListDataSource`: the adapter ITSELF outside the preview; one
25+
* wrapper per draft revision inside it.
26+
* 3. The `ObjectDataPage` (`/:objectName/data`) and `InterfaceListPage` call
27+
* sites hand `ListView` that wrapper in the preview and the adapter itself
28+
* outside it.
29+
*/
30+
31+
import * as React from 'react';
32+
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
33+
import { render, renderHook, cleanup, waitFor } from '@testing-library/react';
34+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
35+
import { attachObjectSortability, readObjectSortability } from '@object-ui/core';
36+
37+
/** The overlay read the provider's `getItem('object', name)` answers in these cases. */
38+
type OverlayRead = (type: string, name: string) => Promise<unknown>;
39+
const OVERLAY: { doc: unknown; getItem: ReturnType<typeof vi.fn<OverlayRead>> } = {
40+
doc: null,
41+
getItem: vi.fn<OverlayRead>(),
42+
};
43+
44+
vi.mock('../../providers/MetadataProvider', async (importOriginal) => {
45+
const actual = await importOriginal<Record<string, unknown>>();
46+
const getItem = (type: string, name: string) => OVERLAY.getItem(type, name);
47+
return {
48+
...actual,
49+
useMetadata: () => ({ objects: LIST_PAGE.objects, loading: false, getItem }),
50+
};
51+
});
52+
53+
/** What the pages under test hand `ListView`. */
54+
const CAPTURED: { dataSource: any } = { dataSource: undefined };
55+
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
56+
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
57+
ListView: (props: { dataSource: unknown }) => {
58+
CAPTURED.dataSource = props.dataSource;
59+
return null;
60+
},
61+
}));
62+
63+
vi.mock('@object-ui/permissions', async (importOriginal) => {
64+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
65+
const perms = {
66+
check: () => ({ allowed: true }),
67+
checkField: () => true,
68+
getFieldPermissions: () => [],
69+
getRowFilter: () => undefined,
70+
getObjectApiOperations: () => undefined,
71+
roles: [],
72+
isLoaded: false,
73+
hasCapabilities: () => true,
74+
can: () => true,
75+
cannot: () => false,
76+
};
77+
const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] };
78+
return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms };
79+
});
80+
81+
vi.mock('@object-ui/auth', async (importOriginal) => ({
82+
...(await importOriginal<Record<string, unknown>>()),
83+
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
84+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
85+
createAuthenticatedFetch: () => vi.fn(),
86+
}));
87+
88+
vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () => null }));
89+
vi.mock('../../views/CreateViewDialog', () => ({ CreateViewDialog: () => null }));
90+
vi.mock('../../views/metadata-admin/useMetadata', () => ({ useMetadataClient: () => ({}) }));
91+
92+
vi.mock('@object-ui/react', async (importOriginal) => ({
93+
...(await importOriginal<Record<string, unknown>>()),
94+
useAdapter: () => LIST_PAGE.dataSource,
95+
}));
96+
97+
import { withUnpublishedObjectReads, usePreviewListDataSource } from '../unpublishedObjectReads';
98+
import { PreviewModeProvider } from '../PreviewModeContext';
99+
import { ObjectDataPage } from '../../views/ObjectDataPage';
100+
import { InterfaceListPage } from '../../views/InterfaceListPage';
101+
import { ExpressionProvider } from '../../providers/ExpressionProvider';
102+
103+
const OBJECT = 'tracker_task';
104+
105+
/** The published document the adapter serves, with its sortability projection. */
106+
function publishedDocument() {
107+
const doc = {
108+
name: OBJECT,
109+
label: 'Task',
110+
fields: { title: { name: 'title', type: 'text', label: 'Title' } },
111+
};
112+
return attachObjectSortability(doc, { fields: { title: { sortable: true } } });
113+
}
114+
115+
/** The draft overlay's document: the published field plus the drafted one. */
116+
const DRAFT_DOCUMENT = {
117+
name: OBJECT,
118+
label: 'Task',
119+
fields: {
120+
title: { name: 'title', type: 'text', label: 'Title' },
121+
priority: { name: 'priority', type: 'select', label: 'Priority (draft)' },
122+
},
123+
listViews: { all: { name: 'all', label: 'All', type: 'grid', columns: ['title', 'priority'] } },
124+
};
125+
126+
function makeAdapter() {
127+
return {
128+
find: vi.fn(async () => ({ data: [], total: 0 })),
129+
findOne: vi.fn(async () => null),
130+
create: vi.fn(async () => ({})),
131+
update: vi.fn(async () => ({})),
132+
delete: vi.fn(async () => ({})),
133+
getObjectSchema: vi.fn(async () => publishedDocument()),
134+
} as any;
135+
}
136+
137+
const LIST_PAGE: { dataSource: any; objects: any[] } = { dataSource: undefined, objects: [] };
138+
139+
beforeEach(() => {
140+
OVERLAY.doc = DRAFT_DOCUMENT;
141+
OVERLAY.getItem = vi.fn<OverlayRead>(async () => OVERLAY.doc);
142+
CAPTURED.dataSource = undefined;
143+
LIST_PAGE.dataSource = makeAdapter();
144+
LIST_PAGE.objects = [DRAFT_DOCUMENT];
145+
// The pages' permission reads go to the network; answer them empty.
146+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
147+
status: 200,
148+
headers: { 'content-type': 'application/json' },
149+
})));
150+
});
151+
afterEach(() => {
152+
cleanup();
153+
vi.unstubAllGlobals();
154+
});
155+
156+
describe('withUnpublishedObjectReads: the list definition under draft preview (objectstack#34807)', () => {
157+
it('answers the published document plus the draft-only field, marked `_draftOnly`, under its draft label', async () => {
158+
const adapter = makeAdapter();
159+
const ds = withUnpublishedObjectReads(adapter, () => {}, (name) => OVERLAY.getItem('object', name));
160+
const def: any = await ds.getObjectSchema(OBJECT);
161+
expect(OVERLAY.getItem).toHaveBeenCalledWith('object', OBJECT);
162+
expect(adapter.getObjectSchema).toHaveBeenCalledWith(OBJECT);
163+
expect(def.fields.priority).toMatchObject({ label: 'Priority (draft)', _draftOnly: true });
164+
// The published field keeps its published definition, unmarked.
165+
expect(def.fields.title._draftOnly).toBeUndefined();
166+
// The published sortability projection rides along: it names no draft-only field.
167+
expect(readObjectSortability(def)?.fields).toEqual({ title: { sortable: true } });
168+
});
169+
170+
it('CONTROL: without the overlay read, the source answers its own definition', async () => {
171+
const adapter = makeAdapter();
172+
const ds = withUnpublishedObjectReads(adapter, () => {});
173+
const def: any = await ds.getObjectSchema(OBJECT);
174+
expect(def.fields.priority).toBeUndefined();
175+
expect(OVERLAY.getItem).not.toHaveBeenCalled();
176+
});
177+
});
178+
179+
describe('usePreviewListDataSource (objectstack#34807)', () => {
180+
const wrapper = (preview: boolean) =>
181+
function Wrapper({ children }: { children: React.ReactNode }) {
182+
return (
183+
<MemoryRouter>
184+
<PreviewModeProvider force={preview}>{children}</PreviewModeProvider>
185+
</MemoryRouter>
186+
);
187+
};
188+
189+
it('CONTROL: outside the preview it is the adapter itself', () => {
190+
const adapter = makeAdapter();
191+
const { result } = renderHook(() => usePreviewListDataSource(adapter, DRAFT_DOCUMENT), { wrapper: wrapper(false) });
192+
expect(result.current).toBe(adapter);
193+
});
194+
195+
it('in the preview it wraps the adapter, once per draft revision', async () => {
196+
const adapter = makeAdapter();
197+
let revision: unknown = DRAFT_DOCUMENT;
198+
const { result, rerender } = renderHook(() => usePreviewListDataSource(adapter, revision), { wrapper: wrapper(true) });
199+
const first = result.current;
200+
expect(first).not.toBe(adapter);
201+
expect(((await first.getObjectSchema(OBJECT)) as any).fields.priority._draftOnly).toBe(true);
202+
rerender();
203+
expect(result.current).toBe(first);
204+
revision = { ...DRAFT_DOCUMENT };
205+
rerender();
206+
expect(result.current).not.toBe(first);
207+
});
208+
});
209+
210+
describe('the list pages hand ListView the preview wrapper (objectstack#34807)', () => {
211+
function renderDataPage(preview: boolean) {
212+
return render(
213+
<ExpressionProvider user={{ id: 'u1', name: 'Ada' }}>
214+
<MemoryRouter initialEntries={[`/apps/demo/${OBJECT}/data`]}>
215+
<PreviewModeProvider force={preview}>
216+
<Routes>
217+
<Route
218+
path="/apps/:appName/:objectName/data"
219+
element={<ObjectDataPage dataSource={LIST_PAGE.dataSource} objects={LIST_PAGE.objects} />}
220+
/>
221+
</Routes>
222+
</PreviewModeProvider>
223+
</MemoryRouter>
224+
</ExpressionProvider>,
225+
);
226+
}
227+
228+
function renderInterfacePage(preview: boolean) {
229+
const page = {
230+
name: 'my_tasks',
231+
label: 'My Tasks',
232+
interfaceConfig: { source: OBJECT, sourceView: 'all' },
233+
};
234+
return render(
235+
<MemoryRouter initialEntries={['/apps/demo/page/my_tasks']}>
236+
<PreviewModeProvider force={preview}>
237+
<InterfaceListPage page={page as any} />
238+
</PreviewModeProvider>
239+
</MemoryRouter>,
240+
);
241+
}
242+
243+
for (const [name, renderPage] of [
244+
['ObjectDataPage', renderDataPage],
245+
['InterfaceListPage', renderInterfacePage],
246+
] as const) {
247+
it(`${name}: in the preview, ListView reads the draft-only field marked`, async () => {
248+
renderPage(true);
249+
await waitFor(() => expect(CAPTURED.dataSource).toBeDefined());
250+
expect(CAPTURED.dataSource).not.toBe(LIST_PAGE.dataSource);
251+
const def: any = await CAPTURED.dataSource.getObjectSchema(OBJECT);
252+
expect(def.fields.priority).toMatchObject({ label: 'Priority (draft)', _draftOnly: true });
253+
});
254+
255+
it(`${name} CONTROL: outside the preview, ListView gets the adapter itself`, async () => {
256+
renderPage(false);
257+
await waitFor(() => expect(CAPTURED.dataSource).toBeDefined());
258+
expect(CAPTURED.dataSource).toBe(LIST_PAGE.dataSource);
259+
expect(OVERLAY.getItem).not.toHaveBeenCalled();
260+
});
261+
}
262+
});

‎ui/packages/app-shell/src/preview/unpublishedObjectReads.ts‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,28 @@
2727
* publish sentence. Every other failure (a 403, a 500, a refused `findOne`)
2828
* reaches the list unchanged, and outside the preview it is never installed,
2929
* so a missing object on the live console is still an error.
30+
*
31+
* objectstack#34807 (ruling 6946403206) — a list column on a field that exists
32+
* only in the draft. The data door validates every `$select`, `$filter` and
33+
* `$orderby` name against the PUBLISHED object, so a draft-only column refused
34+
* the whole list query (`400 INVALID_FIELD`), and the list read its object
35+
* definition from the adapter's published `getObjectSchema`, which does not
36+
* know the field at all. Given the provider's overlay read, this wrapper's
37+
* `getObjectSchema` answers {@link readDraftPreviewObjectSchema}: the
38+
* published document plus each draft-only field with its draft label, marked
39+
* `_draftOnly` (the form half's convention, `utils/previewFormDataSource.ts`),
40+
* with the published sortability projection kept. `@object-ui/plugin-list`
41+
* reads the marker and keeps those names out of every data request, drawing
42+
* the column empty under its draft label. The data contract is unchanged:
43+
* data reads never see a draft schema.
3044
*/
3145

46+
import { useRef } from 'react';
3247
import { answeredLoadFailure } from '@object-ui/react';
3348
import type { DataSource } from '@object-ui/types';
49+
import { useMetadata } from '../providers/MetadataProvider.js';
50+
import { readDraftPreviewObjectSchema } from '../utils/previewFormDataSource.js';
51+
import { usePreviewDrafts } from './PreviewModeContext.js';
3452

3553
/** The data engine's answer for an object it has not registered. */
3654
export const UNPUBLISHED_OBJECT_CODE = 'OBJECT_NOT_FOUND';
@@ -44,12 +62,19 @@ export function isUnpublishedObjectRefusal(err: unknown): boolean {
4462
* `ds`, except that a `find` the data engine refuses with
4563
* {@link UNPUBLISHED_OBJECT_CODE} answers an empty page and reports the
4664
* object through `onUnpublished`, so the caller can say why the list is empty.
47-
* Every other member is the source's own, bound to it.
65+
* Given `readOverlay` (the draft overlay's read of one object document),
66+
* `getObjectSchema` answers {@link readDraftPreviewObjectSchema} over the
67+
* source's own published read. Every other member is the source's own, bound
68+
* to it.
4869
*/
4970
export function withUnpublishedObjectReads(
5071
ds: DataSource,
5172
onUnpublished: (objectName: string) => void,
73+
readOverlay?: (objectName: string) => Promise<unknown>,
5274
): DataSource {
75+
const getObjectSchema = readOverlay && typeof ds.getObjectSchema === 'function'
76+
? (objectName: string) => readDraftPreviewObjectSchema(ds, readOverlay, objectName)
77+
: undefined;
5378
return new Proxy(ds, {
5479
get(target, prop, receiver) {
5580
if (prop === 'find') {
@@ -63,8 +88,50 @@ export function withUnpublishedObjectReads(
6388
}
6489
};
6590
}
91+
if (prop === 'getObjectSchema' && getObjectSchema) return getObjectSchema;
6692
const value = Reflect.get(target, prop, receiver);
6793
return typeof value === 'function' ? value.bind(target) : value;
6894
},
6995
});
7096
}
97+
98+
const IGNORE_UNPUBLISHED = (): void => {};
99+
100+
/**
101+
* The data source a list page hands `ListView`: `ds` itself outside draft
102+
* preview; inside it, {@link withUnpublishedObjectReads} over `ds`, reading
103+
* draft-only fields through the provider's overlay (`useMetadata().getItem`,
104+
* which reads through the preview client in preview).
105+
*
106+
* `revision` is the page's own draft-aware definition of the object (the
107+
* provider's `objects` entry): a new one means the draft changed, and only
108+
* then is a new wrapper made, so the list re-reads its definition when a
109+
* field is drafted and otherwise keeps one data source identity. A page with
110+
* no publish sentence of its own passes no `onUnpublished`.
111+
*/
112+
export function usePreviewListDataSource<T extends DataSource | null | undefined>(
113+
ds: T,
114+
revision?: unknown,
115+
onUnpublished: (objectName: string) => void = IGNORE_UNPUBLISHED,
116+
): T {
117+
const previewDrafts = usePreviewDrafts();
118+
const { getItem } = useMetadata();
119+
// Read at call time, so neither callback's identity decides the wrapper's.
120+
const getItemRef = useRef(getItem);
121+
getItemRef.current = getItem;
122+
const unpublishedRef = useRef(onUnpublished);
123+
unpublishedRef.current = onUnpublished;
124+
// Cached on the inputs the wrapper is made of (the source and the payload
125+
// `revision`), not on a memo's identity (ui/AGENTS.md #10).
126+
const cache = useRef<{ ds: DataSource; revision: unknown; wrapped: DataSource } | null>(null);
127+
if (!previewDrafts || !ds) return ds;
128+
const held = cache.current;
129+
if (held && held.ds === ds && held.revision === revision) return held.wrapped as T;
130+
const wrapped = withUnpublishedObjectReads(
131+
ds,
132+
(name) => unpublishedRef.current(name),
133+
(name) => getItemRef.current('object', name),
134+
);
135+
cache.current = { ds, revision, wrapped };
136+
return wrapped as T;
137+
}

0 commit comments

Comments
 (0)