Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/34807-draft-preview-list-column.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<unknown>;
const OVERLAY: { doc: unknown; getItem: ReturnType<typeof vi.fn<OverlayRead>> } = {
doc: null,
getItem: vi.fn<OverlayRead>(),
};

vi.mock('../../providers/MetadataProvider', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
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<typeof import('@object-ui/plugin-list')>()),
ListView: (props: { dataSource: unknown }) => {
CAPTURED.dataSource = props.dataSource;
return null;
},
}));

vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
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<Record<string, unknown>>()),
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<Record<string, unknown>>()),
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<OverlayRead>(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 (
<MemoryRouter>
<PreviewModeProvider force={preview}>{children}</PreviewModeProvider>
</MemoryRouter>
);
};

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(
<ExpressionProvider user={{ id: 'u1', name: 'Ada' }}>
<MemoryRouter initialEntries={[`/apps/demo/${OBJECT}/data`]}>
<PreviewModeProvider force={preview}>
<Routes>
<Route
path="/apps/:appName/:objectName/data"
element={<ObjectDataPage dataSource={LIST_PAGE.dataSource} objects={LIST_PAGE.objects} />}
/>
</Routes>
</PreviewModeProvider>
</MemoryRouter>
</ExpressionProvider>,
);
}

function renderInterfacePage(preview: boolean) {
const page = {
name: 'my_tasks',
label: 'My Tasks',
interfaceConfig: { source: OBJECT, sourceView: 'all' },
};
return render(
<MemoryRouter initialEntries={['/apps/demo/page/my_tasks']}>
<PreviewModeProvider force={preview}>
<InterfaceListPage page={page as any} />
</PreviewModeProvider>
</MemoryRouter>,
);
}

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();
});
}
});
69 changes: 68 additions & 1 deletion ui/packages/app-shell/src/preview/unpublishedObjectReads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<unknown>,
): 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') {
Expand All @@ -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<T extends DataSource | null | undefined>(
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;
}
Loading
Loading