Skip to content

Commit 32409a9

Browse files
fix(form): new master-detail form lines start on the child's defaults and skip an untouched line with a notice (#35940) (#35984)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuWrjronJ2on8T4hXL4F5MV7)_ Fixes #35940 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户在主对象的新建/编辑表单里点「添加明细」,新行直接带上子对象的默认值(如状态「已提交」),点保存之前必填格不再一出来就标红;记录页编辑态同样如此。 - 属于「记录详情页重做」专题的衍生问题:主表单和记录页的新增明细行行为原本不一致,这次对齐。 - 加了一行却一个格都没动,保存照常成功,不会写入这行,并提示「1 行空白明细未保存」(按你选的「跳过并提示未保存」);这是纯前端行为,回退本 PR 即恢复原样。 - 要你做什么:无。 ## What changes On a parent object's create / edit form (`MasterDetailForm` → `LineItemsField`), a new detail line now behaves the way the record page's edit state already does (#35937): - **Starts on the child's defaults.** `MasterDetailForm` builds each child's static defaults with `schemaDefaultValues` (the values a create form of the child seeds) and passes them as `newRowValues`. A default the server resolves at insert (`NOW()`, CEL) is left to the server. - **Not red before a save is tried.** `newRowRequiredShown` is false until a save of the form is tried; a stored line is flagged as before. - **Seeding context.** Both the form and `RecordBodyTableEditor` now read the defaults with the session facts `ObjectForm` threads (`currentUserId`, `homeCurrency`, `homeTimeZone`), so a field defaulted to the acting user starts on that user. The editor's `childSchema` cast is gone (rider 1 and 2 of comment 7051917540). - **A line added and left untouched (ruling 7056413638, 「跳过并提示未保存」).** A line Add started on its defaults that nobody edited is skipped at save (as before), and the save now says so: `form.lineItems.untouchedNotSaved` ("1 blank line was not saved" / "N blank lines were not saved"), on the form (also when the host supplies `onSuccess`) and on the record page's edit state. Such a line is never red, before or after a refused save (`GridField`: `isUntouchedNewRow` ⇒ the row waits). Once the user edits any cell, or applies the line from the row editor, it is input: saved and flagged like any other new line. On an edit form that stays open, the skipped line leaves with the save. A line typed into and then cleared stays blank and is skipped without the notice. The count is of marked lines only. A line Enter appends on the last line (#35998) starts and is marked the same way. - **Live spec in CI (rider 4).** `record-page-polish-35745.spec.ts` joins `test:e2e:live:ci`; its "not stored" check asks the server with `$filter` on `expense_report`, and it now asserts the notice. - Pack key in all 11 built-in locales (each locale's plural set) plus the `formChrome.ts` defaults rows. <details><summary>Read first (risk order) and the two-minute check</summary> 1. `ui/packages/plugin-form/src/MasterDetailForm.tsx`: the `saveTried` flips (set in `handleSave` and `submitViaBatch`, cleared in `handleSaved`), the `untouchedSkippedRef` count in `sendBatch`, and the edit-mode post-save `filter((r) => !isUntouchedNewRow(r))`. 2. `ui/packages/fields/src/widgets/GridField.tsx`: `newRowWaits` now also holds for a marked row. 3. `ui/packages/app-shell/src/views/recordEditState.tsx`: the notice after `finish()` on both the no-op and success paths. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-form/src/MasterDetailForm.test.tsx` → 17 passed, including the "ruling 7056413638" block. </details> ## Tests - `MasterDetailForm.test.tsx`: new describe "a new line starts on the child's defaults and waits to read red": defaults shown and red only after the try; CONTROL stored line flagged at once; acting user written; Add then row-editor Apply is written. Nested "ruling 7056413638": create skip + notice with a host `onSuccess`; a refused save flags the edited row, not the untouched one; edit mode drops the skipped line after save. - `RecordBodyTableEditor.seedContext-35940.test.tsx` (new): acting user seeded; CONTROL with no known user the field starts empty. - `GridField.test.tsx`: a marked row is never red; its first edit makes it input. - `RecordDetailView.harness.test.tsx`: the page notice plus a parent-update-only batch; CONTROL no notice. <details><summary>Ablations (each applied on disk to the committed head with <code>scripts/ablation-replace.mjs</code>, file restored after)</summary> | Ablation | Result | |---|---| | `GridField` `isUntouchedNewRow` term removed | GridField 1 failed; MasterDetailForm 1 failed | | `newRowRequiredShown` prop deleted (MDF) | 1 failed | | `newRowValues` prop deleted (MDF) | 6 failed | | MDF seed context removed | 1 failed | | RBE seed context removed | 1 failed | | row-editor Apply keeps the untouched mark | 1 failed | | MDF notice removed | 2 failed | | MDF edit-mode drop removed | 1 failed | | page notice removed | 1 failed | A form-mode Add seed (row editor) ablated stayed green: the row editor's `ObjectForm` already seeds defaults through its own create detection, so that code was removed (96501c2) rather than kept untested. </details> ## Acceptance notes - Form-mode Add (row editor) gets its defaults from the editor's own create seeding; no separate seed here. - `minRows` is out of scope (seat facts, 23:18Z). - Merged with main twice (K = 23 at the seat's ask, then a conflict after #35998). #35998 draws no trailing entry line, so the second merge commit (b08c7f5) also moves this PR's tests and the live spec to read the new line as the one Add appends: `addSeededLine` waits for the child schema and sees the line start on 'Pending'; the harness counts lines before and after Add; the live spec skips the empty state's row; one GridField pin adds Enter-append. Conflicts were two append-only test blocks (both kept) and one import line (union). - Branch name is the harness name `claude/project-thread-c6vkj1`. ## Verification Post-merge on b08c7f5: `vitest run` MasterDetailForm, GridField, RecordBodyTableEditor*, RecordDetailView.harness → Test Files 5 passed, Tests 173 passed; GridField alone 71 passed with the Enter-append pin; `@object-ui/fields` and `@object-ui/plugin-form` type-check exit 0 (closure rebuilt); `check:nul-bytes`, `check:i18n-keys` exit 0. The live spec's new row reading is left to CI's Live E2E UI on this head. Earlier readings, all on head e642739: - CI: 46 check runs success, 13 skipped by their own rules, 0 failed. - Unit tests under the verify lock: `vitest run packages/fields packages/i18n packages/plugin-form` → Test Files 655 passed | 1 skipped, Tests 9356 passed | 21 skipped; `vitest run packages/app-shell/src/views` → Test Files 1575 passed, Tests 14926 passed | 1 skipped. Declared narrowing: app-shell outside `src/views` was left to CI (one run of all four packages passed 40 minutes on this 4-core box and was stopped). - Type-check: `@object-ui/fields`, `@object-ui/i18n`, `@object-ui/plugin-form`, `@object-ui/app-shell` (after building its closure) all exit 0. - Derived gates: `dispatch-gates --ran` → 56 derived, 56 run, 0 NOT-MEASURED, 0 UNRUN, every exit 0. `check:type-check-debt` first queue-timed out (exit 3, not measured) and was re-run under the lock: OK, 0 raw tsc errors above the ledger. ui `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys` exit 0. <details><summary>Real browser on the live stack (workspace showcase backend :4010 + built console preview)</summary> - `playwright test --config=playwright.live.config.ts record-page-polish-35745.spec.ts` → 1 passed (5.8s). - Create form, showcase Expense Report: Add line → line 1 reads Category "Other", Line Status "Submitted"; 0 cells flagged (`line-items-invalid*` count 0). Create → toast "1 blank line was not saved" beside the created toast; the server holds the report and 0 lines for it (`$filter` on `expense_report`). - Record page edit state: Add line → defaults, 0 flagged; Save → "1 blank line was not saved"; 0 lines stored. - Screenshots kept with the seat's evidence for this card. </details> --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgWYi6WWWnJAmc7Jtpu <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgWYi6WWWnJAmc7Jtpu --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 907b378 commit 32409a9

24 files changed

Lines changed: 551 additions & 24 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
'@object-ui/fields': patch
4+
'@object-ui/app-shell': patch
5+
'@object-ui/i18n': patch
6+
---
7+
8+
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
9+
10+
Clause-②: no
11+
Metadata-protocol: none
12+
13+
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.
14+
15+
**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.
16+
17+
**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.
18+
19+
**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.

‎ui/e2e/live/record-page-polish-35745.spec.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ import { test, expect, type Page } from '@playwright/test';
1212
* 3. in the edit state Save is the one filled button, after Cancel;
1313
* 4. a line added to the Expense Lines table starts on the child object's
1414
* defaults (Category "Other", Status "Submitted") with no cell flagged
15-
* red, and a line added and left as it came is not stored by the save.
15+
* red, and a line added and left as it came is not stored by the save,
16+
* which says so.
1617
*
1718
* ⚠️ Layout is the reason this is a Playwright spec: jsdom lays nothing out,
1819
* so the 12 px is read here off real boxes. The vitest pins
@@ -101,22 +102,27 @@ test('record page polish (#35745, #35816) — showcase Expense Report', async ({
101102
// ── 4. A new line starts on its defaults, unflagged; left as it came, it is not stored. ──
102103
const editor = page.locator('[data-body-table-editor]').first();
103104
await editor.scrollIntoViewIfNeeded();
104-
const lines = editor.locator('tbody tr');
105+
// A line row, not the empty state's row (an empty grid draws one).
106+
const lines = editor.locator('tbody tr').filter({ hasNot: page.getByTestId('line-items-empty') });
105107
const before = await lines.count();
106108
await editor.getByTestId('line-items-add').click();
107109
await expect(lines).toHaveCount(before + 1);
108-
// The grid keeps a trailing entry line, so the added line is the one before it.
109-
const added = lines.nth(before - 1);
110+
const added = lines.nth(before);
110111
await expect(added).toContainText('Other');
111112
await expect(added).toContainText('Submitted');
112113
await expect(editor.locator('[data-testid^="line-items-invalid"]')).toHaveCount(0);
113114

114115
await save.click();
115116
await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 });
116-
const stored = await request.get(`${API}/api/v1/data/${LINE}?$top=500`);
117+
// objectstack#35940 (ruling 7056413638): the save says the line was left out.
118+
await expect(page.getByText('1 blank line was not saved')).toBeVisible();
119+
// Asked of the server for this report's lines only: a filter the route
120+
// ignored would answer other reports' lines, and fail the count.
121+
const ofThisReport = encodeURIComponent(JSON.stringify([['expense_report', 'equals', id]]));
122+
const stored = await request.get(`${API}/api/v1/data/${LINE}?$filter=${ofThisReport}`);
117123
expect(stored.ok(), await stored.text()).toBeTruthy();
118124
const body = await stored.json();
119-
const rows: any[] = (body.records ?? body.data ?? []).filter((r: any) => r.expense_report === id);
125+
const rows: any[] = body.records ?? body.data ?? [];
120126
expect(rows, 'an added line left on its defaults is not stored').toHaveLength(0);
121127
} finally {
122128
await request.delete(`${API}/api/v1/data/${OBJECT}/${encodeURIComponent(id)}`);

‎ui/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
"test:e2e": "playwright test",
111111
"test:e2e:ui": "playwright test --ui",
112112
"test:e2e:live": "playwright test --config=playwright.live.config.ts",
113-
"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",
113+
"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",
114114
"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",
115115
"test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts"
116116
},

‎ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import * as React from 'react';
4848
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
4949
import { render, waitFor, cleanup, screen, act, fireEvent } from '@testing-library/react';
5050
import { MemoryRouter, Route, Routes, BrowserRouter } from 'react-router-dom';
51+
import { toast } from 'sonner';
5152
import { RelatedCountStore } from '@object-ui/components';
5253
import { ComponentRegistry } from '@object-ui/core';
5354
import { I18nProvider, LocalizationProvider, createI18n } from '@object-ui/i18n';
@@ -2941,7 +2942,8 @@ describe('RecordDetailView.recordEditState-35599', () => {
29412942
showcase_task: [{ id: 't1', subject: 'Call', quote: RECORD_ID }],
29422943
};
29432944

2944-
function renderPage(objects: ReturnType<typeof objectsWith>, opts: { emptyTables?: boolean } = {}) {
2945+
/** `i18n`: under the real English provider, so a notice reads as the pack writes it. */
2946+
function renderPage(objects: ReturnType<typeof objectsWith>, opts: { emptyTables?: boolean; i18n?: boolean } = {}) {
29452947
const metadata = {
29462948
objects, pages: [], loading: false, error: null,
29472949
refresh: async () => {}, invalidate: () => {},
@@ -2960,7 +2962,7 @@ describe('RecordDetailView.recordEditState-35599', () => {
29602962
batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })),
29612963
};
29622964
const onEdit = vi.fn();
2963-
const view = render(
2965+
const page = (
29642966
<MemoryRouter initialEntries={[`/apps/demo/${PARENT}/record/${RECORD_ID}`]}>
29652967
<MetadataCtx.Provider value={metadata}>
29662968
<NavigationProvider>
@@ -2973,7 +2975,12 @@ describe('RecordDetailView.recordEditState-35599', () => {
29732975
</Routes>
29742976
</NavigationProvider>
29752977
</MetadataCtx.Provider>
2976-
</MemoryRouter>,
2978+
</MemoryRouter>
2979+
);
2980+
const view = render(
2981+
opts.i18n
2982+
? <I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>{page}</I18nProvider>
2983+
: page,
29772984
);
29782985
return { ...view, dataSource, onEdit };
29792986
}
@@ -3196,6 +3203,36 @@ describe('RecordDetailView.recordEditState-35599', () => {
31963203
expect(summaryInput(view.container)).not.toBeNull();
31973204
});
31983205

3206+
it('objectstack#35940 (ruling 7056413638): a line Add started and nobody edited is not written, and the save says so', async () => {
3207+
const view = renderPage(objectsWith(), { i18n: true });
3208+
await enterEditState(view);
3209+
vi.mocked(toast.info).mockClear();
3210+
fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } });
3211+
const lines = editor(view.container, 'showcase_line.quote')!;
3212+
const before = cells(lines, 'Product').length;
3213+
fireEvent.click(lines.querySelector('[data-testid="line-items-add"]') as HTMLElement);
3214+
await waitFor(() => expect(cells(lines, 'Product').length).toBe(before + 1), { timeout: 5000 });
3215+
await act(async () => { fireEvent.click(headerButton('Save')!); });
3216+
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
3217+
// The record's update alone: the untouched line is not created.
3218+
const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array<Record<string, any>>;
3219+
expect(ops.map((o) => [o.object, o.action])).toEqual([[PARENT, 'update']]);
3220+
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
3221+
expect(toast.info).toHaveBeenCalledTimes(1);
3222+
expect(toast.info).toHaveBeenCalledWith('1 blank line was not saved');
3223+
});
3224+
3225+
it('CONTROL — a save that skips no untouched line says nothing more', async () => {
3226+
const view = renderPage(objectsWith());
3227+
await enterEditState(view);
3228+
vi.mocked(toast.info).mockClear();
3229+
editEverything(view.container);
3230+
await act(async () => { fireEvent.click(headerButton('Save')!); });
3231+
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
3232+
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
3233+
expect(toast.info).not.toHaveBeenCalled();
3234+
});
3235+
31993236
it('item 5: a child without bulk keeps its table read-only in the edit state, with the notice', async () => {
32003237
const view = renderPage(objectsWith({ lineEnable: { apiMethods: ['get', 'list', 'create', 'update', 'delete'] } }));
32013238
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });

‎ui/packages/app-shell/src/views/RecordDetailView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5671,6 +5671,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
56715671
bodyTablesReadOnly={bodyTableIds.size > 0 && !bodyTablesEditable}
56725672
readOnlyNotice={t('detail.bodyTablesReadOnlyBulk')}
56735673
unsavedMessage={t('form.unsavedChanges')}
5674+
untouchedNotSaved={(count) => t('form.lineItems.untouchedNotSaved', { count })}
56745675
>
56755676
<HighlightFieldsProvider>
56765677
<DiscussionContextProvider

‎ui/packages/app-shell/src/views/recordEditState.tsx‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
type BodyTableEditHandle,
4242
type RecordEditSession,
4343
} from '@object-ui/plugin-form';
44+
import { isUntouchedNewRow } from '@object-ui/fields';
4445
import {
4546
AlertDialog,
4647
AlertDialogAction,
@@ -50,6 +51,7 @@ import {
5051
AlertDialogFooter,
5152
AlertDialogHeader,
5253
AlertDialogTitle,
54+
toast,
5355
} from '@object-ui/components';
5456
import { useInlineEdit, type RelatedRecordActionsValue } from '@object-ui/react';
5557
import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '@object-ui/plugin-detail';
@@ -175,6 +177,11 @@ export interface RecordEditStateControllerProps {
175177
readOnlyNotice: string;
176178
/** The question asked before unsaved edits are dropped. */
177179
unsavedMessage: string;
180+
/**
181+
* The notice after a save that skipped `count` lines Add started on their
182+
* defaults and nobody edited (objectstack#35940, ruling 7056413638).
183+
*/
184+
untouchedNotSaved: (count: number) => string;
178185
children: React.ReactNode;
179186
}
180187

@@ -198,6 +205,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
198205
bodyTablesReadOnly,
199206
readOnlyNotice,
200207
unsavedMessage,
208+
untouchedNotSaved,
201209
children,
202210
}) => {
203211
const inline = useInlineEdit();
@@ -294,12 +302,19 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
294302
})
295303
: [];
296304
const built = buildRecordEditBatch(objectName, String(recordId), draft, tables);
305+
// objectstack#35940 — the lines the batch skips untouched: never written,
306+
// and said so once the save has landed (or had nothing else to write).
307+
const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0);
308+
const sayWhatWasSkipped = () => {
309+
if (skipped > 0) toast.info(untouchedNotSaved(skipped));
310+
};
297311
// An untouched record writes no update of its own: op 0 goes when the draft is empty.
298312
const hasDraft = Object.keys(draft).length > 0;
299313
const ops = hasDraft ? built.ops : built.ops.slice(1);
300314
const owners = hasDraft ? built.owners : built.owners.slice(1);
301315
if (ops.length === 0) {
302316
await finish();
317+
sayWhatWasSkipped();
303318
return;
304319
}
305320
setSaving(true);
@@ -312,6 +327,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
312327
await runBatchTransaction(dataSource, ops);
313328
}
314329
await finish();
330+
sayWhatWasSkipped();
315331
} catch (err) {
316332
const refusal = attributeRecordEditRefusal(err, ops, owners);
317333
inline.setFieldErrors(refusal.fieldErrors);
@@ -323,7 +339,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
323339
inline.setSaving(false);
324340
setSaving(false);
325341
}
326-
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish]);
342+
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]);
327343

328344
const cancel = useCallback(() => {
329345
inline?.cancel();

‎ui/packages/fields/src/widgets/GridField.test.tsx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,46 @@ describe('GridField — a new line starts on its defaults and waits to read red
847847
});
848848
});
849849

850+
describe('GridField — a line Add started on its defaults and nobody edited never reads red (objectstack#35940)', () => {
851+
const taskColumns = {
852+
columns: [
853+
{ name: 'name', label: 'Name', type: 'text' as const, required: true },
854+
{ name: 'status', label: 'Status', type: 'text' as const, required: true },
855+
],
856+
} as any;
857+
858+
it('stays unflagged after the host says a save was refused, while an edited new line is flagged', () => {
859+
const rows = [
860+
{ name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true },
861+
{ name: null, status: 'done' },
862+
];
863+
render(<GridField value={rows} onChange={() => {}} field={taskColumns} newRowValues={{ status: 'pending' }} newRowRequiredShown />);
864+
expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull();
865+
expect(screen.getByTestId('line-items-invalid-1-name')).toBeTruthy();
866+
});
867+
868+
it('a line Enter appends on the last line starts on the defaults and is marked untouched, as Add\'s is', () => {
869+
const onChange = vi.fn();
870+
render(<GridField value={[{ name: 'A', status: 'done' }]} onChange={onChange} field={taskColumns} newRowValues={{ status: 'pending' }} />);
871+
fireEvent.keyDown(screen.getByDisplayValue('done'), { key: 'Enter' });
872+
const appended = onChange.mock.lastCall![0][1];
873+
expect(appended).toMatchObject({ status: 'pending' });
874+
expect(isUntouchedNewRow(appended)).toBe(true);
875+
});
876+
877+
it('its first edit makes it input, and from then on it is flagged like any new line', () => {
878+
const onChange = vi.fn();
879+
const field = { columns: [...taskColumns.columns, { name: 'note', label: 'Note', type: 'text' as const }] } as any;
880+
const rows = [{ name: null, status: 'pending', note: null, [UNTOUCHED_NEW_ROW]: true }];
881+
const { rerender } = render(
882+
<GridField value={rows} onChange={onChange} field={field} newRowValues={{ status: 'pending' }} newRowRequiredShown />,
883+
);
884+
fireEvent.change(screen.getAllByDisplayValue('pending')[0], { target: { value: 'done' } });
885+
rerender(<GridField value={onChange.mock.lastCall![0]} onChange={onChange} field={field} newRowValues={{ status: 'pending' }} newRowRequiredShown />);
886+
expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy();
887+
});
888+
});
889+
850890
/**
851891
* objectstack#35507 — no blank entry row beside "Add line". The grid used to
852892
* append an always-present empty "ghost" line under the data rows; it carried

‎ui/packages/fields/src/widgets/GridField.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,9 @@ type GridFieldProps = FieldWidgetComponentProps<Row[]> & {
702702
* no id) is flagged only while it is `true` (objectstack#35816): a line
703703
* the user just added does not read red before the host has tried to save
704704
* it, and does once a save was refused. A stored line is flagged as
705-
* before. Absent: every line is flagged at once, as before. */
705+
* before. Absent: every line is flagged at once, as before. A line still
706+
* marked {@link UNTOUCHED_NEW_ROW} is never flagged (objectstack#35940):
707+
* the host skips it at save. */
706708
newRowRequiredShown?: boolean;
707709
/** The help text of each column's child field, by column name
708710
* ({@link ColumnHelp}, objectstack#35804): drawn as an info button beside
@@ -1698,8 +1700,12 @@ function GridFieldBody({
16981700
const required = cellRules(c, row).required;
16991701
// objectstack#35816 — a new line waits for the host's
17001702
// word before it reads red; a stored line does not.
1703+
// objectstack#35940 — a line Add started on its defaults
1704+
// and nobody edited never reads red: the save skips it
1705+
// and says so, so there is nothing in it to fix.
17011706
const newRowWaits =
1702-
newRowRequiredShown === false && !isGhost && !rowHasId(row);
1707+
(newRowRequiredShown === false && !isGhost && !rowHasId(row)) ||
1708+
isUntouchedNewRow(row);
17031709
const invalid =
17041710
(!isGhost || hostFailedEmpty) &&
17051711
!newRowWaits &&

‎ui/packages/i18n/src/locales/ar.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,13 @@ const ar = {
233233
notLoaded: "لم يتم تحميل بنود هذا السجل.",
234234
loadFailed: "تعذّر تحميل البنود",
235235
saveFailed: "تعذّر حفظ البنود",
236+
untouchedNotSaved: "لم يُحفظ {{count}} سطر فارغ",
237+
untouchedNotSaved_zero: "لم يُحفظ {{count}} سطر فارغ",
238+
untouchedNotSaved_one: "لم يُحفظ {{count}} سطر فارغ",
239+
untouchedNotSaved_two: "لم يُحفظ سطران فارغان ({{count}})",
240+
untouchedNotSaved_few: "لم تُحفظ {{count}} أسطر فارغة",
241+
untouchedNotSaved_many: "لم يُحفظ {{count}} سطرًا فارغًا",
242+
untouchedNotSaved_other: "لم يُحفظ {{count}} سطر فارغ",
236243
noChildObject: "لم يُكوَّن كائن فرعي لهذه اللوحة: عيّن {{property}} إلى الكائن الذي تسرد صفوفه.",
237244
},
238245
keepEditing: "متابعة التحرير",

0 commit comments

Comments
 (0)