Skip to content
Merged
18 changes: 18 additions & 0 deletions .changeset/34605-form-section-nav.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/components': patch
'@object-ui/plugin-form': patch
'@object-ui/i18n': patch
---

feat(plugin-form): a sectioned form shows its sections as a navigation strip; a click scrolls to the section, and a section with errors carries the count

Clause-②: yes (widening — one @object-ui/components export + new @object-ui/i18n locale keys; no FormSchema or spec key)
Metadata-protocol: none

The new export is `FormSectionNavContext` with its `FormSectionNavItem` / `FormSectionNavSink` types; the new locale keys are `form.sectionNav` and `form.sectionNavErrors`. Nothing that worked before is refused.

A create or edit dialog whose form is stacked in sections now shows one entry per visible section between the title and the scrolling body; a full-page sectioned form shows the same strip above its sections, sticky at the top of the page. A click scrolls to the section, unfolding it first when it is collapsed, and the entry of the section in view is highlighted while the form scrolls. When a submit is refused, each entry shows how many fields in its section need fixing, and the count drops as the fields are fixed.

The strip appears only with two or more visible sections. A section hidden by its `visibleWhen` is not listed. A tabbed form keeps its tab strip and gets no section strip. Nothing is configured: no form, section or field key turns it on or off.

For hosts: the `form` renderer reports the section headings it draws, with each section's error count, to a sink provided through `FormSectionNavContext`; each heading row now carries a stable `id` and a `data-form-section` attribute naming its section.
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,10 @@ describe('the Form tab lays out the form the app opens (objectstack#30057)', ()
await waitFor(() => expect(sectionTitles()).toEqual(['Basic info', 'Money details']));

await userEvent.click(screen.getByRole('button', { name: 'Preview' }));
const frame = within(await screen.findByTestId('data-form-preview-frame'));
const previewFrame = await screen.findByTestId('data-form-preview-frame');
// The section navigation (#34605) repeats each section name above the form: read inside the form.
await waitFor(() => expect(previewFrame.querySelector('form')).not.toBeNull());
const frame = within(previewFrame.querySelector('form') as HTMLElement);
expect(await frame.findByText('Basic info')).toBeInTheDocument();
expect(frame.getByText('Money details')).toBeInTheDocument();
expect(frame.queryByText('Designer group')).toBeNull();
Expand Down
5 changes: 5 additions & 0 deletions ui/packages/components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ export type { PageHeaderActionsProps } from './renderers/layout/containers';
// until edited; its edit page hands the changes an AI chat update proposed, and
// the form applies them as unsaved edits, marked, before → after, revertible.
export { SuggestedFieldsContext, SuggestedFieldChangesContext } from './renderers/form/suggested-fields-context';
// The form's section-list slot (objectstack#34605): a sectioned form reports
// the headings it draws, with each section's error count, and the host draws
// the section navigation from them (`@object-ui/plugin-form`).
export { FormSectionNavContext } from './renderers/form/section-nav-context';
export type { FormSectionNavItem, FormSectionNavSink } from './renderers/form/section-nav-context';

// The field-face seam (objectui#13216): the slot `@object-ui/fields` fills
// with its read-face registry when it loads, so `page:header` can draw a
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/**
* 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#34605 — the form renderer's half of the section navigation: the
* section list it reports to a host through `FormSectionNavContext`.
*
* Pinned: each drawn heading row carries a stable DOM id and is reported with
* it, in order; a heading its predicate hides is not reported; a headingless
* section is not reported and its fields count for no heading; a refused
* submit counts each section's errored fields; a tabbed form and a form
* nested in another report nothing; unmounting reports `null`.
*/

import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, cleanup, fireEvent, waitFor } from '@testing-library/react';
import React from 'react';
import { ComponentRegistry } from '@object-ui/core';
// Module-scope import (not `beforeAll`) — objectui#3010/#3021.
import '../../../renderers';
// The renderers reach `react-runtime` through a dynamic import: pay its load at collection.
import '@object-ui/react-runtime';
import { FormSectionNavContext, type FormSectionNavItem } from '../section-nav-context';

afterEach(cleanup);

const cel = (source: string) => ({ dialect: 'cel', source });

const divider = (name: string, label: string | undefined, fields: string[], extra: Record<string, unknown> = {}) => ({
name,
type: 'section-divider',
label,
fields,
...extra,
});

const SECTIONED = [
divider('s_overview', 'Overview', ['name']),
{ name: 'name', label: 'Name', type: 'input' },
divider('s_forecast', 'Forecast', ['forecast', 'quarter']),
{ name: 'forecast', label: 'Forecast Category', type: 'input', required: true },
{ name: 'quarter', label: 'Quarter', type: 'input', required: true },
divider('s_hidden', 'Won Details', ['won_note'], { visibleWhen: cel("record.name == 'won'") }),
{ name: 'won_note', label: 'Won Note', type: 'input' },
divider('s_untitled', undefined, ['loose']),
{ name: 'loose', label: 'Loose', type: 'input', required: true },
];

function renderWithSink(schema: Record<string, unknown>) {
const reports: Array<FormSectionNavItem[] | null> = [];
const sink = vi.fn((items: FormSectionNavItem[] | null) => {
reports.push(items);
});
const Form = ComponentRegistry.get('form')!;
const utils = render(
<FormSectionNavContext.Provider value={sink}>
<Form schema={{ type: 'form', showCancel: false, ...schema }} />
</FormSectionNavContext.Provider>,
);
return { ...utils, reports, sink, last: () => reports[reports.length - 1] };
}

describe('form section list for the host navigation (objectstack#34605)', () => {
it('reports the drawn headings in order, each with the DOM id of its row', async () => {
const { last } = renderWithSink({ fields: SECTIONED });
await waitFor(() => expect(last()).toBeTruthy());

const items = last()!;
expect(items.map((i) => [i.key, i.label])).toEqual([
['s_overview', 'Overview'],
['s_forecast', 'Forecast'],
]);
for (const item of items) {
const row = document.getElementById(item.anchorId);
expect(row).not.toBeNull();
expect(row!.getAttribute('data-form-section')).toBe(item.key);
expect(row!.textContent).toBe(item.label);
expect(item.errorCount).toBe(0);
expect(item.collapsed).toBe(false);
}
});

it('adds a heading when its predicate admits it, by the verdict that draws the row', async () => {
const { last } = renderWithSink({ fields: SECTIONED });
await waitFor(() => expect(last()).toBeTruthy());
fireEvent.change(document.querySelector('input[name="name"]')!, { target: { value: 'won' } });
await waitFor(() => expect(last()!.map((i) => i.key)).toEqual(['s_overview', 's_forecast', 's_hidden']));
});

it('counts the errored fields of each section after a refused submit, and none for a headingless run', async () => {
const { last } = renderWithSink({ fields: SECTIONED });
await waitFor(() => expect(last()).toBeTruthy());

fireEvent.submit(document.querySelector('form')!);

await waitFor(() => expect(last()!.find((i) => i.key === 's_forecast')!.errorCount).toBe(2));
expect(last()!.find((i) => i.key === 's_overview')!.errorCount).toBe(0);
// `loose` holds an error too, but sits under no heading: no entry claims it.
expect(last()!.reduce((n, i) => n + i.errorCount, 0)).toBe(2);

fireEvent.change(document.querySelector('input[name="forecast"]')!, { target: { value: 'Commit' } });
await waitFor(() => expect(last()!.find((i) => i.key === 's_forecast')!.errorCount).toBe(1));
});

it('reports a collapsed section, and its expand unfolds it through the row toggle', async () => {
const onToggle = vi.fn();
const { last } = renderWithSink({
fields: [
divider('s_a', 'A', ['a']),
{ name: 'a', label: 'A field', type: 'input' },
divider('s_b', 'B', ['b'], { collapsible: true, collapsed: true, onToggle }),
{ name: 'b', label: 'B field', type: 'input', hidden: true },
],
});
await waitFor(() => expect(last()).toBeTruthy());
const b = last()!.find((i) => i.key === 's_b')!;
expect(b.collapsed).toBe(true);
b.expand();
expect(onToggle).toHaveBeenCalledTimes(1);
last()!.find((i) => i.key === 's_a')!.expand();
expect(onToggle).toHaveBeenCalledTimes(1);
});

it('reports nothing for a tabbed form', async () => {
const { reports } = renderWithSink({
fields: [
{ name: 'a', label: 'A', type: 'input' },
{ name: 'b', label: 'B', type: 'input' },
],
fieldTabs: [
{ key: 't1', label: 'One', fields: ['a'] },
{ key: 't2', label: 'Two', fields: ['b'] },
],
});
await waitFor(() => expect(document.querySelector('[data-testid="form-tab:t1"]')).not.toBeNull());
expect(reports.every((r) => r === null)).toBe(true);
});

it('keeps a form nested in another out of the host sink', async () => {
const { reports } = renderWithSink({
children: [{ type: 'form', showSubmit: false, showCancel: false, fields: SECTIONED }],
});
await waitFor(() => expect(document.querySelectorAll('form').length).toBe(2));
expect(document.querySelector('[data-form-section="s_forecast"]')).not.toBeNull();
expect(reports.every((r) => r === null)).toBe(true);
});

it('reports null when the form unmounts', async () => {
const { last, unmount } = renderWithSink({ fields: SECTIONED });
await waitFor(() => expect(last()).toBeTruthy());
unmount();
expect(last()).toBeNull();
});
});
Loading
Loading