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
19 changes: 19 additions & 0 deletions .changeset/35940-master-detail-form-new-lines.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@object-ui/plugin-form': patch
'@object-ui/fields': patch
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

fix(form): a new detail line on a master-detail create / edit form starts on the child's defaults, does not read red before a save is tried, and a line added and left untouched is skipped with a notice on the form and the record page

Clause-②: no
Metadata-protocol: none

On a parent object's create or edit form, a line added to a detail table started blank, so a required column with a default (a status that defaults to "Pending") read red at once although saving would store the default. The record page's edit state already started its new lines on their defaults; the form now does the same.

**New lines on the form.** A new line starts on the child object's static defaults, the values a create form of the child seeds, whether it is added with Add or with Enter on the last line. A default the server resolves at insert (`NOW()`, a CEL expression) is left to the server. A new line's empty required cell reads red once a save of the form was tried, not the moment the line appears; a stored line is flagged as before. A line added with Add and then applied from the row editor is the user's input and is saved.

**A line added and left untouched** (maintainer ruling, card comment 7056413638: 「跳过并提示未保存」). A line Add started on its defaults that nobody edited holds only those defaults. It is still not written, and the save now says so: once the save lands, the form and the record page's edit state show "1 blank line was not saved" (or "N blank lines were not saved"), also when the host supplies its own save confirmation. Such a line never reads red, before or after a refused save, since there is nothing in it to fix; once the user edits any of its cells it is input, saved and flagged like any other new line. On an edit form that stays open after saving, the skipped line leaves with the save, as it does on the record page. A line the user typed into and then cleared is blank and is skipped as before, without the notice. The pack key is `form.lineItems.untouchedNotSaved`, in every built-in locale.

**Seeding context.** The defaults on both the form and the record page's edit state are now read with the session facts a create form uses: a child field defaulted to the acting user starts on that user, and the organization's currency and time zone seed the fields they seed on a create form. With no known user that field starts empty and the server fills it, as before.
18 changes: 12 additions & 6 deletions ui/e2e/live/record-page-polish-35745.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { test, expect, type Page } from '@playwright/test';
* 3. in the edit state Save is the one filled button, after Cancel;
* 4. a line added to the Expense Lines table starts on the child object's
* defaults (Category "Other", Status "Submitted") with no cell flagged
* red, and a line added and left as it came is not stored by the save.
* red, and a line added and left as it came is not stored by the save,
* which says so.
*
* ⚠️ Layout is the reason this is a Playwright spec: jsdom lays nothing out,
* so the 12 px is read here off real boxes. The vitest pins
Expand Down Expand Up @@ -101,22 +102,27 @@ test('record page polish (#35745, #35816) — showcase Expense Report', async ({
// ── 4. A new line starts on its defaults, unflagged; left as it came, it is not stored. ──
const editor = page.locator('[data-body-table-editor]').first();
await editor.scrollIntoViewIfNeeded();
const lines = editor.locator('tbody tr');
// A line row, not the empty state's row (an empty grid draws one).
const lines = editor.locator('tbody tr').filter({ hasNot: page.getByTestId('line-items-empty') });
const before = await lines.count();
await editor.getByTestId('line-items-add').click();
await expect(lines).toHaveCount(before + 1);
// The grid keeps a trailing entry line, so the added line is the one before it.
const added = lines.nth(before - 1);
const added = lines.nth(before);
await expect(added).toContainText('Other');
await expect(added).toContainText('Submitted');
await expect(editor.locator('[data-testid^="line-items-invalid"]')).toHaveCount(0);

await save.click();
await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 });
const stored = await request.get(`${API}/api/v1/data/${LINE}?$top=500`);
// objectstack#35940 (ruling 7056413638): the save says the line was left out.
await expect(page.getByText('1 blank line was not saved')).toBeVisible();
// Asked of the server for this report's lines only: a filter the route
// ignored would answer other reports' lines, and fail the count.
const ofThisReport = encodeURIComponent(JSON.stringify([['expense_report', 'equals', id]]));
const stored = await request.get(`${API}/api/v1/data/${LINE}?$filter=${ofThisReport}`);
expect(stored.ok(), await stored.text()).toBeTruthy();
const body = await stored.json();
const rows: any[] = (body.records ?? body.data ?? []).filter((r: any) => r.expense_report === id);
const rows: any[] = body.records ?? body.data ?? [];
expect(rows, 'an added line left on its defaults is not stored').toHaveLength(0);
} finally {
await request.delete(`${API}/api/v1/data/${OBJECT}/${encodeURIComponent(id)}`);
Expand Down
2 changes: 1 addition & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:live": "playwright test --config=playwright.live.config.ts",
"test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts",
"test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts record-page-polish-35745.spec.ts",
"test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts",
"test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts"
},
Expand Down
43 changes: 40 additions & 3 deletions ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import { render, waitFor, cleanup, screen, act, fireEvent } from '@testing-library/react';
import { MemoryRouter, Route, Routes, BrowserRouter } from 'react-router-dom';
import { toast } from 'sonner';
import { RelatedCountStore } from '@object-ui/components';
import { ComponentRegistry } from '@object-ui/core';
import { I18nProvider, LocalizationProvider, createI18n } from '@object-ui/i18n';
Expand Down Expand Up @@ -2941,7 +2942,8 @@ describe('RecordDetailView.recordEditState-35599', () => {
showcase_task: [{ id: 't1', subject: 'Call', quote: RECORD_ID }],
};

function renderPage(objects: ReturnType<typeof objectsWith>, opts: { emptyTables?: boolean } = {}) {
/** `i18n`: under the real English provider, so a notice reads as the pack writes it. */
function renderPage(objects: ReturnType<typeof objectsWith>, opts: { emptyTables?: boolean; i18n?: boolean } = {}) {
const metadata = {
objects, pages: [], loading: false, error: null,
refresh: async () => {}, invalidate: () => {},
Expand All @@ -2960,7 +2962,7 @@ describe('RecordDetailView.recordEditState-35599', () => {
batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })),
};
const onEdit = vi.fn();
const view = render(
const page = (
<MemoryRouter initialEntries={[`/apps/demo/${PARENT}/record/${RECORD_ID}`]}>
<MetadataCtx.Provider value={metadata}>
<NavigationProvider>
Expand All @@ -2973,7 +2975,12 @@ describe('RecordDetailView.recordEditState-35599', () => {
</Routes>
</NavigationProvider>
</MetadataCtx.Provider>
</MemoryRouter>,
</MemoryRouter>
);
const view = render(
opts.i18n
? <I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>{page}</I18nProvider>
: page,
);
return { ...view, dataSource, onEdit };
}
Expand Down Expand Up @@ -3196,6 +3203,36 @@ describe('RecordDetailView.recordEditState-35599', () => {
expect(summaryInput(view.container)).not.toBeNull();
});

it('objectstack#35940 (ruling 7056413638): a line Add started and nobody edited is not written, and the save says so', async () => {
const view = renderPage(objectsWith(), { i18n: true });
await enterEditState(view);
vi.mocked(toast.info).mockClear();
fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } });
const lines = editor(view.container, 'showcase_line.quote')!;
const before = cells(lines, 'Product').length;
fireEvent.click(lines.querySelector('[data-testid="line-items-add"]') as HTMLElement);
await waitFor(() => expect(cells(lines, 'Product').length).toBe(before + 1), { timeout: 5000 });
await act(async () => { fireEvent.click(headerButton('Save')!); });
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
// The record's update alone: the untouched line is not created.
const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array<Record<string, any>>;
expect(ops.map((o) => [o.object, o.action])).toEqual([[PARENT, 'update']]);
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
expect(toast.info).toHaveBeenCalledTimes(1);
expect(toast.info).toHaveBeenCalledWith('1 blank line was not saved');
});

it('CONTROL — a save that skips no untouched line says nothing more', async () => {
const view = renderPage(objectsWith());
await enterEditState(view);
vi.mocked(toast.info).mockClear();
editEverything(view.container);
await act(async () => { fireEvent.click(headerButton('Save')!); });
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
expect(toast.info).not.toHaveBeenCalled();
});

it('item 5: a child without bulk keeps its table read-only in the edit state, with the notice', async () => {
const view = renderPage(objectsWith({ lineEnable: { apiMethods: ['get', 'list', 'create', 'update', 'delete'] } }));
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
Expand Down
1 change: 1 addition & 0 deletions ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5671,6 +5671,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
bodyTablesReadOnly={bodyTableIds.size > 0 && !bodyTablesEditable}
readOnlyNotice={t('detail.bodyTablesReadOnlyBulk')}
unsavedMessage={t('form.unsavedChanges')}
untouchedNotSaved={(count) => t('form.lineItems.untouchedNotSaved', { count })}
>
<HighlightFieldsProvider>
<DiscussionContextProvider
Expand Down
18 changes: 17 additions & 1 deletion ui/packages/app-shell/src/views/recordEditState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
type BodyTableEditHandle,
type RecordEditSession,
} from '@object-ui/plugin-form';
import { isUntouchedNewRow } from '@object-ui/fields';
import {
AlertDialog,
AlertDialogAction,
Expand All @@ -50,6 +51,7 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
toast,
} from '@object-ui/components';
import { useInlineEdit, type RelatedRecordActionsValue } from '@object-ui/react';
import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '@object-ui/plugin-detail';
Expand Down Expand Up @@ -175,6 +177,11 @@ export interface RecordEditStateControllerProps {
readOnlyNotice: string;
/** The question asked before unsaved edits are dropped. */
unsavedMessage: string;
/**
* The notice after a save that skipped `count` lines Add started on their
* defaults and nobody edited (objectstack#35940, ruling 7056413638).
*/
untouchedNotSaved: (count: number) => string;
children: React.ReactNode;
}

Expand All @@ -198,6 +205,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
bodyTablesReadOnly,
readOnlyNotice,
unsavedMessage,
untouchedNotSaved,
children,
}) => {
const inline = useInlineEdit();
Expand Down Expand Up @@ -294,12 +302,19 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
})
: [];
const built = buildRecordEditBatch(objectName, String(recordId), draft, tables);
// objectstack#35940 — the lines the batch skips untouched: never written,
// and said so once the save has landed (or had nothing else to write).
const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0);
const sayWhatWasSkipped = () => {
if (skipped > 0) toast.info(untouchedNotSaved(skipped));
};
// An untouched record writes no update of its own: op 0 goes when the draft is empty.
const hasDraft = Object.keys(draft).length > 0;
const ops = hasDraft ? built.ops : built.ops.slice(1);
const owners = hasDraft ? built.owners : built.owners.slice(1);
if (ops.length === 0) {
await finish();
sayWhatWasSkipped();
return;
}
setSaving(true);
Expand All @@ -312,6 +327,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
await runBatchTransaction(dataSource, ops);
}
await finish();
sayWhatWasSkipped();
} catch (err) {
const refusal = attributeRecordEditRefusal(err, ops, owners);
inline.setFieldErrors(refusal.fieldErrors);
Expand All @@ -323,7 +339,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
inline.setSaving(false);
setSaving(false);
}
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish]);
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]);

const cancel = useCallback(() => {
inline?.cancel();
Expand Down
40 changes: 40 additions & 0 deletions ui/packages/fields/src/widgets/GridField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,46 @@ describe('GridField — a new line starts on its defaults and waits to read red
});
});

describe('GridField — a line Add started on its defaults and nobody edited never reads red (objectstack#35940)', () => {
const taskColumns = {
columns: [
{ name: 'name', label: 'Name', type: 'text' as const, required: true },
{ name: 'status', label: 'Status', type: 'text' as const, required: true },
],
} as any;

it('stays unflagged after the host says a save was refused, while an edited new line is flagged', () => {
const rows = [
{ name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true },
{ name: null, status: 'done' },
];
render(<GridField value={rows} onChange={() => {}} field={taskColumns} newRowValues={{ status: 'pending' }} newRowRequiredShown />);
expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull();
expect(screen.getByTestId('line-items-invalid-1-name')).toBeTruthy();
});

it('a line Enter appends on the last line starts on the defaults and is marked untouched, as Add\'s is', () => {
const onChange = vi.fn();
render(<GridField value={[{ name: 'A', status: 'done' }]} onChange={onChange} field={taskColumns} newRowValues={{ status: 'pending' }} />);
fireEvent.keyDown(screen.getByDisplayValue('done'), { key: 'Enter' });
const appended = onChange.mock.lastCall![0][1];
expect(appended).toMatchObject({ status: 'pending' });
expect(isUntouchedNewRow(appended)).toBe(true);
});

it('its first edit makes it input, and from then on it is flagged like any new line', () => {
const onChange = vi.fn();
const field = { columns: [...taskColumns.columns, { name: 'note', label: 'Note', type: 'text' as const }] } as any;
const rows = [{ name: null, status: 'pending', note: null, [UNTOUCHED_NEW_ROW]: true }];
const { rerender } = render(
<GridField value={rows} onChange={onChange} field={field} newRowValues={{ status: 'pending' }} newRowRequiredShown />,
);
fireEvent.change(screen.getAllByDisplayValue('pending')[0], { target: { value: 'done' } });
rerender(<GridField value={onChange.mock.lastCall![0]} onChange={onChange} field={field} newRowValues={{ status: 'pending' }} newRowRequiredShown />);
expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy();
});
});

/**
* objectstack#35507 — no blank entry row beside "Add line". The grid used to
* append an always-present empty "ghost" line under the data rows; it carried
Expand Down
10 changes: 8 additions & 2 deletions ui/packages/fields/src/widgets/GridField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,9 @@ type GridFieldProps = FieldWidgetComponentProps<Row[]> & {
* no id) is flagged only while it is `true` (objectstack#35816): a line
* the user just added does not read red before the host has tried to save
* it, and does once a save was refused. A stored line is flagged as
* before. Absent: every line is flagged at once, as before. */
* before. Absent: every line is flagged at once, as before. A line still
* marked {@link UNTOUCHED_NEW_ROW} is never flagged (objectstack#35940):
* the host skips it at save. */
newRowRequiredShown?: boolean;
/** The help text of each column's child field, by column name
* ({@link ColumnHelp}, objectstack#35804): drawn as an info button beside
Expand Down Expand Up @@ -1698,8 +1700,12 @@ function GridFieldBody({
const required = cellRules(c, row).required;
// objectstack#35816 — a new line waits for the host's
// word before it reads red; a stored line does not.
// objectstack#35940 — a line Add started on its defaults
// and nobody edited never reads red: the save skips it
// and says so, so there is nothing in it to fix.
const newRowWaits =
newRowRequiredShown === false && !isGhost && !rowHasId(row);
(newRowRequiredShown === false && !isGhost && !rowHasId(row)) ||
isUntouchedNewRow(row);
const invalid =
(!isGhost || hostFailedEmpty) &&
!newRowWaits &&
Expand Down
7 changes: 7 additions & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,13 @@ const ar = {
notLoaded: "لم يتم تحميل بنود هذا السجل.",
loadFailed: "تعذّر تحميل البنود",
saveFailed: "تعذّر حفظ البنود",
untouchedNotSaved: "لم يُحفظ {{count}} سطر فارغ",
untouchedNotSaved_zero: "لم يُحفظ {{count}} سطر فارغ",
untouchedNotSaved_one: "لم يُحفظ {{count}} سطر فارغ",
untouchedNotSaved_two: "لم يُحفظ سطران فارغان ({{count}})",
untouchedNotSaved_few: "لم تُحفظ {{count}} أسطر فارغة",
untouchedNotSaved_many: "لم يُحفظ {{count}} سطرًا فارغًا",
untouchedNotSaved_other: "لم يُحفظ {{count}} سطر فارغ",
noChildObject: "لم يُكوَّن كائن فرعي لهذه اللوحة: عيّن {{property}} إلى الكائن الذي تسرد صفوفه.",
},
keepEditing: "متابعة التحرير",
Expand Down
Loading
Loading