diff --git a/.changeset/34898-grid-draft-only-fields.md b/.changeset/34898-grid-draft-only-fields.md new file mode 100644 index 00000000000..f42e268b9ab --- /dev/null +++ b/.changeset/34898-grid-draft-only-fields.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +--- + +fix(plugin-grid): a grouped grid under draft preview no longer asks the data door for fields only the draft declares + +Clause-②: yes — one new locale key (the visible "this grouping waits for publish" note the card's Expected names), locale-only; no spec, no new exported prop +Metadata-protocol: none + +Under the console's draft preview (`?preview=draft`) the object definition marks each field only the draft adds with `_draftOnly`, while the data door still checks every requested field against the published object. A grouped grid built its own requests from that definition, so a draft-only column went into every group's row request and every group showed `INVALID_FIELD`, and a grouping on a draft-only field went out as the header query's `groupBy` and the whole grid showed "Error loading grid". + +The grid now leaves a draft-only field out of its row `$select` and `$expand`, on the flat fetch and on every group's row page; the column still draws, empty, under its draft label. A grouping entry on a draft-only field is dropped the way a masked grouping key is: the grid groups by the published entries left, or draws ungrouped, and one note above the rows (`grid.grouping.draftOnly`, new in every locale pack) names the field and says grouping by it waits for publish. After Publish the marker is gone, and the grouping and the column work on the next definition read without a reload. Outside the preview no field carries the marker and nothing changes. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index b8e2d76ac5a..8b0120bfd3a 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -629,6 +629,7 @@ const ar = { "هذا العرض مُجمَّع، لكن مصدر بياناته لا يطبّق queryGroupHeaders، لذا لا يمكن عدّ المجموعات. أزِل التجميع لعرض السجلات.", needsWholeRows: "يتطلب التجميع جميع السجلات، لكن هذه الشبكة تلقّت صفحة واحدة منها فقط، لذا لا يمكن عدّ المجموعات. مرّر جميع السجلات، أو دع الشبكة تجلبها من مصدر بيانات يطبّق queryGroupHeaders.", + draftOnly: "لم يتم التجميع حسب {{fields}}: هذا الحقل موجود في المسودة فقط حتى تقوم بالنشر.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 19e4ef1d927..1302e42a652 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -583,6 +583,7 @@ const de = { "Diese Ansicht ist gruppiert, aber ihre Datenquelle implementiert queryGroupHeaders nicht, daher können die Gruppen nicht gezählt werden. Entfernen Sie die Gruppierung, um die Datensätze anzuzeigen.", needsWholeRows: "Die Gruppierung benötigt alle Datensätze, aber dieses Raster hat nur eine Seite davon erhalten, daher können die Gruppen nicht gezählt werden. Übergeben Sie alle Datensätze oder lassen Sie das Raster sie aus einer Datenquelle laden, die queryGroupHeaders implementiert.", + draftOnly: "Nicht nach {{fields}} gruppiert: Das Feld existiert nur im Entwurf, bis Sie veröffentlichen.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 05dc3eac472..88a78bdea22 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -816,6 +816,7 @@ const en = { 'This view is grouped, but its data source does not implement queryGroupHeaders, so the groups cannot be counted. Remove the grouping to show the records.', needsWholeRows: 'Grouping needs every record, but this grid was handed one page of them, so the groups cannot be counted. Hand in every record, or let the grid fetch them from a data source that implements queryGroupHeaders.', + draftOnly: 'Not grouped by {{fields}}: it exists only in the draft until you publish.', }, // Column-footer aggregate prefixes, keyed by the spec's `ColumnSummary` // vocabulary (objectui#4024). The footer already formatted its NUMBER diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 18596c01fb4..6edce614748 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -598,6 +598,7 @@ const es = { "Esta vista está agrupada, pero su origen de datos no implementa queryGroupHeaders, por lo que no se pueden contar los grupos. Quite la agrupación para mostrar los registros.", needsWholeRows: "La agrupación necesita todos los registros, pero esta cuadrícula recibió solo una página de ellos, por lo que no se pueden contar los grupos. Entregue todos los registros o deje que la cuadrícula los obtenga de un origen de datos que implemente queryGroupHeaders.", + draftOnly: "No agrupado por {{fields}}: solo existe en el borrador hasta que publique.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 008363ecffa..a9e5e017090 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -593,6 +593,7 @@ const fr = { "Cette vue est groupée, mais sa source de données n'implémente pas queryGroupHeaders : les groupes ne peuvent donc pas être comptés. Supprimez le regroupement pour afficher les enregistrements.", needsWholeRows: "Le regroupement a besoin de tous les enregistrements, mais cette grille n'en a reçu qu'une page : les groupes ne peuvent donc pas être comptés. Fournissez tous les enregistrements, ou laissez la grille les charger depuis une source de données qui implémente queryGroupHeaders.", + draftOnly: "Non regroupé par {{fields}} : ce champ n'existe que dans le brouillon jusqu'à la publication.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 42ea9c925b3..4e6e1ad7ded 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -583,6 +583,7 @@ const ja = { "このビューはグループ化されていますが、データソースが queryGroupHeaders を実装していないため、グループの件数を数えられません。レコードを表示するにはグループ化を解除してください。", needsWholeRows: "グループ化にはすべてのレコードが必要ですが、このグリッドにはその一部のページしか渡されていないため、グループの件数を数えられません。すべてのレコードを渡すか、queryGroupHeaders を実装したデータソースからグリッドに読み込ませてください。", + draftOnly: "{{fields}} ではグループ化されていません:公開するまで下書きにのみ存在します。", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6bb204167d0..5334f4c3480 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -583,6 +583,7 @@ const ko = { "이 뷰는 그룹화되어 있지만 데이터 소스가 queryGroupHeaders를 구현하지 않아 그룹 개수를 셀 수 없습니다. 레코드를 표시하려면 그룹화를 제거하세요.", needsWholeRows: "그룹화에는 모든 레코드가 필요하지만 이 그리드에는 한 페이지만 전달되어 그룹 개수를 셀 수 없습니다. 모든 레코드를 전달하거나 queryGroupHeaders를 구현하는 데이터 소스에서 그리드가 불러오도록 하세요.", + draftOnly: "{{fields}}(으)로 그룹화되지 않았습니다: 게시할 때까지 초안에만 존재합니다.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index b4a7a70058a..87663e30303 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -593,6 +593,7 @@ const pt = { "Esta visão está agrupada, mas sua fonte de dados não implementa queryGroupHeaders, portanto os grupos não podem ser contados. Remova o agrupamento para mostrar os registros.", needsWholeRows: "O agrupamento precisa de todos os registros, mas esta grade recebeu apenas uma página deles, portanto os grupos não podem ser contados. Entregue todos os registros ou deixe a grade buscá-los em uma fonte de dados que implemente queryGroupHeaders.", + draftOnly: "Não agrupado por {{fields}}: existe apenas no rascunho até você publicar.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ff3b4d5b044..d5c43aae7a4 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -606,6 +606,7 @@ const ru = { "Это представление сгруппировано, но его источник данных не реализует queryGroupHeaders, поэтому группы невозможно подсчитать. Уберите группировку, чтобы показать записи.", needsWholeRows: "Для группировки нужны все записи, но этой таблице передана только одна их страница, поэтому группы невозможно подсчитать. Передайте все записи или позвольте таблице загрузить их из источника данных, который реализует queryGroupHeaders.", + draftOnly: "Без группировки по {{fields}}: это поле существует только в черновике до публикации.", }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 094504a6ffb..2cd196b5d51 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -566,6 +566,7 @@ const zh = { '此视图已分组,但其数据源未实现 queryGroupHeaders,因此无法统计分组。移除分组即可显示记录。', needsWholeRows: '分组需要全部记录,但此表格只收到其中一页,因此无法统计分组。请传入全部记录,或让表格从实现了 queryGroupHeaders 的数据源获取记录。', + draftOnly: '未按 {{fields}} 分组:它仅存在于草稿中,发布后才生效。', }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 993f6f4677a..387c5328d92 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -566,6 +566,7 @@ const zhHant = { '此檢視已分組,但其資料來源未實現 queryGroupHeaders,因此無法統計分組。移除分組即可顯示記錄。', needsWholeRows: '分組需要全部記錄,但此表格只收到其中一頁,因此無法統計分組。請傳入全部記錄,或讓表格從實現了 queryGroupHeaders 的資料來源獲取記錄。', + draftOnly: '未按 {{fields}} 分組:它僅存在於草稿中,釋出後才生效。', }, // objectui#4024 — column-footer aggregate prefixes, keyed by the spec's // `ColumnSummary` vocabulary. `pattern` owns the label/value join so this diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 823a2fe2e93..4ba6540cfe8 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1180,6 +1180,7 @@ export const ObjectGrid: React.FC = ({ // grouping refusals and the fetch window (`./objectGridGroupingDecisions`). const { unmaskedGroupingFields, + draftOnlyGroupingFields, groupingRefusesNothing, groupingKeyReadable, serverGroupedFetch, @@ -1732,6 +1733,31 @@ export const ObjectGrid: React.FC = ({ ); } + // objectstack#34898 — the grouping sentences' non-blocking sibling. A + // grouping entry on a field only the draft declares is dropped + // (`draftOnlyGroupingFields`) and the grid draws ungrouped, or grouped by the + // published entries left. Unlike the two refusals above nothing is withheld, + // so this is no panel replacing the grid: it is one line drawn above the + // rows, under the description, by every branch that draws them (the card + // view and the table), in the strip `ListView` draws its own draft-preview + // note in, so it is read before the rows it explains. + const groupingDraftOnlyNote = draftOnlyGroupingFields.length > 0 ? ( +

+ {t('grid.grouping.draftOnly', { + fields: draftOnlyGroupingFields + .map((field) => { + const fallback = (objectFields?.[field] as { label?: string } | undefined)?.label || field; + return schema.objectName ? resolveFieldLabel(schema.objectName, field, fallback) : fallback; + }) + .join(', '), + })} +

+ ) : null; + // The generated columns, enriched and folded, with the persisted widths and // order applied (`./objectGridPersistedColumns`). const { persistedColumns } = resolveObjectGridPersistedColumns({ @@ -3517,6 +3543,7 @@ export const ObjectGrid: React.FC = ({ data-testid="object-grid-card-scroller" > {gridDescription} + {groupingDraftOnlyNote}
{data.map(renderMobileCard)}
@@ -4126,6 +4153,7 @@ export const ObjectGrid: React.FC = ({ )} {gridDescription} + {groupingDraftOnlyNote} {gridToolbar} {renderedGridContent} {isGrouped && onRowGroupsChange && ( diff --git a/ui/packages/plugin-grid/src/__tests__/serverGroupedDraftOnly-34898.test.tsx b/ui/packages/plugin-grid/src/__tests__/serverGroupedDraftOnly-34898.test.tsx new file mode 100644 index 00000000000..86b06a4bc17 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/serverGroupedDraftOnly-34898.test.tsx @@ -0,0 +1,248 @@ +/** + * 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#34898 — under the console's draft preview a grouped grid never + * asks the data door for a field only the draft declares. + * + * Under `?preview=draft` the host's data source answers `getObjectSchema` with + * the published definition plus each field only the draft adds, marked + * `_draftOnly`. The door still judges every `$select` and `groupBy` name + * against the PUBLISHED object and refuses one it does not know. Measured on + * origin/main with this double: a draft-only COLUMN went into every group's + * row-page `$select` (`['id','name','priority','category']`, every group + * INVALID_FIELD), and a GROUPING on a draft-only field went out as + * `groupBy: ['priority']` (the whole grid drew "Error loading grid"). + * + * The double answers the way that door does: a `$select` or `groupBy` name the + * published object does not declare is refused, naming it. Publishing moves + * the field into the published set and drops the marker. + * + * CONTROL: each shape with the same field PUBLISHED (no marker) asks for it + * exactly as before, so the pins read the marker, not the field's name. + */ +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; +import { render, cleanup, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { ActionProvider } from '@object-ui/react'; +import { registerAllFields } from '@object-ui/fields'; +import type { DataSource, ObjectGridSchema } from '@object-ui/types'; + +beforeAll(() => { + registerAllFields(); +}); + +afterEach(() => cleanup()); + +const OBJECT = 'crm_product'; + +const BASE_FIELDS: Record> = { + id: { type: 'text', label: 'Id' }, + name: { type: 'text', label: 'Name' }, + category: { type: 'text', label: 'Category' }, +}; +const PRIORITY = { type: 'text', label: 'Priority' }; + +const ROWS: Array> = [ + { id: 'p1', name: 'Router X1', category: 'hardware', priority: 'high' }, + { id: 'p2', name: 'Switch S2', category: 'hardware', priority: 'low' }, + { id: 'p3', name: 'Onsite Setup', category: 'service', priority: 'high' }, +]; + +/** The `FilterCondition` subset the compiled group queries use. */ +function matches(row: Record, cond: unknown): boolean { + if (cond === undefined || cond === null) return true; + return Object.entries(cond as Record).every(([key, value]) => { + if (key === '$and') return (value as unknown[]).every((c) => matches(row, c)); + if (value && typeof value === 'object' && !Array.isArray(value)) { + const op = value as Record; + if ('$eq' in op) return row[key] === op.$eq; + if ('$null' in op) return op.$null ? row[key] == null : row[key] != null; + throw new Error(`double: unsupported operator ${JSON.stringify(op)}`); + } + return row[key] === value; + }); +} + +/** + * The door and the preview definition over one state. `published: false` is + * the draft preview (the definition marks `priority`, the door does not know + * it); `true` is after Publish (declared, unmarked, served). + */ +function makeDataSource(state: { published: boolean }) { + const publishedFields = () => (state.published ? { ...BASE_FIELDS, priority: PRIORITY } : BASE_FIELDS); + const ds = { + queryGroupHeaders: vi.fn(async (_object: string, query: { where?: unknown; groupBy?: string[] }) => { + const groupBy = query.groupBy ?? []; + const unknown = groupBy.find((f) => !(f in publishedFields())); + if (unknown !== undefined) { + throw new Error(`INVALID_FIELD: Unknown groupBy field '${unknown}' on object '${OBJECT}'`); + } + const buckets = new Map(); + for (const row of ROWS.filter((r) => matches(r, query.where))) { + const key = JSON.stringify(groupBy.map((f) => row[f] ?? null)); + buckets.set(key, (buckets.get(key) ?? 0) + 1); + } + return [...buckets.entries()].map(([key, count]) => { + const values = JSON.parse(key) as unknown[]; + return { ...Object.fromEntries(groupBy.map((f, i) => [f, values[i]])), count }; + }); + }), + find: vi.fn(async (_object: string, params: Record) => { + const select = (params.$select as unknown[] | undefined) ?? []; + const unknown = select.find((entry) => typeof entry !== 'string' || !(entry in publishedFields())); + if (unknown !== undefined) { + throw new Error(`INVALID_FIELD: Unknown field '${String(unknown)}' on object '${OBJECT}'`); + } + const matching = ROWS.filter((r) => matches(r, params.$filter)); + const skip = (params.$skip as number | undefined) ?? 0; + const top = (params.$top as number | undefined) ?? matching.length; + // Projected as the door projects: only the selected keys come back. + const project = (row: Record) => (select.length === 0 + ? row + : Object.fromEntries(select.map((f) => [f as string, row[f as string]]))); + return { data: matching.slice(skip, skip + top).map(project), total: matching.length }; + }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => ({ + name: OBJECT, + fields: state.published + ? { ...BASE_FIELDS, priority: PRIORITY } + : { ...BASE_FIELDS, priority: { ...PRIORITY, _draftOnly: true } }, + })), + }; + return ds; +} +type Ds = ReturnType; + +const gridNode = (ds: Ds, schemaExtra: Record) => ( + + + +); + +const BY_CATEGORY = { grouping: { fields: [{ field: 'category', order: 'asc' }] } }; +const BY_PRIORITY = { grouping: { fields: [{ field: 'priority', order: 'asc' }] } }; +const BY_PRIORITY_THEN_CATEGORY = { grouping: { fields: [{ field: 'priority', order: 'asc' }, { field: 'category', order: 'asc' }] } }; + +const groupRowErrors = () => [...document.querySelectorAll('[data-testid^="group-rows-error-"]')]; +const draftNote = () => screen.queryByTestId('grid-grouping-draft-only'); +const groupBys = (ds: Ds) => ds.queryGroupHeaders.mock.calls.map(([, q]) => (q as { groupBy?: string[] }).groupBy); + +describe('a draft-only COLUMN is never projected (objectstack#34898)', () => { + it('grouped by a published field: no group row page selects it, and the column still draws', async () => { + const ds = makeDataSource({ published: false }); + render(gridNode(ds, BY_CATEGORY)); + + await vi.waitFor(() => expect(ds.find).toHaveBeenCalledTimes(2)); + for (const [, params] of ds.find.mock.calls) { + expect(params.$select).toEqual(['id', 'name', 'category']); + } + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(groupRowErrors()).toHaveLength(0); + expect(groupBys(ds)).toEqual([['category']]); + // Drawn, empty, under its draft label; no grouping was dropped, so no note. + expect(screen.getAllByText('Priority').length).toBeGreaterThan(0); + expect(screen.queryByText('high')).not.toBeInTheDocument(); + expect(draftNote()).not.toBeInTheDocument(); + }); + + it('ungrouped: the flat fetch does not select it either', async () => { + const ds = makeDataSource({ published: false }); + render(gridNode(ds, {})); + + await vi.waitFor(() => expect(ds.find).toHaveBeenCalledTimes(1)); + expect(ds.find.mock.calls[0][1].$select).toEqual(['id', 'name']); + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + }); + + it('CONTROL — the same column PUBLISHED is selected on every group row page', async () => { + const ds = makeDataSource({ published: true }); + render(gridNode(ds, BY_CATEGORY)); + + await vi.waitFor(() => expect(ds.find).toHaveBeenCalledTimes(2)); + for (const [, params] of ds.find.mock.calls) { + expect(params.$select).toEqual(['id', 'name', 'priority', 'category']); + } + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(screen.getAllByText('high').length).toBeGreaterThan(0); + expect(groupRowErrors()).toHaveLength(0); + }); +}); + +describe('a grouping on a draft-only field degrades visibly (objectstack#34898)', () => { + it('the only grouping key: never sent as groupBy, the grid draws flat and names the field', async () => { + const ds = makeDataSource({ published: false }); + render(gridNode(ds, { columns: ['name'], ...BY_PRIORITY })); + + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(ds.queryGroupHeaders).not.toHaveBeenCalled(); + expect(screen.queryByText('Error loading grid')).not.toBeInTheDocument(); + expect(document.querySelectorAll('[data-testid^="group-row-"]')).toHaveLength(0); + for (const [, params] of ds.find.mock.calls) { + expect(params.$select).not.toContain('priority'); + } + expect(draftNote()).toBeInTheDocument(); + expect(draftNote()).toHaveTextContent('Priority'); + }); + + it('beside a published key: groups by the published key alone, and names the dropped one', async () => { + const ds = makeDataSource({ published: false }); + render(gridNode(ds, { columns: ['name'], ...BY_PRIORITY_THEN_CATEGORY })); + + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(groupBys(ds).length).toBeGreaterThan(0); + for (const groupBy of groupBys(ds)) expect(groupBy).toEqual(['category']); + expect(screen.queryByText('Error loading grid')).not.toBeInTheDocument(); + expect(groupRowErrors()).toHaveLength(0); + expect(draftNote()).toHaveTextContent('Priority'); + }); + + it('CONTROL — the same grouping PUBLISHED is sent as groupBy and draws no note', async () => { + const ds = makeDataSource({ published: true }); + render(gridNode(ds, { columns: ['name'], ...BY_PRIORITY })); + + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(groupBys(ds)).toEqual([['priority']]); + expect(draftNote()).not.toBeInTheDocument(); + }); + + it('after Publish the grouping and the column work in place, with no reload', async () => { + const state = { published: false }; + const ds = makeDataSource(state); + const { rerender } = render(gridNode(ds, BY_PRIORITY)); + await vi.waitFor(() => expect(draftNote()).toBeInTheDocument()); + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + expect(ds.queryGroupHeaders).not.toHaveBeenCalled(); + + // Publish: the door now serves `priority` and the definition drops the + // marker. The host hands the same grid a data source answering for the + // published state (a new identity, as leaving the preview does); the grid + // is re-rendered, never re-mounted, and re-reads the definition. + state.published = true; + const published = { ...ds }; + rerender(gridNode(published as Ds, BY_PRIORITY)); + + await vi.waitFor(() => expect(draftNote()).not.toBeInTheDocument()); + await vi.waitFor(() => expect(groupBys(ds)).toContainEqual(['priority'])); + await vi.waitFor(() => expect(screen.getByText('Onsite Setup')).toBeInTheDocument()); + const lastRowPage = ds.find.mock.calls[ds.find.mock.calls.length - 1][1]; + expect(lastRowPage.$select).toContain('priority'); + expect(groupRowErrors()).toHaveLength(0); + expect(screen.queryByText('Error loading grid')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts b/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts index 9562d4ba941..b161247731d 100644 --- a/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts +++ b/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts @@ -16,6 +16,18 @@ import { normalizeColumns } from './objectGridColumns'; import { DEFAULT_FETCH_BATCH_SIZE, NO_GROUPING_REFUSAL, resolvePageSize } from './objectGridDefaults'; import type { ObjectGridExternalPaginationProps } from './objectGridProps'; +/** + * Is `def` a field only the draft declares? The console's draft preview + * (`?preview=draft`) answers `getObjectSchema` with the published definition + * plus each field only the draft adds, carrying the `_draftOnly` marker + * (`@object-ui/app-shell`'s preview data source sets it). An underscore-private + * convention, never an authoring key: outside the preview no definition + * carries it and this answers false for every field. + */ +function isDraftOnlyField(def: unknown): boolean { + return !!def && typeof def === 'object' && (def as { _draftOnly?: unknown })._draftOnly === true; +} + export function useObjectGridGroupingDecisions({ schema, objectName, @@ -31,7 +43,7 @@ export function useObjectGridGroupingDecisions({ }: { schema: ObjectGridSchema; objectName: string | undefined; - objectFields: Readonly> | undefined; + objectFields: Readonly> | undefined; objectTypesPending: boolean; perms: ReturnType; dataSource: DataSource | undefined; @@ -73,14 +85,38 @@ export function useObjectGridGroupingDecisions({ warned: refused.filter((field) => isMaskedGridColumn(columnTypeOf(field), objectFields?.[field]?.type, false)), }); }, [groupingFieldsRaw, schema.columns, objectFields, objectTypesPending]); + // objectstack#34898 — a field only the DRAFT declares is REFUSED as a + // grouping key too. Under the console's draft preview (`?preview=draft`) the + // object definition carries each field only the draft adds, marked + // `_draftOnly` (see `isDraftOnlyField`), while the data door still judges + // every `groupBy` name against the PUBLISHED object and refuses one it does + // not know, which failed the whole grid. So the entry is dropped exactly as + // a masked one is: the grid groups by the published entries left, or draws + // flat, and names the dropped field in a note (`grid.grouping.draftOnly`) + // rather than an error. Read off the same catalogue as the masked rule, so + // after Publish the marker is gone and the entry groups again on the next + // definition read, with no reload. Outside the preview no field carries the + // marker and this list is always empty. + const draftOnlyGroupingKey = JSON.stringify( + usableGroupingFields(groupingFieldsRaw) + .map((gf) => gf.field) + .filter((field) => isDraftOnlyField(objectFields?.[field])), + ); + const draftOnlyGroupingFields = React.useMemo( + () => JSON.parse(draftOnlyGroupingKey) as string[], + [draftOnlyGroupingKey], + ); // Keyed on the authored array and the signature STRING, never on a memo's // identity (AGENTS.md #10). Read only when something was refused: the // unmasked path below hands `useGroupedData` the authored config itself. const unmaskedGroupingFields = React.useMemo(() => { const { refused }: { refused: string[] } = JSON.parse(maskedGroupingSignature); - return usableGroupingFields(groupingFieldsRaw).filter((gf) => !refused.includes(gf.field)); - }, [groupingFieldsRaw, maskedGroupingSignature]); - const groupingRefusesNothing = maskedGroupingSignature === NO_GROUPING_REFUSAL; + const draftOnly: string[] = JSON.parse(draftOnlyGroupingKey); + return usableGroupingFields(groupingFieldsRaw) + .filter((gf) => !refused.includes(gf.field) && !draftOnly.includes(gf.field)); + }, [groupingFieldsRaw, maskedGroupingSignature, draftOnlyGroupingKey]); + const groupingRefusesNothing = maskedGroupingSignature === NO_GROUPING_REFUSAL + && draftOnlyGroupingFields.length === 0; useEffect(() => { const { warned: masked }: { warned: string[] } = JSON.parse(maskedGroupingSignature); if (masked.length === 0) return; @@ -115,9 +151,15 @@ export function useObjectGridGroupingDecisions({ // masked type — NOT less the entries merely withheld while the object's // types are still loading, or the first render would fetch one flat window // it is about to throw away. - const groupingRefusedKnownMasked = React.useMemo( - () => (JSON.parse(maskedGroupingSignature) as { warned: string[] }).warned, - [maskedGroupingSignature], + // objectstack#34898: a draft-only entry is refused on a KNOWN fact as well + // (the definition that marks it has landed), so it counts nowhere below: it + // neither makes the grid group on the server nor asks for a header query. + const groupingRefusedKnown = React.useMemo( + () => [ + ...(JSON.parse(maskedGroupingSignature) as { warned: string[] }).warned, + ...(JSON.parse(draftOnlyGroupingKey) as string[]), + ], + [maskedGroupingSignature, draftOnlyGroupingKey], ); // A grouping field this principal may not READ is not a key the server may // group by: a header row carries every key's raw value, so grouping by it @@ -130,7 +172,7 @@ export function useObjectGridGroupingDecisions({ && !!objectName && typeof dataSource?.queryGroupHeaders === 'function' && usableGroupingFields(groupingFieldsRaw).some( - (gf) => !groupingRefusedKnownMasked.includes(gf.field) && groupingKeyReadable(gf.field), + (gf) => !groupingRefusedKnown.includes(gf.field) && groupingKeyReadable(gf.field), ); // [objectui#10881] The refusal: this grid would fetch its own rows and group // them, and its data source cannot answer the group header query. There is @@ -148,7 +190,7 @@ export function useObjectGridGroupingDecisions({ && !!objectName && !!dataSource && typeof dataSource.queryGroupHeaders !== 'function' - && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnownMasked.includes(gf.field)); + && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnown.includes(gf.field)); // [objectui#10881] The second refusal: rows a host handed in that the SAME // host declares to be one page of more — the external-pagination props // (`externalManualPagination`) with a `rowCount` above the rows it handed. @@ -167,7 +209,7 @@ export function useObjectGridGroupingDecisions({ externalManualPagination && Array.isArray(handedRows) && (hostRowCount as number) > handedRows.length - && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnownMasked.includes(gf.field)); + && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnown.includes(gf.field)); // What the load effect's ONE flat fetch asks for (objectui#9853, ruling // 5824040487, structure B). Where the rows it holds ARE the page on screen, // that is the display page size. Where this grid buckets the rows it holds @@ -188,7 +230,7 @@ export function useObjectGridGroupingDecisions({ const bucketsFetchedWindow = !serverGroupedFetch && !groupingNeedsHeaderQuery - && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnownMasked.includes(gf.field)); + && usableGroupingFields(groupingFieldsRaw).some((gf) => !groupingRefusedKnown.includes(gf.field)); const fetchWindow = bucketsFetchedWindow ? resolvePageSize(schema, DEFAULT_FETCH_BATCH_SIZE) : serverPageSize; @@ -209,6 +251,7 @@ export function useObjectGridGroupingDecisions({ return { unmaskedGroupingFields, + draftOnlyGroupingFields, groupingRefusesNothing, groupingKeyReadable, serverGroupedFetch, diff --git a/ui/packages/plugin-grid/src/objectGridRowLoad.ts b/ui/packages/plugin-grid/src/objectGridRowLoad.ts index ef260d36af7..09a4be98b87 100644 --- a/ui/packages/plugin-grid/src/objectGridRowLoad.ts +++ b/ui/packages/plugin-grid/src/objectGridRowLoad.ts @@ -56,6 +56,34 @@ function toOrderByClause(sort: QuerySortEntry[] | undefined | null): string | un return ordered.map((s) => `${s.field} ${s.order}`).join(', '); } +/** + * The field names an object definition marks `_draftOnly` (objectstack#34898): + * under the console's draft preview (`?preview=draft`) `getObjectSchema` + * answers the published definition plus each field only the draft adds, + * carrying that marker (`@object-ui/app-shell`'s preview data source sets it). + * An underscore-private convention, never an authoring key: outside the + * preview no field carries it and the set is empty. Either field-map shape. + */ +function draftOnlyFieldNames(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)._draftOnly === true) names.add(name); + } + return names.size > 0 ? names : NO_DRAFT_ONLY_FIELDS; +} +const NO_DRAFT_ONLY_FIELDS: ReadonlySet = new Set(); + +/** Whether a field reference (`owner`, or a dotted `owner.name`) starts at a draft-only field. */ +function refersToDraftOnly(ref: unknown, draftOnly: ReadonlySet): boolean { + return typeof ref === 'string' && draftOnly.size > 0 && draftOnly.has(ref.split('.')[0]); +} + export function useObjectGridRowLoad({ schema, dataSource, objectName, dataConfig, hasInlineData, perms, refreshKey, hostFindParams, lastFindParamsRef, setData, setLoading, setError, setObjectSchema, setTotalMatching, @@ -175,6 +203,12 @@ export function useObjectGridRowLoad({ // backends that reject rather than ignore it), while `$expand` is // gated structurally by `buildExpandFields` itself. const groupingFieldRefs = collectGroupingFieldRefs(schema.grouping); + // objectstack#34898 — the names the definition marks draft-only (see + // `draftOnlyFieldNames`); empty outside the draft preview. + const draftOnly = draftOnlyFieldNames(resolvedSchema); + const withoutDraftOnly = (list: any[]): any[] => (draftOnly.size === 0 + ? list + : list.filter((f: any) => !refersToDraftOnly(columnIdentity(f), draftOnly))); const getSelectFields = () => { // Always include 'id' so row click / navigation handlers can resolve // the record key — without it `record.id` is undefined and the @@ -496,11 +530,21 @@ export function useObjectGridRowLoad({ .filter(passesProjectionGate) .map((entry) => columnIdentity(entry)) .filter((v): v is string => !!v); + // objectstack#34898 — a field only the DRAFT declares is never + // asked of the door. Under the console's draft preview the object + // definition carries it (marked `_draftOnly`), while the door judges + // every `$select` name against the PUBLISHED object and answers + // INVALID_FIELD for one it does not know — every group's row page + // carried it, so every group showed the error. Applied to the WHOLE + // projection, last, so a column, a grouping key and every harvested + // operand pass the same rule; the column still draws, empty, under + // its draft label. Outside the preview nothing is marked and the + // projection is unchanged. if (schemaFields) { - return withHarvestedFields(ensureId(projectFieldNames(schemaFields as unknown[]))); + return withoutDraftOnly(withHarvestedFields(ensureId(projectFieldNames(schemaFields as unknown[])))); } if (schemaColumns && Array.isArray(schemaColumns)) { - return withHarvestedFields(ensureId(projectFieldNames(schemaColumns))); + return withoutDraftOnly(withHarvestedFields(ensureId(projectFieldNames(schemaColumns)))); } return undefined; }; @@ -663,10 +707,12 @@ export function useObjectGridRowLoad({ .filter((read) => read.expand) .map((read) => read.field) : []; + // objectstack#34898: a draft-only relation is not expanded either — + // the door judges `$expand` names against the published object too. const expand = buildExpandFields( resolvedSchema?.fields, expandColumns ? [...(expandColumns as any[]), ...groupingFieldRefs, ...parentCurrencyRoots] : undefined, - ).filter(expandReadable); + ).filter(expandReadable).filter((f) => !refersToDraftOnly(f, draftOnly)); if (expand.length > 0) { params.$expand = expand; } diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index 81366bfc5db..5a4d3ec3902 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -40,6 +40,10 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { // …and over rows a host handed in while declaring them one page of more. 'grid.grouping.needsWholeRows': 'Grouping needs every record, but this grid was handed one page of them, so the groups cannot be counted. Hand in every record, or let the grid fetch them from a data source that implements queryGroupHeaders.', + // …and the note over a grouping entry on a field only the draft declares, + // dropped under the console's draft preview (objectstack#34898). + // Byte-identical to the `en` pack. + 'grid.grouping.draftOnly': 'Not grouped by {{fields}}: it exists only in the draft until you publish.', // Reused by the grouped-view pager (falls back here when no I18nProvider). 'table.rowsPerPage': 'Rows per page', 'table.pageInfo': 'Page {{current}} of {{total}}',