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
15 changes: 15 additions & 0 deletions .changeset/34599-subform-sticky-save-bar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/plugin-form': patch
---

fix(plugin-form): the master-detail Save bar stays in view, and closing a master-detail dialog with unsaved input asks first

Clause-②: no
Metadata-protocol: none

A form with inline sub-tables (`subforms`) drew its Cancel and Save buttons after the last field and the last line, so in a dialog, a drawer or on the record page a long form had to be scrolled to the end before it could be saved.

- **The action bar is pinned.** `MasterDetailForm` keeps its own Cancel and Save (ADR-0035 Decision §6), and the bar now sticks to the bottom edge of whatever scroll frame hosts the form: the dialog body, the drawer, the record page. The test ids `md-form-cancel` and `md-form-submit` are unchanged.
- **Closing asks before it discards.** The master-detail arm of `ModalForm` closed on Escape, a backdrop click or the X with the typed values and edited lines gone. It now goes through the same "Discard changes?" confirmation, and the same page-unload prompt, as a form without sub-tables. Input counts when it is in the header fields, in the lines (a change the save would write; a blank line does not count) or in the open row editor. `DrawerForm` already routed its close through the guard, and now hears the master-detail form's input too. The explicit Cancel button still closes at once, and a successful save clears the guard.

Nothing changes in how the form saves (one atomic `/api/v1/batch`), and no prop or type is added to the package's exports.
8 changes: 7 additions & 1 deletion ui/packages/plugin-form/src/DrawerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
} from './loadFailure';
import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget';
import { useRecordInvalidation } from './recordInvalidation';
import { FormDirtyReportContext } from './formDirtyReport';
import { useInitialFieldFocus } from './initialFieldFocus';

// Localized strings for the unsaved-changes guard and, since objectui#11039,
Expand Down Expand Up @@ -953,9 +954,13 @@ const DrawerFormBody: React.FC<DrawerFormProps> = ({
) : null;

// Master-detail in a drawer: render the master-detail form (it owns its Save
// bar) when the schema declares inline child collections; saved atomically.
// bar, pinned to the bottom of this drawer's scroll frame) when the schema
// declares inline child collections; saved atomically. It reports its unsaved
// input into this drawer's close guard (`formDirtyReport.ts`), so the close
// paths prompt as they do for the flat body (objectstack#34599).
const subforms = (schema as any).subforms as any[] | undefined;
const drawerBody = subforms?.length && schema.mode !== 'view' ? (
<FormDirtyReportContext.Provider value={setIsDirty}>
<MasterDetailForm
schema={{
type: 'object-master-detail-form',
Expand All @@ -973,6 +978,7 @@ const DrawerFormBody: React.FC<DrawerFormProps> = ({
}}
dataSource={dataSource}
/>
</FormDirtyReportContext.Provider>
) : (
<>
{closedAffordanceNotice}
Expand Down
61 changes: 57 additions & 4 deletions ui/packages/plugin-form/src/MasterDetailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
* `lookup`) FK on the child object.
*/

import React, { startTransition, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types';
import { resolveAffordance, runBatchTransaction } from '@object-ui/core';
import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields';
Expand All @@ -48,6 +48,7 @@ import { dataChangeMatches, subscribeDataChanges } from '@object-ui/react';
import { ObjectForm } from './ObjectForm';
import { applyColumnPermissions } from './fieldWriteGate';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { FormDirtyReportContext } from './formDirtyReport';
import { useFormChromeTranslation } from './formChrome';
import {
buildMasterDetailBatch,
Expand Down Expand Up @@ -1766,6 +1767,41 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
}));
}, []);

/**
* Whether this document holds input a close would discard, reported to the
* hosting overlay's close guard (`formDirtyReport.ts`): the header form's
* renderer verdict, the open row editor's, or any collection whose lines the
* save would write ({@link linesUnsaved}, the edit save's own row diff — so a
* blank ghost line is not input and a reverted edit reads as saved).
*
* The header and the row editor report through reporters this form provides
* around them, never to the host directly. A save clears the header's
* verdict (a create remounts it; an edit's next keystroke reports again) and
* advances or empties the lines, so a saved document reads as pristine.
*/
const reportUnsaved = useContext(FormDirtyReportContext);
const [headerDirty, setHeaderDirty] = useState(false);
const [rowEditorDirty, setRowEditorDirty] = useState(false);
const linesDirty = useMemo(
() =>
entries.some((e) =>
linesUnsaved(rowState[e.id], e.config, parentIdKey, childSchemasRef.current[e.config.childObject]),
),
[entries, rowState, parentIdKey],
);
// A closed row editor holds no draft: Apply wrote it into the lines, and
// cancel dropped it. Its renderer reports nothing on its way out.
useEffect(() => {
if (!expanded) setRowEditorDirty(false);
}, [expanded]);
const unsavedInput = headerDirty || rowEditorDirty || linesDirty;
useEffect(() => {
reportUnsaved?.(unsavedInput);
}, [reportUnsaved, unsavedInput]);
// Unmounted (the overlay closed, or the host swapped forms): nothing of this
// document is on screen to discard any more.
useEffect(() => () => reportUnsaved?.(false), [reportUnsaved]);

// Header tax-rate field name — the live value is read by <MasterDetailLines>
// (from the header record and the user's edits) and drives the Subtotal / Tax
// / Total stack.
Expand Down Expand Up @@ -1826,6 +1862,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
const handleSaved = useCallback(
async (parent: any) => {
releaseSave();
setHeaderDirty(false);
if (!schema.onSuccess) {
toast.success(
isEdit
Expand Down Expand Up @@ -2147,7 +2184,9 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
<div className={cn('space-y-6', className, schema.className)}>
{/* 1) Header fields on top */}
<div ref={formHostRef}>
<ObjectForm key={formKey} schema={parentSchema as any} dataSource={headerDataSource} />
<FormDirtyReportContext.Provider value={setHeaderDirty}>
<ObjectForm key={formKey} schema={parentSchema as any} dataSource={headerDataSource} />
</FormDirtyReportContext.Provider>
</div>

{/* 2) Line items + document totals, in a sibling component that owns the
Expand Down Expand Up @@ -2204,6 +2243,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
row its id. A disabled fieldset disables every control in the
editor, "Apply" included, until the save has settled. */}
<fieldset disabled={saving} className="min-w-0">
<FormDirtyReportContext.Provider value={setRowEditorDirty}>
<ObjectForm
key={`row-${expanded.entryId}-${expanded.rowIdx}`}
schema={{
Expand All @@ -2225,15 +2265,28 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
} as any}
dataSource={dataSource}
/>
</FormDirtyReportContext.Provider>
</fieldset>
</CardContent>
</Card>
)}

{/* Single action bar at the bottom — suppressed when the host opts out
(e.g. the Studio screen-preview, which must never persist). */}
(e.g. the Studio screen-preview, which must never persist).
Pinned to the bottom edge of whatever scroll frame hosts this form —
the dialog body, the drawer, the record page — so Save and Cancel
stay in view at any scroll position (objectstack#34599). Sticky
resolves against the nearest scrolling ancestor, so it is a direct
child of this form's root and nothing between it and the host's
scroller may set `overflow`. Sticky stops at the scroller's CONTENT
edge: the `after:` strip paints over the host's bottom padding below
it, so lines never scroll through that gap. Owned here, not by the
host (ADR-0035 Decision §6: the form owns its Save). */}
{schema.showSubmit !== false && (
<div className="border-t border-border pt-4">
<div
className="sticky bottom-0 z-10 border-t border-border bg-background pt-4 pb-3 after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-6 after:bg-background"
data-testid="md-form-actions"
>
{/* Why Save is unavailable — above the row so it reads before the
dead control (objectui#10166). */}
<UploadInFlightNotice gate={uploadGate} />
Expand Down
81 changes: 47 additions & 34 deletions ui/packages/plugin-form/src/ModalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget';
import { useRecordInvalidation } from './recordInvalidation';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { useInitialFieldFocus } from './initialFieldFocus';
import { FormDirtyReportContext } from './formDirtyReport';

// Localized strings for the unsaved-changes guard and, since objectui#11039,
// the form's own chrome (the default submit and cancel labels and the
Expand Down Expand Up @@ -1183,9 +1184,49 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
);
}

// Radix routes backdrop click, Escape, and the X button all through here, in
// both arms. Closes are intercepted so unsaved input isn't silently
// discarded.
const handleDialogOpenChange = (open: boolean) => {
if (open) { schema.onOpenChange?.(true); return; }
attemptClose(false);
};

// Unsaved-changes guard — rendered INSIDE DialogContent so its portal
// inherits the Dialog's Radix layer context (focus scope + dismissable
// layer) through React. As a sibling of <Dialog> it had no such context, so
// the still-open modal swallowed its button clicks and "Keep editing" did
// nothing. Nesting lets Radix stack the two modals correctly: the alert
// becomes the topmost layer and its buttons work.
const discardDialog = (
<AlertDialog open={discardOpen} onOpenChange={setDiscardOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('form.discardTitle')}</AlertDialogTitle>
<AlertDialogDescription>
{t('form.discardMessage')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => { cancelIntentRef.current = false; }}>
{t('form.keepEditing')}
</AlertDialogCancel>
<AlertDialogAction onClick={finalizeClose}>
{t('form.discard')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);

if (subforms?.length && schema.mode !== 'view') {
// The master-detail form owns its Save bar and pins it to the bottom of
// the body scroller below (objectstack#34599); it reports its unsaved
// input — header, lines, row editor — into this dialog's close guard, so
// the close paths prompt here exactly as they do in the flat arm. Its
// batch save carries no OCC token, so this arm has no conflict dialog.
return (
<Dialog open={isOpen} onOpenChange={schema.onOpenChange}>
<Dialog open={isOpen} onOpenChange={handleDialogOpenChange}>
<MobileDialogContent
showCloseButton={showCloseButton}
onOpenAutoFocus={initialFieldFocus.onOpenAutoFocus}
Expand All @@ -1204,6 +1245,7 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
)}
<div className="@container flex-1 overflow-y-auto px-4 sm:px-6 py-4">
<Suspense fallback={<ModalFormBodyPending />}>
<FormDirtyReportContext.Provider value={setIsDirty}>
<MasterDetailForm
schema={{
type: 'object-master-detail-form',
Expand Down Expand Up @@ -1239,8 +1281,10 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
}}
dataSource={dataSource}
/>
</FormDirtyReportContext.Provider>
</Suspense>
</div>
{discardDialog}
</MobileDialogContent>
</Dialog>
);
Expand All @@ -1249,15 +1293,7 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
const hasFooter = !loading && !error && (showSubmit || showCancel || showReset);

return (
<Dialog
open={isOpen}
onOpenChange={(open) => {
// Radix routes backdrop click, Escape, and the X button all through
// here. Intercept closes so unsaved input isn't silently discarded.
if (open) { schema.onOpenChange?.(true); return; }
attemptClose(false);
}}
>
<Dialog open={isOpen} onOpenChange={handleDialogOpenChange}>
<MobileDialogContent
showCloseButton={showCloseButton}
onOpenAutoFocus={initialFieldFocus.onOpenAutoFocus}
Expand Down Expand Up @@ -1338,30 +1374,7 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
</div>
)}

{/* Unsaved-changes guard — rendered INSIDE DialogContent so its portal
inherits the Dialog's Radix layer context (focus scope + dismissable
layer) through React. As a sibling of <Dialog> it had no such
context, so the still-open modal swallowed its button clicks and
"Keep editing" did nothing. Nesting lets Radix stack the two modals
correctly: the alert becomes the topmost layer and its buttons work. */}
<AlertDialog open={discardOpen} onOpenChange={setDiscardOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('form.discardTitle')}</AlertDialogTitle>
<AlertDialogDescription>
{t('form.discardMessage')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => { cancelIntentRef.current = false; }}>
{t('form.keepEditing')}
</AlertDialogCancel>
<AlertDialogAction onClick={finalizeClose}>
{t('form.discard')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{discardDialog}
{/* Same nesting rationale as the discard guard above: as a child of
the Dialog content the conflict alert stacks as the topmost Radix
layer, so its buttons receive clicks while the modal stays open. */}
Expand Down
6 changes: 5 additions & 1 deletion ui/packages/plugin-form/src/ObjectForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type { ObjectFormSchema, FormField, FormSchema, DataSource } from '@objec
import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react';
import { pickLocalized, useObjectTranslation, useLocalization, withHomeAmountSource } from '@object-ui/i18n';
import { useRecordInvalidation } from './recordInvalidation';
import { useReportedDirtyChange } from './formDirtyReport';
import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields';
import { isExpressionComputedField } from '@object-ui/core';
import { useIsMobile, toast } from '@object-ui/components';
Expand Down Expand Up @@ -814,8 +815,11 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
// (objectui#10715). Dirtiness is read from the form renderer's existing
// `onDirtyChange` channel; nothing new is declared on any schema.
const readsRecord = !!schema.recordId && schema.mode !== 'create' && !hasInlineFields;
const { refetch: recordRefetch, onDirtyChange: handleDirtyChange, saved: recordSaved } =
const { refetch: recordRefetch, onDirtyChange: onBusDirtyChange, saved: recordSaved } =
useRecordInvalidation(schema.objectName, schema.recordId, readsRecord);
// The same verdict reaches a hosting master-detail form, when one provides a
// reporter (`formDirtyReport.ts`): its close guard counts the header's input.
const handleDirtyChange = useReportedDirtyChange(onBusDirtyChange);
// The `recordRefetch` value the fetch effect last ran for — a run that moved
// it is a re-read IN PLACE and must not enter the loading branch.
const appliedRecordRefetchRef = React.useRef(0);
Expand Down
5 changes: 4 additions & 1 deletion ui/packages/plugin-form/src/TabbedForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
} from './loadFailure';
import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget';
import { useRecordInvalidation } from './recordInvalidation';
import { useReportedDirtyChange } from './formDirtyReport';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { useFormChromeTranslation } from './formChrome';

Expand Down Expand Up @@ -374,8 +375,10 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
// this record, to its object or to `'*'` re-reads the record IN PLACE through
// the effect below while the form is pristine, and is held while it is dirty.
// Dirtiness is the form renderer's `onDirtyChange`, wired below.
const { refetch: recordRefetch, onDirtyChange: handleDirtyChange, saved: recordSaved } =
const { refetch: recordRefetch, onDirtyChange: onBusDirtyChange, saved: recordSaved } =
useRecordInvalidation(schema.objectName, schema.recordId, !!schema.recordId && schema.mode !== 'create');
// Also reported to a hosting master-detail form (`formDirtyReport.ts`).
const handleDirtyChange = useReportedDirtyChange(onBusDirtyChange);

// Fetch initial data for edit/view modes
React.useEffect(() => {
Expand Down
Loading
Loading