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

fix(plugin-form): the master-detail record dialog keeps its Save bar at the dialog's bottom, and the form section navigation follows a scroll that lands inside its click hold

Clause-②: no
Metadata-protocol: none

**Save bar.** A record dialog whose form carries an inline sub-table (`subforms`) drew the master-detail form's Save bar as a sticky box inside the dialog's body scroller. A sticky box stops at its scroller's content edge, so the bar floated above the dialog's bottom by the scroller's bottom padding, and rose further as the body scrolled past the form's own end. The dialog now hands the form a frame of fixed height: the form scrolls its body in a box of its own and draws the bar as the row below it, outside the scrolled content. From the bar's bottom to the dialog's bottom is now the dialog's padding at every scroll position, maximized too — the same distance as the footer of a dialog without a sub-table. The form still owns its Save (ADR-0035 Decision §6), the close guard is unchanged, and the drawer and the record page keep the sticky bar.

**Section navigation.** After a click on a section entry, the navigation holds the highlight for 800 ms so the jump does not light up every section it passes. A scroll that landed inside that hold was never measured, so a refused submit right after a jump left the highlight on the clicked section while the form showed its first error. The navigation now measures once more when the hold ends. At the bottom of a short tail, where several headings are in view, the section the click picked keeps the highlight.
139 changes: 138 additions & 1 deletion ui/packages/plugin-form/src/FormSectionNav.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, within, cleanup } from '@testing-library/react';
import { render, screen, fireEvent, waitFor, within, cleanup, act } from '@testing-library/react';
import React from 'react';
import { registerAllFields } from '@object-ui/fields';
import { ModalForm } from './ModalForm';
import { ObjectForm } from './ObjectForm';
import { FormSectionNav } from './FormSectionNav';

registerAllFields();

Expand Down Expand Up @@ -205,3 +206,139 @@ describe('ObjectForm section navigation (objectstack#34605)', () => {
expect((scrollIntoView.mock.contexts[0] as HTMLElement).getAttribute('data-form-section')).toBe('__section_description');
});
});

/**
* objectstack#34819 — the highlight follows the scroll position, including a
* scroll that lands inside the hold a click starts: a refused submit taking
* the form back to its first error right after a jump left the highlight on
* the section the click had picked.
*
* jsdom does no layout, so the scroller and its headings are a fixture whose
* geometry the test sets: the scroller's box spans 100..700, each heading sits
* at its offset in the content minus `scrollTop`.
*/
describe('FormSectionNav highlight follows the scroll position after a click (objectstack#34819)', () => {
const VIEW_TOP = 100;
const VIEW_HEIGHT = 600;

function mountFixture(offsets: number[], contentHeight: number) {
const keys = offsets.map((_, i) => `s${i}`);
let scrollTop = 0;
const host = render(
<div>
<FormSectionNav
items={keys.map((key, i) => ({
key,
label: `Section ${i}`,
anchorId: `anchor-${key}`,
errorCount: 0,
collapsed: false,
expand: () => {},
}))}
/>
<div data-testid="fixture-scroller" style={{ overflowY: 'auto' }}>
{keys.map((key) => (
<div key={key} id={`anchor-${key}`} />
))}
</div>
</div>,
);
const scroller = screen.getByTestId('fixture-scroller');
const rect = (top: number, height: number) =>
({ top, bottom: top + height, height, left: 0, right: 0, width: 0, x: 0, y: top, toJSON: () => ({}) }) as DOMRect;
scroller.getBoundingClientRect = () => rect(VIEW_TOP, VIEW_HEIGHT);
Object.defineProperty(scroller, 'clientHeight', { configurable: true, get: () => VIEW_HEIGHT });
Object.defineProperty(scroller, 'scrollHeight', { configurable: true, get: () => contentHeight });
Object.defineProperty(scroller, 'scrollTop', { configurable: true, get: () => scrollTop });
keys.forEach((key, i) => {
document.getElementById(`anchor-${key}`)!.getBoundingClientRect = () => rect(VIEW_TOP + offsets[i] - scrollTop, 20);
});
/** Move the scroller and let the spy's frame run. */
const scrollTo = (top: number) => {
scrollTop = top;
act(() => {
fireEvent.scroll(scroller);
vi.advanceTimersToNextFrame();
});
};
const highlighted = () =>
within(host.container.querySelector('[data-testid="form-section-nav"]') as HTMLElement)
.getAllByRole('button')
.find((b) => b.getAttribute('aria-current') === 'true')
?.textContent;
return { scrollTo, highlighted };
}

beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'requestAnimationFrame', 'cancelAnimationFrame'] });
});
afterEach(() => {
vi.useRealTimers();
});

it('follows a scroll back to the top that lands inside the click hold, once the hold ends', () => {
const { scrollTo, highlighted } = mountFixture([0, 600, 1200, 1800], 2400);
fireEvent.click(screen.getByTestId('form-section-nav:s2'));
scrollTo(1200);
expect(highlighted()).toBe('Section 2');

// The refused submit's scroll back to the first error, inside the hold.
scrollTo(0);
expect(highlighted()).toBe('Section 2');

act(() => {
vi.advanceTimersByTime(800);
vi.advanceTimersToNextFrame();
});
expect(highlighted()).toBe('Section 0');
});

it('follows a scroll back to the top that comes after the hold', () => {
const { scrollTo, highlighted } = mountFixture([0, 600, 1200, 1800], 2400);
fireEvent.click(screen.getByTestId('form-section-nav:s2'));
scrollTo(1200);
act(() => {
vi.advanceTimersByTime(800);
vi.advanceTimersToNextFrame();
});
expect(highlighted()).toBe('Section 2');

scrollTo(0);
expect(highlighted()).toBe('Section 0');
});

it('CONTROL: the jump a click starts does not move the highlight through the sections it passes', () => {
const { scrollTo, highlighted } = mountFixture([0, 600, 1200, 1800], 2400);
fireEvent.click(screen.getByTestId('form-section-nav:s2'));
const seen: Array<string | undefined> = [highlighted()];
for (const top of [150, 450, 700, 950, 1200]) {
scrollTo(top);
seen.push(highlighted());
}
act(() => {
vi.advanceTimersByTime(800);
vi.advanceTimersToNextFrame();
});
seen.push(highlighted());
expect(new Set(seen)).toEqual(new Set(['Section 2']));
});

it('CONTROL: at the bottom of a short tail, the section the click picked keeps the highlight when the hold ends', () => {
// Content 1900 high in a 600 box: the deepest scroll is 1300, where the
// third heading (1350) sits in view below the top edge, the fourth too.
const { scrollTo, highlighted } = mountFixture([0, 600, 1350, 1700], 1900);
fireEvent.click(screen.getByTestId('form-section-nav:s2'));
scrollTo(1300);
act(() => {
vi.advanceTimersByTime(800);
vi.advanceTimersToNextFrame();
});
expect(highlighted()).toBe('Section 2');

// Scrolled there by hand, the bottom still reads as the last section.
scrollTo(400);
expect(highlighted()).toBe('Section 0');
scrollTo(1300);
expect(highlighted()).toBe('Section 3');
});
});
24 changes: 20 additions & 4 deletions ui/packages/plugin-form/src/FormSectionNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ const SCROLL_SPY_OFFSET = 24;

/**
* After a click, the jump's own scroll events must not move the highlight
* through the sections it passes on the way.
* through the sections it passes on the way. When the hold ends the highlight
* is measured once more, so a scroll that landed inside the hold — a refused
* submit taking the form back to its first error — is followed too.
*/
const CLICK_HOLD_MS = 800;

Expand Down Expand Up @@ -74,15 +76,21 @@ export function FormSectionNav({ items, className }: FormSectionNavProps) {
const [current, setCurrent] = React.useState<string | undefined>(undefined);
// While set, the jump a click started is under way: see CLICK_HOLD_MS.
const holding = React.useRef<ReturnType<typeof setTimeout> | null>(null);
// The section the last click jumped to, while the form stays at its bottom:
// a short tail shows several headings at once and the click picks one.
const jumpedTo = React.useRef<string | null>(null);
// Re-reads the scroll position; bound by the scroll spy below.
const remeasure = React.useRef<(() => void) | null>(null);
React.useEffect(() => () => {
if (holding.current) clearTimeout(holding.current);
}, []);
const shown = items && items.length >= 2 ? items : null;
const anchorIds = shown ? shown.map((i) => i.anchorId).join('\n') : '';

// Scroll spy: the current section is the last heading at or above the
// scroller's top edge; at the very bottom it is the last section, whose
// heading may never reach the top on a short tail.
// scroller's top edge; at the very bottom it is the section a click jumped
// to when its heading is in view, else the last section, whose heading may
// never reach the top on a short tail.
React.useEffect(() => {
if (!anchorIds) return;
const ids = anchorIds.split('\n');
Expand All @@ -101,8 +109,12 @@ export function FormSectionNav({ items, className }: FormSectionNavProps) {
: window.scrollY > 0 && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2;
let found = ids[0];
if (atBottom) {
found = ids[ids.length - 1];
const clicked = jumpedTo.current ? document.getElementById(jumpedTo.current) : null;
const viewBottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight;
const clickedTop = clicked ? clicked.getBoundingClientRect().top : NaN;
found = clickedTop >= top && clickedTop < viewBottom ? jumpedTo.current! : ids[ids.length - 1];
} else {
jumpedTo.current = null;
for (const id of ids) {
const el = document.getElementById(id);
if (el && el.getBoundingClientRect().top - top <= SCROLL_SPY_OFFSET) found = id;
Expand All @@ -113,8 +125,10 @@ export function FormSectionNav({ items, className }: FormSectionNavProps) {
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
remeasure.current = onScroll;
target.addEventListener('scroll', onScroll, { passive: true });
return () => {
remeasure.current = null;
target.removeEventListener('scroll', onScroll);
if (frame) cancelAnimationFrame(frame);
};
Expand Down Expand Up @@ -145,7 +159,9 @@ export function FormSectionNav({ items, className }: FormSectionNavProps) {
if (holding.current) clearTimeout(holding.current);
holding.current = setTimeout(() => {
holding.current = null;
remeasure.current?.();
}, CLICK_HOLD_MS);
jumpedTo.current = item.anchorId;
setCurrent(item.key);
const reveal = () =>
document.getElementById(item.anchorId)?.scrollIntoView?.({ block: 'start', behavior: 'smooth' });
Expand Down
35 changes: 30 additions & 5 deletions ui/packages/plugin-form/src/MasterDetailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { ObjectForm } from './ObjectForm';
import { applyColumnPermissions } from './fieldWriteGate';
import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate';
import { FormDirtyReportContext } from './formDirtyReport';
import { MasterDetailFrameContext } from './masterDetailFrame';
import { useFormChromeTranslation } from './formChrome';
import {
buildMasterDetailBatch,
Expand Down Expand Up @@ -1780,6 +1781,9 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
* advances or empties the lines, so a saved document reads as pristine.
*/
const reportUnsaved = useContext(FormDirtyReportContext);
// A host frame of fixed height (the record dialog, objectstack#34819): the
// body scrolls in its own box and the bar sits below it. See `masterDetailFrame`.
const frame = useContext(MasterDetailFrameContext);
const [headerDirty, setHeaderDirty] = useState(false);
const [rowEditorDirty, setRowEditorDirty] = useState(false);
const linesDirty = useMemo(
Expand Down Expand Up @@ -2179,9 +2183,8 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({

useEffect(() => () => { if (saveGuardTimer.current) clearTimeout(saveGuardTimer.current); }, []);

return (
<UploadGateProvider gate={uploadGate}>
<div className={cn('space-y-6', className, schema.className)}>
const body = (
<>
{/* 1) Header fields on top */}
<div ref={formHostRef}>
<FormDirtyReportContext.Provider value={setHeaderDirty}>
Expand Down Expand Up @@ -2270,6 +2273,19 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
</CardContent>
</Card>
)}
</>
);

return (
<UploadGateProvider gate={uploadGate}>
<div className={cn(frame ? 'flex min-h-0 flex-1 flex-col' : 'space-y-6', className, schema.className)}>
{frame ? (
<div className={cn('min-h-0 flex-1 overflow-y-auto space-y-6', frame.bodyClassName)} data-testid="md-form-body">
{body}
</div>
) : (
body
)}

{/* Single action bar at the bottom — suppressed when the host opts out
(e.g. the Studio screen-preview, which must never persist).
Expand All @@ -2281,10 +2297,19 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
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). */}
host (ADR-0035 Decision §6: the form owns its Save).
In a host frame of fixed height (objectstack#34819) the bar is not
sticky: it is the flex row below the body's own scroller, outside
the scrolled content, so nothing the body holds can lift it off the
frame's bottom edge. */}
{schema.showSubmit !== false && (
<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"
className={cn(
'border-t border-border bg-background',
frame
? cn('shrink-0', frame.actionsClassName)
: 'sticky bottom-0 z-10 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
Expand Down
26 changes: 22 additions & 4 deletions ui/packages/plugin-form/src/ModalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
} from '@object-ui/components';
import { Loader2, Maximize2, Minimize2 } from 'lucide-react';
import { MasterDetailForm } from './MasterDetailForm';
import { MasterDetailFrameContext, type MasterDetailFrame } from './masterDetailFrame';
import { SchemaRenderer, useSafeFieldLabel, usePreviewMode } from '@object-ui/react';
import { createSafeTranslation, useLocalization } from '@object-ui/i18n';
import { buildSectionFields as buildSectionFieldsShared } from './sectionFields';
Expand Down Expand Up @@ -1296,8 +1297,13 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
);

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
// The master-detail form owns its Save bar (objectstack#34599, ADR-0035
// Decision §6). This dialog hands it a frame of fixed height — the region
// between the header and the dialog's bottom — through
// `MasterDetailFrameContext`, so the form scrolls its body in a box of its
// own and draws the bar below it, at the dialog's bottom at every scroll
// position, with the gutters the flat arm's body and footer use
// (objectstack#34819). 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.
Expand All @@ -1320,8 +1326,9 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
)}
</DialogHeader>
)}
<div className="@container flex-1 overflow-y-auto px-4 sm:px-6 py-4">
<Suspense fallback={<ModalFormBodyPending />}>
<div className="flex min-h-0 flex-1 flex-col" data-testid="modal-form-md-frame">
<Suspense fallback={<div className="px-4 sm:px-6 py-4"><ModalFormBodyPending /></div>}>
<MasterDetailFrameContext.Provider value={MODAL_MASTER_DETAIL_FRAME}>
<FormDirtyReportContext.Provider value={setIsDirty}>
<MasterDetailForm
schema={{
Expand Down Expand Up @@ -1359,6 +1366,7 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
dataSource={dataSource}
/>
</FormDirtyReportContext.Provider>
</MasterDetailFrameContext.Provider>
</Suspense>
</div>
{discardDialog}
Expand Down Expand Up @@ -1467,6 +1475,16 @@ const ModalFormBody: React.FC<ModalFormProps> = ({
);
};

/**
* The frame the master-detail arm hands its form (objectstack#34819): the
* body scroller takes the flat arm's body gutters and container query, the
* action bar the flat arm's footer padding.
*/
const MODAL_MASTER_DETAIL_FRAME: MasterDetailFrame = {
bodyClassName: '@container px-4 sm:px-6 py-4',
actionsClassName: 'px-4 sm:px-6 py-3',
};

/**
* What the dialog's body shows while a field widget's code loads
* (objectui#12559).
Expand Down
Loading
Loading