diff --git a/.changeset/34605-form-section-nav.md b/.changeset/34605-form-section-nav.md new file mode 100644 index 00000000000..572b4c6b533 --- /dev/null +++ b/.changeset/34605-form-section-nav.md @@ -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. diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx index 72246212a87..79e8be760ff 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx @@ -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(); diff --git a/ui/packages/components/src/index.ts b/ui/packages/components/src/index.ts index da6d98ebf00..43a185eb2f0 100644 --- a/ui/packages/components/src/index.ts +++ b/ui/packages/components/src/index.ts @@ -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 diff --git a/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx new file mode 100644 index 00000000000..53c69bff6e7 --- /dev/null +++ b/ui/packages/components/src/renderers/form/__tests__/form-section-nav-34605.test.tsx @@ -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 = {}) => ({ + 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) { + const reports: Array = []; + const sink = vi.fn((items: FormSectionNavItem[] | null) => { + reports.push(items); + }); + const Form = ComponentRegistry.get('form')!; + const utils = render( + +
+ , + ); + 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(); + }); +}); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index a8e7a302110..95e447bac1c 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -48,6 +48,7 @@ import type { RendererHostProps } from '../../lib/renderer-host-props'; import { currencyCodeFieldNames, useUsedCurrencyCodes, withUsedCurrencyCodes } from './usedCurrencyCodes'; import { usePatchingUpdateActions } from './actionRequirements'; import { SuggestedFieldChangesContext, SuggestedFieldsContext } from './suggested-fields-context'; +import { FormSectionNavContext, type FormSectionNavItem, type FormSectionNavSink } from './section-nav-context'; /** * A submit refusal as the banner and the toast draw it: one string as itself, @@ -126,7 +127,9 @@ function sectionGateVisible( /** Inline section header rendered as a virtual field inside a flat SchemaRenderer field list. * Collapsibility is controlled externally (collapsed state lives in DrawerForm). */ -function SectionDivider({ label, description, collapsible, collapsed, onToggle, className }: { +function SectionDivider({ sectionKey, anchorId, label, description, collapsible, collapsed, onToggle, className }: { + sectionKey?: string; + anchorId?: string; label?: string; description?: string; collapsible?: boolean; @@ -153,7 +156,7 @@ function SectionDivider({ label, description, collapsible, collapsed, onToggle, return (
{label && (
@@ -263,6 +271,67 @@ function splitAtUntitledRuns(fields: FormFieldConfig[]): FormFieldConfig[][] { return blocks; } +/** + * The section each field of a stacked sectioned form sits under, for the + * section navigation's error counts (objectstack#34605): field name → the name + * of the divider row whose heading it is drawn under. + * + * The same reading as {@link splitAtUntitledRuns}: a field belongs to the + * heading above it when that heading's membership claim names it, or when the + * heading carries no claim; a field the claim does not name, and a row that + * draws no heading, end the heading's run. + */ +function sectionKeyByFieldName(fields: FormFieldConfig[]): Map { + const out = new Map(); + let heading: { key: string; claim: ReadonlySet | 'all' } | null = null; + for (const f of fields) { + if (f?.type === 'section-divider') { + if (!dividerDrawsRow(f.label, f.description) || typeof f.name !== 'string') { + heading = null; + continue; + } + const claim = f.fields; + heading = { key: f.name, claim: Array.isArray(claim) && claim.length > 0 ? new Set(claim) : 'all' }; + continue; + } + if (!heading || typeof f?.name !== 'string') continue; + if (heading.claim === 'all' || heading.claim.has(f.name)) out.set(f.name, heading.key); + else heading = null; + } + return out; +} + +/** + * The DOM `id` of a section heading row: unique per form instance (two forms + * can be open at once, a drawer under a dialog), and a valid `id` whatever the + * section name holds — a section keyed by its label can carry spaces. + */ +function sectionAnchorId(formInstanceId: string, sectionKey: string): string { + return `form-section-${formInstanceId.replace(/[^A-Za-z0-9_-]/g, '')}-${encodeURIComponent(sectionKey).replace(/%/g, '_')}`; +} + +/** + * Hands the drawn section list to the host's sink (objectstack#34605) when it + * changes, and `null` when the form stops drawing sections or unmounts. A + * component of its own so the report is an effect after commit, not a write + * during render, and so the form's hook order never depends on its layout. + * The list is compared by what a host draws; `expand` reads the latest row + * state through the form's ref, so an older list never acts on a stale one. + */ +function SectionNavReporter({ sink, items }: { sink: FormSectionNavSink; items: FormSectionNavItem[] | null }) { + const signature = items + ? JSON.stringify(items.map((i) => [i.key, i.label, i.anchorId, i.errorCount, i.collapsed])) + : ''; + React.useEffect(() => { + sink(items); + // `signature` stands for `items`: a new array of the same sections must + // not re-report. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sink, signature]); + React.useEffect(() => () => sink(null), [sink]); + return null; +} + /** * Pane sizes in the JSON protocol are percentages (spec `splitSize`). react-resizable-panels * documents a NUMERIC size as pixels and an unsuffixed STRING as a percentage — @@ -1975,6 +2044,14 @@ ComponentRegistry.register('form', */ const formInstanceId = React.useId(); const outcomeToastId = `form-outcome:${formInstanceId}`; + // The host's section-list sink (objectstack#34605), and per drawn section + // row its latest collapse state and toggle — republished by + // `renderFormField` on every render, like `requiredMessages` below, so a + // navigation click always acts on the row as it now stands. A ref: nothing + // renders off it. + const sectionNavSink = React.useContext(FormSectionNavContext); + const sectionRowsRef = React.useRef void }> | undefined>(undefined); + const sectionRows = (sectionRowsRef.current ??= new Map void }>()); /** * A refused submit is said ONCE, by the banner above the fields * (objectstack-ai/objectstack#27520). The toast that used to repeat it word @@ -2289,6 +2366,13 @@ ComponentRegistry.register('form', return hiddenNames; }, [fields, ruleRecord, previousRecord, isCreateForm, predicateScope]); + // Field name → the section heading it is drawn under, for the section + // navigation's per-section error count (objectstack#34605). + const sectionKeyByField = React.useMemo( + () => sectionKeyByFieldName(fields as FormFieldConfig[]), + [fields], + ); + // --- Tabbed field layout (#2959) --------------------------------------- // `fieldTabs` spreads THIS form's fields across tab panels. Crucially there // is still exactly ONE / react-hook-form instance: the panels are @@ -3670,9 +3754,12 @@ ComponentRegistry.register('form', // so all fields share the same form instance (enables cross-section conditions). if (type === 'section-divider') { const fp = fieldProps as any; + sectionRows.set(name, { collapsed: !!fp.collapsible && !!fp.collapsed, toggle: fp.onToggle }); return ( { + const renderFieldBlocks = ( + list: FormFieldConfig[], + drawnHeadings?: Array<{ key: string; label: string }>, + ): React.ReactNode => { let drawnAbove = false; return splitAtUntitledRuns(list).map((block, index) => { const nodes = block.map(renderFormField); + // The headings this render actually drew, in order (objectstack#34605): + // the section navigation lists exactly these, so a section a predicate + // hides is absent from it by the same verdict that hid its row. + block.forEach((f, j) => { + if (f?.type === 'section-divider' && nodes[j] != null && f.label && typeof f.name === 'string') { + drawnHeadings?.push({ key: f.name, label: String(f.label) }); + } + }); const draws = block.some( (f, j) => nodes[j] != null && @@ -4334,6 +4432,39 @@ ComponentRegistry.register('form', }); }; + // The stacked (untabbed, unpaned) field list, drawn here rather than inline + // below so the headings it draws are known before the tree is returned — + // the section navigation is built from them (objectstack#34605). A tabbed + // or paned form has its own group switcher, and reports no sections. + const drawsStackedFields = !schema.children && !fieldTabGroups && !fieldPaneGroups; + const drawnHeadings: Array<{ key: string; label: string }> = []; + const stackedFieldBlocks = drawsStackedFields + ? renderFieldBlocks(fields as FormFieldConfig[], drawnHeadings) + : null; + let sectionNavItems: FormSectionNavItem[] | null = null; + if (sectionNavSink && drawnHeadings.length > 0) { + // Read only when a host listens: reading `formState.errors` subscribes + // this component to every error change, which keeps the counts live — + // a fixed field drops out of its section's count as it revalidates. + const errors = (form.formState.errors ?? {}) as Record; + const counts = new Map(); + for (const fieldName of Object.keys(errors)) { + const key = sectionKeyByField.get(fieldName); + if (key) counts.set(key, (counts.get(key) ?? 0) + 1); + } + sectionNavItems = drawnHeadings.map(({ key, label: headingLabel }) => ({ + key, + label: headingLabel, + anchorId: sectionAnchorId(formInstanceId, key), + errorCount: counts.get(key) ?? 0, + collapsed: sectionRows.get(key)?.collapsed ?? false, + expand: () => { + const row = sectionRows.get(key); + if (row?.collapsed) row.toggle?.(); + }, + })); + } + // Extract designer-related props and conflicting handlers const { 'data-obj-id': dataObjId, @@ -4403,6 +4534,10 @@ ComponentRegistry.register('form', } = props; return ( + // A form nested inside this one (a sub-form widget) reports into no + // sink: the host's navigation belongs to the outermost form. + + {sectionNavSink && } + ); }, { diff --git a/ui/packages/components/src/renderers/form/section-nav-context.ts b/ui/packages/components/src/renderers/form/section-nav-context.ts new file mode 100644 index 00000000000..8a14ce31696 --- /dev/null +++ b/ui/packages/components/src/renderers/form/section-nav-context.ts @@ -0,0 +1,51 @@ +/** + * 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. + */ + +import React from 'react'; + +/** + * One section heading of a sectioned form, as the form renderer drew it + * (objectstack#34605). The renderer reports the list; a host draws the + * section navigation from it. + */ +export interface FormSectionNavItem { + /** The section's divider row name — stable for the life of the form. */ + key: string; + /** The heading text the row draws. */ + label: string; + /** The `id` of the heading row in the DOM, the scroll target. */ + anchorId: string; + /** + * Fields of this section that hold a validation error right now — a client + * rule, a required field left empty at submit, or a field the server + * rejected. `0` when none. + */ + errorCount: number; + /** The section's fields are folded away behind its heading. */ + collapsed: boolean; + /** Unfold the section; a no-op when it is not collapsed. */ + expand: () => void; +} + +/** + * The section list sink a host provides (objectstack#34605). + * + * A `form` renderer below it reports the section headings it draws — only the + * visible ones, in order, with each section's error count — every time that + * list changes, and `null` when it draws no stacked sections (a flat form, a + * tabbed or paned layout) or unmounts. The renderer provides `null` to its own + * descendants, so a form nested inside another never reports into the outer + * form's sink. + * + * It is a host slot, never metadata: no form or section key says it, so every + * sectioned form under a host that mounts it gets the navigation, with nothing + * for an author to configure. `null` (the default) means nobody is listening. + */ +export type FormSectionNavSink = (items: FormSectionNavItem[] | null) => void; + +export const FormSectionNavContext = React.createContext(null); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 2d2d113e92c..c610c2b067a 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -203,6 +203,8 @@ const ar = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "املأ حقول النموذج ثم أرسل أو ألغِ.", + sectionNav: "أقسام النموذج", + sectionNavErrors: "حقول تحتاج إلى تصحيح: {{number}}", deniedDescription: "ليس لديك إذن لتعديل هذا الحقل.", serverDefaultHint: "يُعيَّن تلقائيًا عند الحفظ.", requiredForAction: "مطلوب لتنفيذ «{{action}}».", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 5870df57cd1..28bf01a9528 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -189,6 +189,8 @@ const de = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "Füllen Sie die Formularfelder aus und senden Sie ab oder brechen Sie ab.", + sectionNav: "Formularabschnitte", + sectionNavErrors: "Zu korrigierende Felder: {{number}}", deniedDescription: "Sie haben keinen Bearbeitungszugriff auf dieses Feld.", serverDefaultHint: "Wird beim Speichern automatisch gesetzt.", requiredForAction: "Erforderlich, um „{{action}}“ auszuführen.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 60e550ffb84..c82c9b3a02a 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -274,6 +274,11 @@ const en = { // only displace it by authoring a `description`, which makes a VISIBLE // subtitle appear on every form — so the fallback has to come from here. dialogDescriptionFallback: 'Complete the form fields, then submit or cancel.', + // The form section navigation (objectstack#34605): its accessible name, + // and the screen-reader text of a section's error count, which is drawn + // as a bare number beside the section name. + sectionNav: 'Form sections', + sectionNavErrors: 'Fields to fix: {{number}}', // The hint under a field the caller may read but not write, shown when the // field declares no description of its own (objectui#11071). deniedDescription: 'You do not have edit access to this field.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ad8f346d6d7..a003750aa1c 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -196,6 +196,8 @@ const es = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "Complete los campos del formulario y luego envíe o cancele.", + sectionNav: "Secciones del formulario", + sectionNavErrors: "Campos por corregir: {{number}}", deniedDescription: "No tienes permiso para editar este campo.", serverDefaultHint: "Se establece automáticamente al guardar.", requiredForAction: "Obligatorio para ejecutar «{{action}}».", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 915d2eaee8d..aa3d23953e5 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -191,6 +191,8 @@ const fr = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "Remplissez les champs du formulaire, puis envoyez ou annulez.", + sectionNav: "Sections du formulaire", + sectionNavErrors: "Champs à corriger : {{number}}", deniedDescription: "Vous n'avez pas l'autorisation de modifier ce champ.", serverDefaultHint: "Défini automatiquement lors de l'enregistrement.", requiredForAction: "Requis pour exécuter « {{action}} ».", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index df84bd31f8a..2ee0ed9071e 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -189,6 +189,8 @@ const ja = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "フォームの項目を入力してから、送信またはキャンセルしてください。", + sectionNav: "フォームのセクション", + sectionNavErrors: "修正が必要な項目: {{number}}", deniedDescription: "このフィールドを編集する権限がありません。", serverDefaultHint: "保存時に自動で設定されます。", requiredForAction: "「{{action}}」の実行に必須です。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7d88810356d..872bf783759 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -189,6 +189,8 @@ const ko = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "양식 필드를 작성한 다음 제출하거나 취소하세요.", + sectionNav: "양식 섹션", + sectionNavErrors: "수정할 필드: {{number}}", deniedDescription: "이 필드를 편집할 권한이 없습니다.", serverDefaultHint: "저장 시 자동으로 설정됩니다.", requiredForAction: "'{{action}}' 실행에 필요합니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index d17bad55541..57fef11f347 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -191,6 +191,8 @@ const pt = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "Preencha os campos do formulário e depois envie ou cancele.", + sectionNav: "Seções do formulário", + sectionNavErrors: "Campos a corrigir: {{number}}", deniedDescription: "Você não tem permissão para editar este campo.", serverDefaultHint: "Definido automaticamente ao salvar.", requiredForAction: "Obrigatório para executar «{{action}}».", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0b2bfc34501..adcea6b57ba 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -196,6 +196,8 @@ const ru = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: "Заполните поля формы, затем отправьте или отмените.", + sectionNav: "Разделы формы", + sectionNavErrors: "Поля для исправления: {{number}}", deniedDescription: "У вас нет прав на редактирование этого поля.", serverDefaultHint: "Задаётся автоматически при сохранении.", requiredForAction: "Обязательно для выполнения «{{action}}».", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 62e7158f8b9..02061057df9 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -201,6 +201,8 @@ const zh = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: '填写表单字段,然后提交或取消。', + sectionNav: '表单分组', + sectionNavErrors: '待修正字段:{{number}}', deniedDescription: '您没有此字段的编辑权限。', serverDefaultHint: '保存时自动设置。', requiredForAction: '执行「{{action}}」时必填。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4c9661845fd..fca15dd5136 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -201,6 +201,8 @@ const zhHant = { // objectui#4024 — the create/edit dialog's `sr-only` accessible // description, used when the form declares no `description` of its own. dialogDescriptionFallback: '填寫表單欄位,然後提交或取消。', + sectionNav: '表單分組', + sectionNavErrors: '待修正欄位:{{number}}', deniedDescription: '您沒有此欄位的編輯權限。', serverDefaultHint: '儲存時自動設定。', requiredForAction: '執行「{{action}}」時必填。', diff --git a/ui/packages/plugin-form/src/FormSectionNav.test.tsx b/ui/packages/plugin-form/src/FormSectionNav.test.tsx new file mode 100644 index 00000000000..575926451ac --- /dev/null +++ b/ui/packages/plugin-form/src/FormSectionNav.test.tsx @@ -0,0 +1,207 @@ +/** + * 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 section navigation of a stacked sectioned form, in + * its two hosts: the record dialog (`ModalForm`, between the header and the + * scrolling body) and the full-page form (`ObjectForm`, above the sections). + * + * The card's acceptance, row by row: + * 1. a four-section form draws four entries under the dialog title, and the + * third scrolls to the third section; + * 2. a required field left empty in section two, submitted, puts "1" on + * section two's entry; + * 3. a form with one section draws no navigation. + * Plus the card's rules: a section its `visibleWhen` hides is not listed, a + * collapsed section unfolds before the jump, and a tabbed form gets none. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, within, cleanup } from '@testing-library/react'; +import React from 'react'; +import { registerAllFields } from '@object-ui/fields'; +import { ModalForm } from './ModalForm'; +import { ObjectForm } from './ObjectForm'; + +registerAllFields(); + +const ds: any = { + getObjectSchema: vi.fn().mockResolvedValue({ + name: 'deal', + fields: { + name: { type: 'text', label: 'Deal Name' }, + amount: { type: 'number', label: 'Amount' }, + forecast: { type: 'text', label: 'Forecast Category', required: true }, + quarter: { type: 'text', label: 'Quarter' }, + budget: { type: 'text', label: 'Budget' }, + notes: { type: 'textarea', label: 'Notes' }, + stage: { type: 'text', label: 'Stage' }, + }, + }), + create: vi.fn().mockResolvedValue({ id: '1' }), + update: vi.fn(), + findOne: vi.fn(), +}; + +const FOUR_SECTIONS = [ + { name: 'overview', label: 'Overview', fields: ['name', 'amount'] }, + { name: 'forecast', label: 'Forecast', fields: ['forecast', 'quarter'] }, + { name: 'qualification', label: 'Qualification', fields: ['budget'] }, + { name: 'description', label: 'Description', fields: ['notes'] }, +]; + +const scrollIntoView = vi.fn(); +const originalScrollIntoView = Element.prototype.scrollIntoView; + +beforeEach(() => { + vi.clearAllMocks(); + Element.prototype.scrollIntoView = scrollIntoView; +}); +afterEach(() => { + Element.prototype.scrollIntoView = originalScrollIntoView; + cleanup(); +}); + +const renderModal = (extra: Record = {}) => + render( + , + ); + +const nav = () => screen.queryByTestId('form-section-nav'); + +// A section's entry and heading row are keyed by its divider row's name, +// which `projectSectionDivider` derives from the section key. + +describe('ModalForm section navigation (objectstack#34605)', () => { + it('draws one entry per section between the title and the body, and a click scrolls to that section', async () => { + renderModal(); + await waitFor(() => expect(nav()).not.toBeNull()); + + const entries = within(nav()!).getAllByRole('button'); + expect(entries.map((b) => b.textContent)).toEqual(['Overview', 'Forecast', 'Qualification', 'Description']); + // Outside the form and above its scroller: it stays in view while the body scrolls. + expect(nav()!.closest('form')).toBeNull(); + const form = document.querySelector('form')!; + expect(nav()!.compareDocumentPosition(form) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // The first section is current before anything scrolls. + expect(entries[0].getAttribute('aria-current')).toBe('true'); + + fireEvent.click(entries[2]); + + // The scroll target is the third section's heading row — its stable DOM id. + expect(scrollIntoView).toHaveBeenCalledTimes(1); + const target = scrollIntoView.mock.contexts[0] as HTMLElement; + expect(target.getAttribute('data-form-section')).toBe('__section_qualification'); + expect(target.textContent).toContain('Qualification'); + expect(within(nav()!).getAllByRole('button')[2].getAttribute('aria-current')).toBe('true'); + }); + + it('marks a section with a required field left empty once a submit is refused, and clears the mark when it is filled', async () => { + renderModal(); + await waitFor(() => expect(nav()).not.toBeNull()); + expect(screen.queryByTestId('form-section-nav-count:__section_forecast')).toBeNull(); + + fireEvent.click(screen.getByText('Create')); + + await waitFor(() => + expect(screen.getByTestId('form-section-nav:__section_forecast').getAttribute('data-error')).toBe('true'), + ); + const count = screen.getByTestId('form-section-nav-count:__section_forecast'); + expect(count.querySelector('[aria-hidden="true"]')!.textContent).toBe('· 1'); + expect(screen.getByTestId('form-section-nav:__section_overview').hasAttribute('data-error')).toBe(false); + expect(ds.create).not.toHaveBeenCalled(); + + fireEvent.change(document.querySelector('input[name="forecast"]')!, { target: { value: 'Commit' } }); + await waitFor(() => expect(screen.queryByTestId('form-section-nav-count:__section_forecast')).toBeNull()); + }); + + it('draws no navigation for a form with one section', async () => { + renderModal({ sections: [FOUR_SECTIONS[0]] }); + await waitFor(() => expect(document.body.textContent).toContain('Deal Name')); + expect(nav()).toBeNull(); + }); + + it('leaves out a section its visibleWhen hides, and lists it again when the predicate admits it', async () => { + renderModal({ + sections: [ + FOUR_SECTIONS[0], + { name: 'closing', label: 'Closing', fields: ['stage'] }, + { name: 'won', label: 'Won Details', fields: ['notes'], visibleWhen: "record.stage == 'won'" }, + ], + }); + await waitFor(() => expect(nav()).not.toBeNull()); + expect(within(nav()!).getAllByRole('button').map((b) => b.textContent)).toEqual(['Overview', 'Closing']); + + fireEvent.change(document.querySelector('input[name="stage"]')!, { target: { value: 'won' } }); + await waitFor(() => + expect(within(nav()!).getAllByRole('button').map((b) => b.textContent)).toEqual([ + 'Overview', + 'Closing', + 'Won Details', + ]), + ); + }); + + it('unfolds a collapsed section before scrolling to it', async () => { + renderModal({ + sections: [ + FOUR_SECTIONS[0], + { name: 'strategy', label: 'Strategy', fields: ['notes'], collapsible: true, collapsed: true }, + ], + }); + await waitFor(() => expect(nav()).not.toBeNull()); + expect(document.querySelector('textarea[name="notes"]')).toBeNull(); + + fireEvent.click(screen.getByTestId('form-section-nav:__section_strategy')); + + await waitFor(() => expect(document.querySelector('textarea[name="notes"]')).not.toBeNull()); + await waitFor(() => expect(scrollIntoView).toHaveBeenCalled()); + expect((scrollIntoView.mock.contexts[0] as HTMLElement).getAttribute('data-form-section')).toBe('__section_strategy'); + }); + + it('draws no navigation for a tabbed dialog, whose tab strip already switches groups', async () => { + renderModal({ contentLayout: 'tabbed' }); + await waitFor(() => expect(screen.getByTestId('form-tab:forecast')).toBeTruthy()); + expect(nav()).toBeNull(); + }); +}); + +describe('ObjectForm section navigation (objectstack#34605)', () => { + it('draws the navigation above a full-page sectioned form', async () => { + render( + , + ); + await waitFor(() => expect(nav()).not.toBeNull()); + expect(within(nav()!).getAllByRole('button').map((b) => b.textContent)).toEqual([ + 'Overview', + 'Forecast', + 'Qualification', + 'Description', + ]); + const form = document.querySelector('form')!; + expect(nav()!.compareDocumentPosition(form) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + + fireEvent.click(screen.getByTestId('form-section-nav:__section_description')); + expect((scrollIntoView.mock.contexts[0] as HTMLElement).getAttribute('data-form-section')).toBe('__section_description'); + }); +}); diff --git a/ui/packages/plugin-form/src/FormSectionNav.tsx b/ui/packages/plugin-form/src/FormSectionNav.tsx new file mode 100644 index 00000000000..e400d4517bb --- /dev/null +++ b/ui/packages/plugin-form/src/FormSectionNav.tsx @@ -0,0 +1,198 @@ +/** + * 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. + */ + +import React from 'react'; +import { cn, type FormSectionNavItem, type FormSectionNavSink } from '@object-ui/components'; +import { createSafeTranslation } from '@object-ui/i18n'; + +// Must stay byte-identical to the `en` pack values — `pnpm check:i18n-keys` +// compares this table against them. +const useSectionNavTranslation = createSafeTranslation( + { + 'form.sectionNav': 'Form sections', + 'form.sectionNavErrors': 'Fields to fix: {{number}}', + }, + 'form.sectionNav', +); + +/** + * The host half of the form section navigation (objectstack#34605): a stable + * sink to provide through `FormSectionNavContext`, and the section list the + * form below it last reported. `items` is `null` until a sectioned form + * reports, and again when it draws no stacked sections. + */ +export function useFormSectionNav(): { sink: FormSectionNavSink; items: FormSectionNavItem[] | null } { + const [items, setItems] = React.useState(null); + // `setItems` is stable for the life of the host, so the sink never re-keys + // the form's report. + return { sink: setItems, items }; +} + +/** How far below the scroller's top edge a heading still counts as the current section. */ +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. + */ +const CLICK_HOLD_MS = 800; + +/** The nearest ancestor that scrolls vertically, or `null` for the window. */ +function scrollParentOf(el: HTMLElement | null): HTMLElement | null { + for (let node = el?.parentElement ?? null; node; node = node.parentElement) { + const overflowY = getComputedStyle(node).overflowY; + if (overflowY === 'auto' || overflowY === 'scroll') return node; + } + return null; +} + +export interface FormSectionNavProps { + /** The sections the form reported — `useFormSectionNav().items`. */ + items: FormSectionNavItem[] | null; + className?: string; +} + +/** + * The section navigation of a stacked sectioned form (objectstack#34605). + * + * One entry per visible section heading, in form order. A click scrolls to the + * section — unfolding it first when it is collapsed — and the entry of the + * section in view is highlighted as the form scrolls. An entry carries the + * number of fields in its section that hold a validation error, so a refused + * submit shows which sections need attention. + * + * Drawn only with two or more visible sections; a host never configures it, + * and a tabbed or paned form reports no sections, so it draws nothing there. + */ +export function FormSectionNav({ items, className }: FormSectionNavProps) { + const { t } = useSectionNavTranslation(); + const [current, setCurrent] = React.useState(undefined); + // While set, the jump a click started is under way: see CLICK_HOLD_MS. + const holding = React.useRef | 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. + React.useEffect(() => { + if (!anchorIds) return; + const ids = anchorIds.split('\n'); + const keyByAnchor = new Map((shown ?? []).map((i) => [i.anchorId, i.key])); + const first = document.getElementById(ids[0]); + if (!first) return; + const scroller = scrollParentOf(first); + const target: HTMLElement | Window = scroller ?? window; + let frame = 0; + const measure = () => { + frame = 0; + if (holding.current) return; + const top = scroller ? scroller.getBoundingClientRect().top : 0; + const atBottom = scroller + ? scroller.scrollTop > 0 && scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2 + : window.scrollY > 0 && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2; + let found = ids[0]; + if (atBottom) { + found = ids[ids.length - 1]; + } else { + for (const id of ids) { + const el = document.getElementById(id); + if (el && el.getBoundingClientRect().top - top <= SCROLL_SPY_OFFSET) found = id; + } + } + setCurrent(keyByAnchor.get(found)); + }; + const onScroll = () => { + if (!frame) frame = requestAnimationFrame(measure); + }; + target.addEventListener('scroll', onScroll, { passive: true }); + return () => { + target.removeEventListener('scroll', onScroll); + if (frame) cancelAnimationFrame(frame); + }; + // `anchorIds` stands for `shown`: the listener only needs re-binding when + // the set of headings changes, not when a count does. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [anchorIds]); + + const active = shown ? (shown.some((i) => i.key === current) ? current : shown[0].key) : undefined; + + // Keep the current entry in view inside the strip, which scrolls sideways + // on a narrow screen. The strip's own scroll offset only: an element + // `scrollIntoView` here would also move the form and cut a jump short. + const navRef = React.useRef(null); + React.useEffect(() => { + const strip = navRef.current; + const entry = strip?.querySelector('[aria-current="true"]'); + if (!strip || !entry) return; + const left = entry.offsetLeft; + const right = left + entry.offsetWidth; + if (left < strip.scrollLeft) strip.scrollLeft = left; + else if (right > strip.scrollLeft + strip.clientWidth) strip.scrollLeft = right - strip.clientWidth; + }, [active]); + + if (!shown) return null; + + const jump = (item: FormSectionNavItem) => { + if (holding.current) clearTimeout(holding.current); + holding.current = setTimeout(() => { + holding.current = null; + }, CLICK_HOLD_MS); + setCurrent(item.key); + const reveal = () => + document.getElementById(item.anchorId)?.scrollIntoView?.({ block: 'start', behavior: 'smooth' }); + if (item.collapsed) { + item.expand(); + // The unfolded fields mount on the next render; scroll once they have. + requestAnimationFrame(reveal); + } else { + reveal(); + } + }; + + return ( + + ); +} diff --git a/ui/packages/plugin-form/src/ModalForm.tsx b/ui/packages/plugin-form/src/ModalForm.tsx index 5adf3e52c49..ab1bd4684c9 100644 --- a/ui/packages/plugin-form/src/ModalForm.tsx +++ b/ui/packages/plugin-form/src/ModalForm.tsx @@ -34,6 +34,7 @@ import { AlertDialogAction, AlertDialogCancel, toast, + FormSectionNavContext, } from '@object-ui/components'; import { Loader2 } from 'lucide-react'; import { MasterDetailForm } from './MasterDetailForm'; @@ -85,6 +86,7 @@ import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget'; import { useRecordInvalidation } from './recordInvalidation'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; import { useInitialFieldFocus } from './initialFieldFocus'; +import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { FormDirtyReportContext } from './formDirtyReport'; // Localized strings for the unsaved-changes guard and, since objectui#11039, @@ -366,6 +368,11 @@ const ModalFormBody: React.FC = ({ // Upload-in-flight gate (objectui#10166): Save is refused, disabled and // EXPLAINED while a file/image widget below is still uploading. const uploadGate = useUploadGate(); + // The section navigation between the header and the scrolling body + // (objectstack#34605): the form reports its visible sections, the dialog + // draws them where they stay in view while the body scrolls. + const sectionNav = useFormSectionNav(); + const drawsSectionNav = (sectionNav.items?.length ?? 0) >= 2; const previewMode = usePreviewMode(); const perms = usePermissions(); // ADR-0144 D8 rule 4 — the organization currency a record-currency code @@ -1328,7 +1335,7 @@ const ModalFormBody: React.FC = ({ className={cn(sizeClass, 'flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0', className, schema.className)} > {(schema.title || schema.description) && ( - + {schema.title && {schema.title}} {schema.description ? ( {schema.description} @@ -1340,6 +1347,8 @@ const ModalFormBody: React.FC = ({ )} + +
{/* Every upload widget below reports into this scope, however deep — a section, a tab, a subform row (objectui#10166). */} @@ -1352,6 +1361,7 @@ const ModalFormBody: React.FC = ({
+
{/* Sticky footer — always visible action buttons */} {hasFooter && ( diff --git a/ui/packages/plugin-form/src/ObjectForm.test.tsx b/ui/packages/plugin-form/src/ObjectForm.test.tsx index 8ec5b623bb5..bb15c895d5b 100644 --- a/ui/packages/plugin-form/src/ObjectForm.test.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.test.tsx @@ -1,5 +1,9 @@ import { describe, it, expect, vi } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; + +// Section names are read inside the
: the section navigation above it +// repeats each name once two or more sections are drawn (objectstack#34605). +const inForm = () => within(document.querySelector('form') as HTMLElement); import { ObjectForm } from './ObjectForm'; import { registerAllFields } from '@object-ui/fields'; import React from 'react'; @@ -145,9 +149,9 @@ describe('ObjectForm Integration', () => { ); await waitFor(() => { - expect(screen.getByText('Contact Info')).toBeTruthy(); + expect(inForm().getByText('Contact Info')).toBeTruthy(); }); - expect(screen.getByText('Billing')).toBeTruthy(); + expect(inForm().getByText('Billing')).toBeTruthy(); // All fields still render, including the ungrouped one. expect(container.querySelector('input[name="email"]')).toBeTruthy(); expect(container.querySelector('input[name="amount"]')).toBeTruthy(); @@ -186,7 +190,7 @@ describe('ObjectForm Integration', () => { // Collapse the Contact Info group → its email field leaves the DOM, // while the other group's field and the ungrouped field stay. - fireEvent.click(screen.getByText('Contact Info')); + fireEvent.click(inForm().getByText('Contact Info')); await waitFor(() => { expect(container.querySelector('input[name="email"]')).toBeNull(); }); @@ -194,7 +198,7 @@ describe('ObjectForm Integration', () => { expect(container.querySelector('[name="notes"]')).toBeTruthy(); // Expand again → the field returns. - fireEvent.click(screen.getByText('Contact Info')); + fireEvent.click(inForm().getByText('Contact Info')); await waitFor(() => { expect(container.querySelector('input[name="email"]')).toBeTruthy(); }); diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index e53de3f1304..0f8a4662f80 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -21,7 +21,7 @@ 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'; +import { useIsMobile, toast, FormSectionNavContext } from '@object-ui/components'; import { resolveSuccessNavigate } from './successBehavior'; import { resolveSubmitRedirect, submitRedirectScope } from './submitRedirect'; import { @@ -49,6 +49,7 @@ import { sectionedGridLayout, } from './autoLayout'; import { deriveFieldGroupSections, projectSectionDivider, resolveSectionCollapse, type FormFieldWithGroup } from './fieldGroups'; +import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { mergeCustomFields } from './customFieldsMerge'; import { hasSectionGroupReference, resolveSectionGroupReferences } from './sectionGroups'; import { @@ -598,6 +599,9 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource // file/image widget below me still uploading" answer, the Save label while it // is true, and the sentence that says why. See `uploadGate.tsx`. const uploadGate = useUploadGate(); + // The section navigation above a sectioned form (objectstack#34605): the + // form reports its visible sections, this host draws them. + const sectionNav = useFormSectionNav(); // Field-level permission gate. When the consumer hasn't mounted a // PermissionProvider / MePermissionsProvider, `usePermissions` returns // a permissive default (isLoaded:false, checkField always true) so we @@ -1796,8 +1800,11 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource return ( +
{closedAffordanceNotice} + {/* Sticky, so the sections stay one click away down a long page. */} + {conflictDialog}
+
); } diff --git a/ui/packages/plugin-form/src/__tests__/formViewTabKeysAndButtons-26843.test.tsx b/ui/packages/plugin-form/src/__tests__/formViewTabKeysAndButtons-26843.test.tsx index b2a478e2a9f..6447b4c59fc 100644 --- a/ui/packages/plugin-form/src/__tests__/formViewTabKeysAndButtons-26843.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/formViewTabKeysAndButtons-26843.test.tsx @@ -24,7 +24,11 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, within } from '@testing-library/react'; + +// Section names are read inside the : the section navigation above it +// repeats each name once two or more sections are drawn (objectstack#34605). +const inForm = () => within(document.querySelector('form') as HTMLElement); import React from 'react'; import { registerAllFields } from '@object-ui/fields'; import { ObjectForm } from '../ObjectForm'; @@ -154,7 +158,7 @@ describe('the modal tabbed layout honours the tab keys, with and without subform it('CONTROL: subforms with no contentLayout stay stacked — no tab strip', async () => { renderModalForm({ contentLayout: undefined, subforms: SUBFORMS }); - await waitFor(() => expect(screen.getByText('Sec Two')).toBeInTheDocument()); + await waitFor(() => expect(inForm().getByText('Sec Two')).toBeInTheDocument()); expect(trigger('s1')).toBeNull(); }); diff --git a/ui/packages/plugin-form/src/__tests__/sectionLabelI18n.test.tsx b/ui/packages/plugin-form/src/__tests__/sectionLabelI18n.test.tsx index ac984e7424c..c19f274a150 100644 --- a/ui/packages/plugin-form/src/__tests__/sectionLabelI18n.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/sectionLabelI18n.test.tsx @@ -21,7 +21,11 @@ * derived from its authored label. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor, renderHook } from '@testing-library/react'; +import { render, screen, waitFor, renderHook, within } from '@testing-library/react'; + +// Section names are read inside the : the section navigation above it +// repeats each name once two or more sections are drawn (objectstack#34605). +const inForm = () => within(document.querySelector('form') as HTMLElement); import React from 'react'; import { createI18n, I18nProvider, useObjectLabel } from '@object-ui/i18n'; import { registerAllFields } from '@object-ui/fields'; @@ -140,8 +144,8 @@ describe('form section headings resolve `_sections` (objectstack#5408)', () => { // The non-tabbed grouping heading goes through the same resolver, so a // `simple` form view's headings never diverge from its tabbed sibling. renderForm(withSections(), { formType: 'simple', sections: NAMED_SECTIONS }); - await waitFor(() => expect(screen.getByText('工单信息')).toBeTruthy()); - expect(screen.getByText('SLA')).toBeTruthy(); + await waitFor(() => expect(inForm().getByText('工单信息')).toBeTruthy()); + expect(inForm().getByText('SLA')).toBeTruthy(); }); it('falls back to the authored label when the bundle carries no `_sections`', async () => { diff --git a/ui/packages/plugin-form/src/__tests__/sectionVisibleWhen-6111.test.tsx b/ui/packages/plugin-form/src/__tests__/sectionVisibleWhen-6111.test.tsx index 63e7cdb8ad7..85e7ded9fef 100644 --- a/ui/packages/plugin-form/src/__tests__/sectionVisibleWhen-6111.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/sectionVisibleWhen-6111.test.tsx @@ -122,7 +122,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, within } from '@testing-library/react'; import React from 'react'; import { PredicateScopeProvider } from '@object-ui/react'; import { registerAllFields } from '@object-ui/fields'; @@ -178,6 +178,13 @@ afterEach(() => { vi.restoreAllMocks(); }); +/** + * Section names are read inside the ``: with two sections drawn, the + * dialog and the full-page form also repeat each name in their section + * navigation above the form (objectstack#34605). + */ +const inForm = () => within(document.querySelector('form') as HTMLElement); + /** * Two sections: `Always` carries no predicate and is the paired control that * proves the form rendered AT ALL — so a missing `Compensation` heading is a @@ -209,7 +216,7 @@ const renderObjectForm = async ( , ); // The un-gated sibling heading is the readiness signal AND the control. - await waitFor(() => expect(screen.getByText('Always')).toBeTruthy()); + await waitFor(() => expect(inForm().getByText('Always')).toBeTruthy()); }; /** Mount `ModalForm` directly — the shape `resolveFormViewLayout` produces. */ @@ -233,11 +240,11 @@ const renderModalFormDirect = async ( /> , ); - await waitFor(() => expect(screen.getByText('Always')).toBeTruthy()); + await waitFor(() => expect(inForm().getByText('Always')).toBeTruthy()); }; /** The gated section's heading — `null` when the layout hid it. */ -const gatedHeading = () => screen.queryByText('Compensation'); +const gatedHeading = () => inForm().queryByText('Compensation'); /** * The gated section's claimed MEMBER field (#6236) — `null` when the layout's diff --git a/ui/packages/plugin-form/src/sectionedFormValues.test.tsx b/ui/packages/plugin-form/src/sectionedFormValues.test.tsx index 2f436892c5d..ecf1c8c94d1 100644 --- a/ui/packages/plugin-form/src/sectionedFormValues.test.tsx +++ b/ui/packages/plugin-form/src/sectionedFormValues.test.tsx @@ -32,7 +32,11 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; +import { render, screen, fireEvent, waitFor, cleanup, within } from '@testing-library/react'; + +// Section names are read inside the : the section navigation above it +// repeats each name once two or more sections are drawn (objectstack#34605). +const inForm = () => within(document.querySelector('form') as HTMLElement); import { registerAllFields } from '@object-ui/fields'; import { ModalForm } from './ModalForm'; import { TabbedForm } from './TabbedForm'; @@ -248,8 +252,8 @@ describe('ModalForm stacked sections — one form for all sections (#2153)', () />, ); - expect(await screen.findByText('Basics')).toBeTruthy(); - expect(screen.getByText('Triage')).toBeTruthy(); + await waitFor(() => expect(inForm().getByText('Basics')).toBeTruthy()); + expect(inForm().getByText('Triage')).toBeTruthy(); // A section's authored blurb survives the move to inline headers. expect(screen.getByText('Who is asking')).toBeTruthy(); });