diff --git a/.changeset/34604-modal-form-maximize.md b/.changeset/34604-modal-form-maximize.md new file mode 100644 index 00000000000..972333e3f17 --- /dev/null +++ b/.changeset/34604-modal-form-maximize.md @@ -0,0 +1,20 @@ +--- +'@object-ui/plugin-form': patch +--- + +feat(plugin-form): the form dialog's header has a maximize / restore button, like the record drawer's, and remembers the choice per object + +Clause-②: no +Metadata-protocol: none + +A create or edit dialog could not be made bigger: a long form, or a form with line items, stayed in a dialog capped at 90% of the window height. The dialog header now has the record drawer's maximize button (the same icon, size and labels, "Maximize" / "Restore size"), just before the close (X) button. + +- **Maximize** widens the dialog to the `full` size (95% of the window width) and makes it fill 95% of the window height. The form body scrolls inside the dialog. +- **Restore size** puts the dialog back to its declared or inferred size. +- The form stays open the whole time. Typed values, the unsaved-changes prompt on close, and line items added in a form with `subforms` are all kept. +- Both dialog kinds have the button: a plain form and a form with `subforms` (line items). +- A maximized dialog with no declared `columns` uses the `full` column count, so a form with sixteen or more fields shows four per row. +- The choice is remembered per object in the browser's local storage. The next dialog for that object opens the same way. Other objects are not affected. +- On a phone the dialog already fills the screen, so the button is shown from the `sm` breakpoint up only. + +No metadata changes. An authored `modalSize` is still the size the dialog opens with until the user maximizes it. diff --git a/ui/packages/plugin-form/src/ModalForm.tsx b/ui/packages/plugin-form/src/ModalForm.tsx index ab1bd4684c9..5bfce7040ea 100644 --- a/ui/packages/plugin-form/src/ModalForm.tsx +++ b/ui/packages/plugin-form/src/ModalForm.tsx @@ -33,10 +33,11 @@ import { AlertDialogDescription, AlertDialogAction, AlertDialogCancel, + RecordTopBarButton, toast, FormSectionNavContext, } from '@object-ui/components'; -import { Loader2 } from 'lucide-react'; +import { Loader2, Maximize2, Minimize2 } from 'lucide-react'; import { MasterDetailForm } from './MasterDetailForm'; import { SchemaRenderer, useSafeFieldLabel, usePreviewMode } from '@object-ui/react'; import { createSafeTranslation, useLocalization } from '@object-ui/i18n'; @@ -88,6 +89,7 @@ import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploa import { useInitialFieldFocus } from './initialFieldFocus'; import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { FormDirtyReportContext } from './formDirtyReport'; +import { useModalFormMaximized } from './modalMaximize'; // Localized strings for the unsaved-changes guard and, since objectui#11039, // the form's own chrome (the default submit and cancel labels and the @@ -118,6 +120,10 @@ const useDiscardTranslation = createSafeTranslation( // The heading of the fields no declared field group claims // (`deriveFieldGroupSections`' trailing bucket). 'common.ungroupedSection': 'Other', + // The header's maximize / restore switch: the record drawer's own pair of + // keys and labels (objectstack-ai/objectstack#34604). + 'detail.maximize': 'Maximize', + 'detail.restoreSize': 'Restore size', }, 'form.discardTitle', ); @@ -511,6 +517,12 @@ const ModalFormBody: React.FC = ({ ? effectiveSections.reduce((n, s) => n + (Array.isArray(s.fields) ? s.fields.length : 0), 0) : layoutPool.length; + // The header's maximize switch (objectstack-ai/objectstack#34604): + // maximized, the dialog is `full` whatever its authored or inferred size, + // and every reader of the size below — the width class and the undeclared + // column count — reads that effective size. + const { maximized, toggleMaximized } = useModalFormMaximized(schema.objectName); + // The dialog's size when the author declared none (objectui#12521): bounded // — `lg` or `xl`, never `full` — and chosen from the declared grid and the // field count, so a short form is not stretched across a wide dialog. An @@ -519,12 +531,13 @@ const ModalFormBody: React.FC = ({ // size, so the size reads that floor and never the count it then bounds // (objectstack-ai/objectstack#34607). const effectiveModalSize = useMemo(() => { + if (maximized) return 'full'; if (schema.modalSize) return schema.modalSize; const columns = effectiveSections?.length ? sectionedFormColumns(schema.columns, effectiveSections.map((s) => s.columns), DIALOG_DEFAULT_COLUMNS) : (clampColumns(schema.columns) ?? DIALOG_DEFAULT_COLUMNS); return inferModalSize(Math.min(columns, inferColumns(layoutFieldCount))); - }, [schema.modalSize, schema.columns, effectiveSections, layoutFieldCount]); + }, [maximized, schema.modalSize, schema.columns, effectiveSections, layoutFieldCount]); // The count an undeclared form or section draws in THIS dialog // (objectstack-ai/objectstack#34607): from the field count, bounded by the @@ -542,6 +555,13 @@ const ModalFormBody: React.FC = ({ }, [formFields, objectSchema, flatColumns, schema.mode, effectiveSections]); const sizeClass = modalSizeClasses[effectiveModalSize] || modalSizeClasses.default; + // The content's height: a phone sheet is always the whole screen; from `sm` + // up the dialog grows with its body to a `90vh` cap, and maximized it fills + // `95dvh` — the height counterpart of the `full` size's `95vw` — so its body + // scroller, not the page, scrolls a long form. + const heightClass = maximized + ? 'h-[100dvh] sm:h-[95dvh] sm:max-h-[95dvh]' + : 'h-[100dvh] sm:h-auto sm:max-h-[90vh]'; // Fetch object schema useEffect(() => { @@ -1226,6 +1246,28 @@ const ModalFormBody: React.FC = ({ attemptClose(false); }; + // The header's maximize / restore switch (objectstack-ai/objectstack#34604): + // the record drawer's control — its `RecordTopBarButton`, its lucide pair at + // its size, its labels — drawn just before the dialog's close (X), in both + // arms. The last child of the content, so it sits after the form in the tab + // order and right before the X, as the drawer orders them. From `sm` up + // only: the phone sheet already fills the screen. Toggling changes the + // content's classes and nothing else, so the form below stays mounted. + const maximizeButton = ( + + ); + // The header keeps its title clear of the switch and the X from `sm` up. + // Its bottom rule is each arm's: the flat arm hands it to the section nav + // strip when one is drawn. + const headerClass = 'shrink-0 px-4 pt-4 sm:px-6 sm:pt-6 sm:pr-20 pb-2'; + // Unsaved-changes guard — rendered INSIDE DialogContent so its portal // inherits the Dialog's Radix layer context (focus scope + dismissable // layer) through React. As a sibling of it had no such context, so @@ -1265,10 +1307,11 @@ const ModalFormBody: React.FC = ({ showCloseButton={showCloseButton} onOpenAutoFocus={initialFieldFocus.onOpenAutoFocus} onCloseAutoFocus={initialFieldFocus.onCloseAutoFocus} - className={cn(sizeClass, 'flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0', className, schema.className)} + className={cn(sizeClass, 'flex flex-col overflow-hidden p-0', heightClass, className, schema.className)} + data-maximized={maximized ? '' : undefined} > {(schema.title || schema.description) && ( - + {schema.title && {schema.title}} {schema.description ? ( {schema.description} @@ -1319,6 +1362,7 @@ const ModalFormBody: React.FC = ({ {discardDialog} + {maximizeButton} ); @@ -1332,10 +1376,11 @@ const ModalFormBody: React.FC = ({ showCloseButton={showCloseButton} onOpenAutoFocus={initialFieldFocus.onOpenAutoFocus} onCloseAutoFocus={initialFieldFocus.onCloseAutoFocus} - className={cn(sizeClass, 'flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0', className, schema.className)} + className={cn(sizeClass, 'flex flex-col overflow-hidden p-0', heightClass, className, schema.className)} + data-maximized={maximized ? '' : undefined} > {(schema.title || schema.description) && ( - + {schema.title && {schema.title}} {schema.description ? ( {schema.description} @@ -1416,6 +1461,7 @@ const ModalFormBody: React.FC = ({ the Dialog content the conflict alert stacks as the topmost Radix layer, so its buttons receive clicks while the modal stays open. */} {conflictDialog} + {maximizeButton} ); diff --git a/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx new file mode 100644 index 00000000000..d8be54e4ead --- /dev/null +++ b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx @@ -0,0 +1,387 @@ +/** + * 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-ai/objectstack#34604 — the form dialog's header carries the + * record drawer's maximize / restore switch, in both of its arms (the flat + * form and the `subforms` master-detail form). + * + * Maximized, the dialog is `full` (`sm:max-w-[95vw]`) and fills `95dvh` + * instead of growing to its `90vh` cap; restored, it is what it was. Only the + * content element's classes change: the same content node, the same inputs, + * the typed values, the dirty state that arms the close guard and the added + * lines all survive the switch. The choice is remembered per object. + * + * jsdom evaluates no container query, so the column count is read from the + * grid classes the form renderer draws (the `dialogContainerColumns-34607` + * reading). + */ + +import React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; +import { registerAllFields } from '@object-ui/fields'; +import { ModalForm } from '../ModalForm'; +import { modalFormMaximizedStorageKey } from '../modalMaximize'; + +registerAllFields(); + +beforeEach(() => window.localStorage.clear()); +afterEach(() => { + cleanup(); + window.localStorage.clear(); +}); + +const DEAL = { + name: 'deal', + fields: { + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; + +const ACCOUNT = { name: 'account', fields: { name: { type: 'text', label: 'Name' } } }; + +function flatDs(defs: Record): any { + return { + getObjectSchema: vi.fn(async (name: string) => defs[name]), + find: vi.fn().mockResolvedValue({ data: [] }), + findOne: vi.fn(), + create: vi.fn().mockResolvedValue({ id: '1' }), + update: vi.fn(), + }; +} + +function renderFlat(objectName: string, extra: Record = {}) { + const onOpenChange = vi.fn(); + const utils = render( + , + ); + return { ...utils, onOpenChange }; +} + +const dialog = () => screen.getByRole('dialog') as HTMLElement; +const maximizeButton = () => screen.getByTestId('modal-form-maximize'); + +async function nameInput(): Promise { + return waitFor(() => { + const el = document.querySelector('input[name="name"]') as HTMLInputElement | null; + if (!el) throw new Error('form not ready'); + return el; + }); +} + +function expectRestored(el: HTMLElement) { + expect(el.hasAttribute('data-maximized')).toBe(false); + expect(el.className).toContain('sm:max-h-[90vh]'); + expect(el.className).toContain('sm:h-auto'); + expect(el.className).not.toContain('sm:max-w-[95vw]'); +} + +function expectMaximized(el: HTMLElement) { + expect(el.hasAttribute('data-maximized')).toBe(true); + expect(el.className).toContain('sm:max-w-[95vw]'); + expect(el.className).toContain('sm:h-[95dvh]'); + expect(el.className).toContain('sm:max-h-[95dvh]'); + expect(el.className).not.toContain('sm:max-h-[90vh]'); + expect(el.className).not.toContain('sm:h-auto'); +} + +describe('#34604 — the flat arm: maximize, restore, nothing lost', () => { + it('draws the switch with the drawer label and icon, before the close button, and toggles in place', async () => { + renderFlat('deal'); + await nameInput(); + const btn = maximizeButton(); + expect(btn.getAttribute('aria-label')).toBe('Maximize'); + expect(btn.querySelector('svg.lucide-maximize2, svg.lucide-maximize-2')).not.toBeNull(); + // Just before the X in document (and tab) order, as the drawer orders them. + const close = screen.getByRole('button', { name: 'Close' }); + expect(btn.compareDocumentPosition(close) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // The phone sheet already fills the screen: the switch is drawn from `sm` up. + expect(btn.className).toContain('hidden'); + expect(btn.className).toContain('sm:inline-flex'); + + const content = dialog(); + expectRestored(content); + const restoredWidth = content.className.match(/sm:max-w-\S+/)?.[0]; + + fireEvent.click(btn); + expect(dialog()).toBe(content); + expectMaximized(content); + expect(maximizeButton().getAttribute('aria-label')).toBe('Restore size'); + expect(maximizeButton().querySelector('svg.lucide-minimize2, svg.lucide-minimize-2')).not.toBeNull(); + + fireEvent.click(maximizeButton()); + expect(dialog()).toBe(content); + expectRestored(content); + expect(content.className.match(/sm:max-w-\S+/)?.[0]).toBe(restoredWidth); + }); + + it('keeps the typed value and the same input across two toggles, and the close guard still fires', async () => { + const { onOpenChange } = renderFlat('deal'); + const input = await nameInput(); + fireEvent.change(input, { target: { value: 'Big deal' } }); + + fireEvent.click(maximizeButton()); + expect(await nameInput()).toBe(input); + expect(input.value).toBe('Big deal'); + fireEvent.click(maximizeButton()); + fireEvent.click(maximizeButton()); + expect(await nameInput()).toBe(input); + expect(input.value).toBe('Big deal'); + expectMaximized(dialog()); + + // Dirty survived: the accidental close (the X) asks first, maximized. + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + await waitFor(() => expect(screen.getByText('Discard changes?')).toBeTruthy()); + expect(onOpenChange).not.toHaveBeenCalled(); + }); + + it('draws the switch with the close button hidden too', async () => { + renderFlat('deal', { modalCloseButton: false }); + await nameInput(); + expect(screen.queryByRole('button', { name: 'Close' })).toBeNull(); + fireEvent.click(maximizeButton()); + expectMaximized(dialog()); + }); +}); + +describe('#34604 — the choice is remembered per object', () => { + it('reopens maximized for the same object; another object opens at its own size', async () => { + renderFlat('deal'); + await nameInput(); + fireEvent.click(maximizeButton()); + expect(window.localStorage.getItem(modalFormMaximizedStorageKey('deal'))).toBe('1'); + cleanup(); + + renderFlat('deal'); + await nameInput(); + expectMaximized(dialog()); + expect(maximizeButton().getAttribute('aria-label')).toBe('Restore size'); + cleanup(); + + renderFlat('account'); + await nameInput(); + expectRestored(dialog()); + expect(window.localStorage.getItem(modalFormMaximizedStorageKey('account'))).toBeNull(); + }); + + it('restoring forgets the choice', async () => { + window.localStorage.setItem(modalFormMaximizedStorageKey('deal'), '1'); + renderFlat('deal'); + await nameInput(); + expectMaximized(dialog()); + fireEvent.click(maximizeButton()); + expectRestored(dialog()); + expect(window.localStorage.getItem(modalFormMaximizedStorageKey('deal'))).toBeNull(); + }); + + it('switches to the other object’s choice when a mounted dialog is handed another object', async () => { + window.localStorage.setItem(modalFormMaximizedStorageKey('deal'), '1'); + const ds = flatDs({ deal: DEAL, account: ACCOUNT }); + const schema = (objectName: string) => + ({ type: 'object-form', formType: 'modal', objectName, mode: 'create', title: 'New', open: true }) as any; + const { rerender } = render(); + await nameInput(); + expectMaximized(dialog()); + rerender(); + expectRestored(dialog()); + }); + + it('a blocked store leaves the switch working', async () => { + const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('blocked'); + }); + const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('blocked'); + }); + try { + renderFlat('deal'); + await nameInput(); + expectRestored(dialog()); + fireEvent.click(maximizeButton()); + expectMaximized(dialog()); + } finally { + getItem.mockRestore(); + setItem.mockRestore(); + } + }); +}); + +describe('#34604 — the undeclared column count reads the maximized size', () => { + const PLAIN = Array.from({ length: 16 }, (_, i) => `f${i}`); + const SIXTEEN = { + name: 'thing', + fields: Object.fromEntries(PLAIN.map((n) => [n, { type: 'text', label: `Field ${n}` }])), + }; + + /** Fields per row at `@4xl`: the grid tracks in force over the field's span in force. */ + function perRowAt4xl(name: string): number { + const cell = document.body.querySelector(`[data-field="${name}"]`); + if (!cell) throw new Error(`field not rendered: ${name}`); + const tokens = (el: Element | null) => (el?.getAttribute('class') || '').split(/\s+/); + const inForce = (list: string[], stem: string) => { + let v: number | undefined; + for (const tier of ['@md', '@2xl', '@4xl']) { + const hit = list.find((c) => c.startsWith(`${tier}:${stem}`)); + if (hit) v = Number(hit.split('-').pop()); + } + return v; + }; + return (inForce(tokens(cell.parentElement), 'grid-cols-') ?? 1) / (inForce(tokens(cell), 'col-span-') ?? 1); + } + + it('sixteen undeclared fields: three per row in the inferred xl, four maximized, three again restored', async () => { + render( + , + ); + await waitFor(() => expect(document.body.querySelector('[data-field="f0"]')).not.toBeNull()); + expect(dialog().className).toContain('sm:max-w-5xl'); + expect(perRowAt4xl('f0')).toBe(3); + + const input = document.querySelector('input[name="f0"]') as HTMLInputElement; + fireEvent.change(input, { target: { value: 'kept' } }); + fireEvent.click(maximizeButton()); + expect(dialog().className).toContain('sm:max-w-[95vw]'); + expect(perRowAt4xl('f0')).toBe(4); + expect((document.querySelector('input[name="f0"]') as HTMLInputElement).value).toBe('kept'); + + fireEvent.click(maximizeButton()); + expect(dialog().className).toContain('sm:max-w-5xl'); + expect(perRowAt4xl('f0')).toBe(3); + }); +}); + +describe('#34604 — the master-detail (subforms) arm', () => { + const mdDs = (): any => ({ + getObjectSchema: vi.fn(async (name: string) => + name === 'quote' + ? { name: 'quote', fields: { title: { type: 'text', label: 'Title' } } } + : { name: 'quote_line', fields: { qty: { type: 'number', label: 'Qty' } } }, + ), + find: vi.fn().mockResolvedValue({ data: [] }), + batchTransaction: vi.fn().mockResolvedValue({ results: [{ id: 'q1' }] }), + }); + const subforms = [ + { childObject: 'quote_line', relationshipField: 'quote', title: 'Lines', columns: [{ name: 'qty', label: 'Qty', type: 'number' }] }, + ]; + + function renderMd() { + const onOpenChange = vi.fn(); + render( + , + ); + return { onOpenChange }; + } + + async function headerInput(): Promise { + await waitFor(() => expect(screen.getByTestId('md-form-submit')).toBeTruthy()); + return waitFor(() => { + const el = document.querySelector('input[name="title"]') as HTMLInputElement | null; + if (!el) throw new Error('header form not ready'); + return el; + }); + } + + const qtyInputs = () => screen.queryAllByLabelText('Qty') as HTMLInputElement[]; + /** The same input ELEMENTS, in order — identity, not structural equality. */ + const expectSameLines = (lines: HTMLInputElement[]) => { + const now = qtyInputs(); + expect(now.length).toBe(lines.length); + now.forEach((el, i) => expect(el).toBe(lines[i])); + }; + + it('draws the switch and toggles the same content node in place', async () => { + renderMd(); + await headerInput(); + const content = dialog(); + expect(maximizeButton().getAttribute('aria-label')).toBe('Maximize'); + expectRestored(content); + fireEvent.click(maximizeButton()); + expect(dialog()).toBe(content); + expectMaximized(content); + expect(screen.getByTestId('md-form-submit')).toBeTruthy(); + fireEvent.click(maximizeButton()); + expectRestored(content); + }); + + it('keeps the header value and an added line across two toggles; the close guard still fires', async () => { + const { onOpenChange } = renderMd(); + const title = await headerInput(); + fireEvent.change(title, { target: { value: 'Q-1' } }); + await waitFor(() => expect(qtyInputs().length).toBeGreaterThan(0)); + const before = qtyInputs().length; + fireEvent.click(screen.getByRole('button', { name: /add/i })); + await waitFor(() => expect(qtyInputs().length).toBe(before + 1)); + // Type into the first line, so the grid's own trailing-row behaviour on + // its last line stays out of the count. + const lines = qtyInputs(); + const line = lines[0]; + fireEvent.change(line, { target: { value: '7' } }); + expectSameLines(lines); + + fireEvent.click(maximizeButton()); + fireEvent.click(maximizeButton()); + fireEvent.click(maximizeButton()); + expectMaximized(dialog()); + // The same line inputs, element for element: nothing below remounted. + expectSameLines(lines); + expect(line.value).toBe('7'); + expect(await headerInput()).toBe(title); + expect(title.value).toBe('Q-1'); + expect(screen.getByTestId('md-form-submit')).toBeTruthy(); + + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + await waitFor(() => expect(screen.getByText('Discard changes?')).toBeTruthy()); + expect(onOpenChange).not.toHaveBeenCalled(); + }); +}); + +describe('#34604 — beside the section nav strip of a sectioned flat form', () => { + const SECTIONED = { + name: 'deal', + fields: { + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + }, + }; + const sections = [ + { name: 'basics', label: 'Basics', fields: ['name'] }, + { name: 'money', label: 'Money', fields: ['amount'] }, + ]; + + it('keeps the nav strip, the same node, across two toggles; the header hands its rule to the strip', async () => { + render( + , + ); + await nameInput(); + const nav = await waitFor(() => screen.getByTestId('form-section-nav')); + const header = screen.getByText('New').parentElement as HTMLElement; + expect(header.className).toContain('sm:pr-20'); + expect(header.className.split(/\s+/)).not.toContain('border-b'); + + fireEvent.click(maximizeButton()); + expectMaximized(dialog()); + expect(screen.getByTestId('form-section-nav')).toBe(nav); + fireEvent.click(maximizeButton()); + expectRestored(dialog()); + expect(screen.getByTestId('form-section-nav')).toBe(nav); + }); +}); diff --git a/ui/packages/plugin-form/src/modalMaximize.ts b/ui/packages/plugin-form/src/modalMaximize.ts new file mode 100644 index 00000000000..8f29d7c0aaf --- /dev/null +++ b/ui/packages/plugin-form/src/modalMaximize.ts @@ -0,0 +1,84 @@ +/** + * 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. + */ + +/** + * The form dialog's maximize / restore switch (objectstack-ai/objectstack#34604). + * + * Package-internal: `ModalForm` is its only reader, and neither `index.tsx` + * nor `core.ts` re-exports it. + * + * Maximized, the dialog takes the `full` size and fills the window's height + * instead of growing up to its `90vh` cap. Only the content element's classes + * change, so the form below stays mounted: typed values, the dirty state and + * master-detail lines all survive the switch. + * + * The choice is a per-object PREFERENCE (ui AGENTS.md #8): one object's form + * dialog reopens the way the user last left it, and another object's is + * untouched. It lives in `localStorage` under {@link modalFormMaximizedStorageKey}; + * every storage access is guarded, so a server render, a private window or a + * blocked store reads as "not maximized" and a failed write keeps the switch + * working for the dialog's lifetime. + */ + +import { useState } from 'react'; + +/** The `localStorage` key that remembers whether `objectName`'s form dialog opens maximized. */ +export function modalFormMaximizedStorageKey(objectName: string): string { + return `modal-form-maximized:${objectName}`; +} + +/** Whether `objectName`'s form dialog was last left maximized; `false` when nothing is stored or storage is out of reach. */ +export function readModalFormMaximized(objectName: string): boolean { + if (!objectName || typeof window === 'undefined') return false; + try { + return window.localStorage.getItem(modalFormMaximizedStorageKey(objectName)) === '1'; + } catch { + return false; + } +} + +/** Remember the choice for `objectName`. Restoring removes the entry, so the stored default stays "not maximized". */ +export function writeModalFormMaximized(objectName: string, maximized: boolean): void { + if (!objectName || typeof window === 'undefined') return; + try { + const key = modalFormMaximizedStorageKey(objectName); + if (maximized) window.localStorage.setItem(key, '1'); + else window.localStorage.removeItem(key); + } catch { + // A blocked store only loses the memory of the choice, never the switch. + } +} + +/** + * The dialog's maximized state for `objectName`: seeded from the remembered + * choice, re-read when the dialog is handed another object, and written back + * on every toggle. + */ +export function useModalFormMaximized(objectName: string): { + maximized: boolean; + toggleMaximized: () => void; +} { + const [state, setState] = useState(() => ({ + objectName, + maximized: readModalFormMaximized(objectName), + })); + let current = state; + if (state.objectName !== objectName) { + // A render-phase update keyed on the object name: React discards this + // render's output and re-renders with the other object's choice before + // anything is committed. + current = { objectName, maximized: readModalFormMaximized(objectName) }; + setState(current); + } + const toggleMaximized = () => { + const next = !current.maximized; + writeModalFormMaximized(objectName, next); + setState({ objectName, maximized: next }); + }; + return { maximized: current.maximized, toggleMaximized }; +}