Skip to content

Commit b1da9f5

Browse files
feat(plugin-form): section navigation for stacked sectioned forms (#34642)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB9h1xhDQ7T3debR2uGogBa2)_ repo:objectstack#3 · os-support-ai · session_01WGufzgTZ8JB6JZFffVhT7R Fixes #34605 Clause-②: yes (widening — one @object-ui/components export + new @object-ui/i18n locale keys; no FormSchema or spec key) Metadata-protocol: none ## 维护者速读 - 改了什么:分组(stacked)表单在对话框里,标题和滚动区之间多了一条分组导航;整页表单在分组上方显示同一条导航(吸顶)。点分组名滚到该分组,折叠的分组先展开;滚动时高亮当前分组;提交被拒后,有错误或必填未填的分组显示数量,填好后数量消失。 - 为什么改:长的分组表单(如 HotCRM 商机,四五个分组)提交失败时用户不知道错在哪一组,只能来回滚动找;导航让分组可直达、错误可定位。 - 风险与回滚:只改 `@object-ui/components`(表单渲染器上报分组列表、分组标题行加稳定 id)和 `@object-ui/plugin-form`(导航组件,接入 ModalForm / ObjectForm),外加两个 i18n 键;不动元数据、契约和服务端,也没有作者配置。只有 2 个及以上可见分组才显示;tab 布局与向导不受影响。回滚即 revert 本 PR。 - 先看:① `ui/packages/plugin-form/src/FormSectionNav.tsx`(导航、滚动高亮、点击跳转);② `ui/packages/components/src/renderers/form/form.tsx` 中 `sectionNavItems` 与 `SectionNavReporter`(哪些分组上报、错误怎么按分组计数);③ `ModalForm.tsx` 与 `ObjectForm.tsx` 的接入点。 - 两分钟验证:在仓根执行 `pnpm --dir ui exec vitest run packages/plugin-form/src/FormSectionNav.test.tsx packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx`,预期 14 个测试全部通过。 - 需要你做的:无,席位落地。注意:Studio 表单视图的「预览」现在也会显示这条导航(预览复用运行时对话框,这是有意的镜像)。 ## What changes `@object-ui/components` (`ui/packages/components/src/renderers/form/`): - New `section-nav-context.ts`: `FormSectionNavContext` (a sink, `null` by default) and the `FormSectionNavItem` / `FormSectionNavSink` types, exported from the package index beside `SuggestedFieldsContext`. - `form.tsx`: each drawn section heading row (`section-divider`) now carries a stable `id` (scoped to the form instance) and `data-form-section="<divider name>"`, with `scroll-mt-2`. When a sink is provided, the renderer reports the headings it actually draws in the stacked layout: key, label, anchor id, collapsed state, an `expand()` that goes through the row's own toggle, and the count of fields in that section holding a react-hook-form error. Membership reads each divider's `fields` claim, falling back to position as `splitAtUntitledRuns` does; a headingless run counts for no entry. A heading its `visibleWhen` hides is not drawn, so not reported. A tabbed form reports nothing. The renderer provides `null` to its own descendants, so a nested form never reports into the host's sink. Unmounting reports `null`. No sink: nothing changes, and `formState.errors` is not subscribed. `@object-ui/plugin-form`: - New `FormSectionNav.tsx`: `useFormSectionNav()` (a sink plus the reported items) and `<FormSectionNav items>`, which renders nothing below two items. Otherwise a `<nav aria-label="Form sections">` strip of buttons; the current entry carries `aria-current="true"`, an entry with errors carries `data-error` and `· N` (with screen-reader text "Fields to fix: N"). Click: expand if collapsed, then `scrollIntoView` the heading row on the next frame; the clicked entry turns current and the scroll spy is held off briefly so it does not flicker through the sections in between. Scroll spy: the nearest scrolling ancestor, rAF-throttled; at the bottom the last entry is current. In a narrow dialog the strip scrolls horizontally and keeps the current entry in view. - `ModalForm.tsx`: the plain (non-subform) dialog provides the sink and draws the strip between `DialogHeader` and the scrolling body (the header drops its bottom border while the strip is drawn). `ObjectForm.tsx` (sectioned simple form): the strip sits above the form, `sticky top-0`. `@object-ui/i18n`: `form.sectionNav` and `form.sectionNavErrors` in all 11 locales. No FormSchema, view or spec key; nothing is configured. ## Why The card: a long sectioned form refuses a submit and the user cannot tell which section holds the problem. The navigation makes each section one click away and marks the sections that need fixing. ## Acceptance notes - Acceptance 1–3 are pinned in `FormSectionNav.test.tsx` (four entries under the dialog title, the third scrolls to the third section's heading row; an empty required field in section two shows `1` after submit; one section draws no strip), and read in a browser (below). - **Footer missing-required hint: not implemented.** Triage comment 6937255202 says the card "carries the footer hint for missing required fields", but the card's acceptance does not include it; the seat agreed to leave it out. It can be a follow-up card. - The Studio form-view **Preview** renders the runtime dialog, so it now shows the strip too. Intended: the preview mirrors the runtime form. - Six existing tests read a section name with an unscoped `getByText`, which now finds two matches (the strip repeats the names). Each is scoped to the form (`within(form)`), test-only; one of them is in `@object-ui/app-shell` (`DataPillar.formViewLayout-30057.test.tsx`), widened by the seat. - Out of scope per the card: the tabbed and wizard layouts. ## Verification Readings against head `3e9036363c` (base `8dd8192c`, merged forward with `origin/main` at `31096af8`). <details><summary>Before / after (browser)</summary> A throwaway probe page served by the console's Vite dev server (not committed) mounting `ModalForm` and `ObjectForm` with an in-memory data source: a five-section create dialog "New Deal" (Overview / Forecast / Qualification / Description / Sales Strategy, the last collapsed; `forecast` required). Chromium 1280×800, driven with Playwright. - Before: not measured in a browser. At base `8dd8192c` no section strip exists in the code; the dialog header sits directly over the scrolling body, and a refused submit marks the field only inside its section. - After: - Five entries under the title; Overview current. - Click Qualification (third) → its heading row lands 8px below the scroller top, Qualification current. - Scrolling by hand: the highlight follows Overview → Forecast → …, and the last entry is current at the bottom. - Click the collapsed Sales Strategy → it unfolds (0 → 4 fields) and is scrolled to. - Submit with `forecast` empty → the Forecast entry shows `· 1`; filling the field clears it. - At 375px width: no page overflow; the strip scrolls sideways and keeps the current entry in view. - Full-page sectioned form: the strip stays at the top while the page scrolls. </details> <details><summary>Tests</summary> Run from the repository root with `ui/` as vitest root, under `scripts/pm/os-verify-lock.sh`. - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-form/ packages/components/src/renderers/form/ packages/i18n/ packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx` → `Test Files 424 passed (424)`, `Tests 5113 passed | 31 skipped (5144)`, lock `VERDICT command-exit 0`. - New: `packages/plugin-form/src/FormSectionNav.test.tsx` (7: acceptance 1–3, `visibleWhen`, collapsed unfold, tabbed none, ObjectForm) and `packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx` (7: report order and DOM ids, predicate-admitted heading, per-section error counts with a headingless run, collapsed + expand, tabbed none, nested form kept out, unmount → null). - Type-check: `@object-ui/components`, `@object-ui/plugin-form`, `@object-ui/i18n` → lock `VERDICT command-exit 0`. - eslint on the touched files → 0 errors. </details> <details><summary>Ablation</summary> Through `node scripts/ablation-replace.mjs`, each restored with an empty `git diff HEAD`: 1. Dropping the drawn-node check (`nodes[j] != null`), so hidden headings are reported → 2 tests red. 2. Dropping the error count → 2 tests red. 3. Providing the sink (not `null`) to the renderer's descendants → the nested-form test red. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` (26 paths vs merge base `31096af83`), then `--ran` → `40 derived famil(ies) accounted for — 40 run, 0 NOT-MEASURED`. `check:test-source-alias` was red on the first run (the new components test reached `@object-ui/react-runtime` through a dynamic import); fixed with a module-top import and re-run green. ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:merge-driver :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:role-word :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` `node scripts/pm/check-governed-merges.mjs --branch HEAD` → `0 of 26 path(s) hit the register`, NOT governed; size +867 / −24. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` untouched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the touched files: 0 errors.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgTZ8JB6JZFffVhT7R <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzgTZ8JB6JZFffVhT7R --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a34eb07 commit b1da9f5

26 files changed

Lines changed: 867 additions & 24 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/components': patch
3+
'@object-ui/plugin-form': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
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
8+
9+
Clause-②: yes (widening — one @object-ui/components export + new @object-ui/i18n locale keys; no FormSchema or spec key)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
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.
15+
16+
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.
17+
18+
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.

‎ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,10 @@ describe('the Form tab lays out the form the app opens (objectstack#30057)', ()
285285
await waitFor(() => expect(sectionTitles()).toEqual(['Basic info', 'Money details']));
286286

287287
await userEvent.click(screen.getByRole('button', { name: 'Preview' }));
288-
const frame = within(await screen.findByTestId('data-form-preview-frame'));
288+
const previewFrame = await screen.findByTestId('data-form-preview-frame');
289+
// The section navigation (#34605) repeats each section name above the form: read inside the form.
290+
await waitFor(() => expect(previewFrame.querySelector('form')).not.toBeNull());
291+
const frame = within(previewFrame.querySelector('form') as HTMLElement);
289292
expect(await frame.findByText('Basic info')).toBeInTheDocument();
290293
expect(frame.getByText('Money details')).toBeInTheDocument();
291294
expect(frame.queryByText('Designer group')).toBeNull();

‎ui/packages/components/src/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ export type { PageHeaderActionsProps } from './renderers/layout/containers';
127127
// until edited; its edit page hands the changes an AI chat update proposed, and
128128
// the form applies them as unsaved edits, marked, before → after, revertible.
129129
export { SuggestedFieldsContext, SuggestedFieldChangesContext } from './renderers/form/suggested-fields-context';
130+
// The form's section-list slot (objectstack#34605): a sectioned form reports
131+
// the headings it draws, with each section's error count, and the host draws
132+
// the section navigation from them (`@object-ui/plugin-form`).
133+
export { FormSectionNavContext } from './renderers/form/section-nav-context';
134+
export type { FormSectionNavItem, FormSectionNavSink } from './renderers/form/section-nav-context';
130135

131136
// The field-face seam (objectui#13216): the slot `@object-ui/fields` fills
132137
// with its read-face registry when it loads, so `page:header` can draw a
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#34605 — the form renderer's half of the section navigation: the
11+
* section list it reports to a host through `FormSectionNavContext`.
12+
*
13+
* Pinned: each drawn heading row carries a stable DOM id and is reported with
14+
* it, in order; a heading its predicate hides is not reported; a headingless
15+
* section is not reported and its fields count for no heading; a refused
16+
* submit counts each section's errored fields; a tabbed form and a form
17+
* nested in another report nothing; unmounting reports `null`.
18+
*/
19+
20+
import { describe, it, expect, vi, afterEach } from 'vitest';
21+
import { render, cleanup, fireEvent, waitFor } from '@testing-library/react';
22+
import React from 'react';
23+
import { ComponentRegistry } from '@object-ui/core';
24+
// Module-scope import (not `beforeAll`) — objectui#3010/#3021.
25+
import '../../../renderers';
26+
// The renderers reach `react-runtime` through a dynamic import: pay its load at collection.
27+
import '@object-ui/react-runtime';
28+
import { FormSectionNavContext, type FormSectionNavItem } from '../section-nav-context';
29+
30+
afterEach(cleanup);
31+
32+
const cel = (source: string) => ({ dialect: 'cel', source });
33+
34+
const divider = (name: string, label: string | undefined, fields: string[], extra: Record<string, unknown> = {}) => ({
35+
name,
36+
type: 'section-divider',
37+
label,
38+
fields,
39+
...extra,
40+
});
41+
42+
const SECTIONED = [
43+
divider('s_overview', 'Overview', ['name']),
44+
{ name: 'name', label: 'Name', type: 'input' },
45+
divider('s_forecast', 'Forecast', ['forecast', 'quarter']),
46+
{ name: 'forecast', label: 'Forecast Category', type: 'input', required: true },
47+
{ name: 'quarter', label: 'Quarter', type: 'input', required: true },
48+
divider('s_hidden', 'Won Details', ['won_note'], { visibleWhen: cel("record.name == 'won'") }),
49+
{ name: 'won_note', label: 'Won Note', type: 'input' },
50+
divider('s_untitled', undefined, ['loose']),
51+
{ name: 'loose', label: 'Loose', type: 'input', required: true },
52+
];
53+
54+
function renderWithSink(schema: Record<string, unknown>) {
55+
const reports: Array<FormSectionNavItem[] | null> = [];
56+
const sink = vi.fn((items: FormSectionNavItem[] | null) => {
57+
reports.push(items);
58+
});
59+
const Form = ComponentRegistry.get('form')!;
60+
const utils = render(
61+
<FormSectionNavContext.Provider value={sink}>
62+
<Form schema={{ type: 'form', showCancel: false, ...schema }} />
63+
</FormSectionNavContext.Provider>,
64+
);
65+
return { ...utils, reports, sink, last: () => reports[reports.length - 1] };
66+
}
67+
68+
describe('form section list for the host navigation (objectstack#34605)', () => {
69+
it('reports the drawn headings in order, each with the DOM id of its row', async () => {
70+
const { last } = renderWithSink({ fields: SECTIONED });
71+
await waitFor(() => expect(last()).toBeTruthy());
72+
73+
const items = last()!;
74+
expect(items.map((i) => [i.key, i.label])).toEqual([
75+
['s_overview', 'Overview'],
76+
['s_forecast', 'Forecast'],
77+
]);
78+
for (const item of items) {
79+
const row = document.getElementById(item.anchorId);
80+
expect(row).not.toBeNull();
81+
expect(row!.getAttribute('data-form-section')).toBe(item.key);
82+
expect(row!.textContent).toBe(item.label);
83+
expect(item.errorCount).toBe(0);
84+
expect(item.collapsed).toBe(false);
85+
}
86+
});
87+
88+
it('adds a heading when its predicate admits it, by the verdict that draws the row', async () => {
89+
const { last } = renderWithSink({ fields: SECTIONED });
90+
await waitFor(() => expect(last()).toBeTruthy());
91+
fireEvent.change(document.querySelector('input[name="name"]')!, { target: { value: 'won' } });
92+
await waitFor(() => expect(last()!.map((i) => i.key)).toEqual(['s_overview', 's_forecast', 's_hidden']));
93+
});
94+
95+
it('counts the errored fields of each section after a refused submit, and none for a headingless run', async () => {
96+
const { last } = renderWithSink({ fields: SECTIONED });
97+
await waitFor(() => expect(last()).toBeTruthy());
98+
99+
fireEvent.submit(document.querySelector('form')!);
100+
101+
await waitFor(() => expect(last()!.find((i) => i.key === 's_forecast')!.errorCount).toBe(2));
102+
expect(last()!.find((i) => i.key === 's_overview')!.errorCount).toBe(0);
103+
// `loose` holds an error too, but sits under no heading: no entry claims it.
104+
expect(last()!.reduce((n, i) => n + i.errorCount, 0)).toBe(2);
105+
106+
fireEvent.change(document.querySelector('input[name="forecast"]')!, { target: { value: 'Commit' } });
107+
await waitFor(() => expect(last()!.find((i) => i.key === 's_forecast')!.errorCount).toBe(1));
108+
});
109+
110+
it('reports a collapsed section, and its expand unfolds it through the row toggle', async () => {
111+
const onToggle = vi.fn();
112+
const { last } = renderWithSink({
113+
fields: [
114+
divider('s_a', 'A', ['a']),
115+
{ name: 'a', label: 'A field', type: 'input' },
116+
divider('s_b', 'B', ['b'], { collapsible: true, collapsed: true, onToggle }),
117+
{ name: 'b', label: 'B field', type: 'input', hidden: true },
118+
],
119+
});
120+
await waitFor(() => expect(last()).toBeTruthy());
121+
const b = last()!.find((i) => i.key === 's_b')!;
122+
expect(b.collapsed).toBe(true);
123+
b.expand();
124+
expect(onToggle).toHaveBeenCalledTimes(1);
125+
last()!.find((i) => i.key === 's_a')!.expand();
126+
expect(onToggle).toHaveBeenCalledTimes(1);
127+
});
128+
129+
it('reports nothing for a tabbed form', async () => {
130+
const { reports } = renderWithSink({
131+
fields: [
132+
{ name: 'a', label: 'A', type: 'input' },
133+
{ name: 'b', label: 'B', type: 'input' },
134+
],
135+
fieldTabs: [
136+
{ key: 't1', label: 'One', fields: ['a'] },
137+
{ key: 't2', label: 'Two', fields: ['b'] },
138+
],
139+
});
140+
await waitFor(() => expect(document.querySelector('[data-testid="form-tab:t1"]')).not.toBeNull());
141+
expect(reports.every((r) => r === null)).toBe(true);
142+
});
143+
144+
it('keeps a form nested in another out of the host sink', async () => {
145+
const { reports } = renderWithSink({
146+
children: [{ type: 'form', showSubmit: false, showCancel: false, fields: SECTIONED }],
147+
});
148+
await waitFor(() => expect(document.querySelectorAll('form').length).toBe(2));
149+
expect(document.querySelector('[data-form-section="s_forecast"]')).not.toBeNull();
150+
expect(reports.every((r) => r === null)).toBe(true);
151+
});
152+
153+
it('reports null when the form unmounts', async () => {
154+
const { last, unmount } = renderWithSink({ fields: SECTIONED });
155+
await waitFor(() => expect(last()).toBeTruthy());
156+
unmount();
157+
expect(last()).toBeNull();
158+
});
159+
});

0 commit comments

Comments
 (0)