From a38808ba321344ec15f296ce83c0dab8a2bb492f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:36:14 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat(ui):=20one=20dialog=20surface=20?= =?UTF-8?q?=E2=80=94=20faint=20overlay,=20white=20two-layer=20card,=20comp?= =?UTF-8?q?act=20controls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dialog, AlertDialog and the form dialog's MobileDialogContent append the shared classes in packages/components/src/lib/dialog-surface.ts: a 10% overlay with no blur, a white card with a hairline edge and a 3px translucent outer ring, a 12px corner, and 32px controls from sm up. The two Shadcn primitives reach it through declared patches (alert-dialog gains its vendored registry fixture, round-trip true). The console's global [role="dialog"] corner rule is gone: popovers and the bottom drawer keep their corner by their own containers, and the shared shadow rule skips the dialog surface. The blurred overlay rule now reaches drawers only. Claude-Session: https://claude.ai/code/session_01L6bhgWL2r2CuFr34ENybDB Co-authored-by: Claude --- .../edgeSheetSquareCorners-35411.test.tsx | 41 ++--- ui/apps/console/src/index.css | 25 ++-- ui/packages/components/shadcn-components.json | 5 +- .../src/custom/mobile-dialog-content.tsx | 4 + .../components/src/lib/dialog-surface.ts | 67 +++++++++ .../components/src/ui/alert-dialog.tsx | 3 + ui/packages/components/src/ui/dialog.tsx | 3 + .../shadcn-registry/alert-dialog.registry.txt | 141 ++++++++++++++++++ .../__tests__/shadcn-local-patches.test.ts | 12 +- ui/scripts/shadcn-local-patches.mjs | 75 +++++++++- 10 files changed, 345 insertions(+), 31 deletions(-) create mode 100644 ui/packages/components/src/lib/dialog-surface.ts create mode 100644 ui/scripts/__tests__/fixtures/shadcn-registry/alert-dialog.registry.txt diff --git a/ui/apps/console/src/__tests__/edgeSheetSquareCorners-35411.test.tsx b/ui/apps/console/src/__tests__/edgeSheetSquareCorners-35411.test.tsx index 421a7d2f33c..93b6726348e 100644 --- a/ui/apps/console/src/__tests__/edgeSheetSquareCorners-35411.test.tsx +++ b/ui/apps/console/src/__tests__/edgeSheetSquareCorners-35411.test.tsx @@ -1,12 +1,16 @@ /** - * The console's extra-rounded dialog corners skip full-height edge drawers - * (objectstack#35411). + * The console's extra-rounded corners skip full-height edge drawers + * (objectstack#35411) and, since objectstack#35980, every modal dialog. * - * `index.css` gives every `role="dialog"` surface a 1.25rem radius. A left or - * right Sheet is fixed against the top, side and bottom of the viewport, so the - * radius showed as a notch at each inner corner. The rule now skips the Sheet's - * edge variants by the `inset-y-0` class their variant carries, while centred - * dialogs and bottom sheets keep the radius. + * `index.css` used to give every `role="dialog"` surface a 1.25rem radius. A + * left or right Sheet is fixed against the top, side and bottom of the + * viewport, so the radius showed as a notch at each inner corner; #35411 made + * the rule skip the Sheet's edge variants. #35980 moved the dialog's look onto + * the dialog itself (`dialog-surface`, a 12px card), so the rule no longer + * names every `role="dialog"`: it keeps the rounded corners for the floating + * popover and the bottom drawer only, by their own containers. A top or + * bottom Sheet meets the viewport on three edges like a side one, and is no + * longer matched either. * * The record drawer is the exception: it is a floating card (objectstack#35854) * that sets its own radius, so the global rule must not override it either. @@ -59,20 +63,21 @@ function renderSheet(side: 'left' | 'right' | 'bottom' | 'top'): HTMLElement { return screen.getByRole('dialog'); } -describe('edge sheets are not rounded by the dialog corner rule (#35411)', () => { - it('the rule still targets dialogs', () => { - expect(roundingSelector()).toContain('[role="dialog"]'); +describe('edge sheets and dialogs are not rounded by the corner rule (#35411, #35980)', () => { + it('the rule names popovers and the bottom drawer, never every dialog', () => { + const selector = roundingSelector(); + expect(selector).toContain('[data-radix-popper-content-wrapper] > [role="dialog"]'); + expect(selector).toContain('[data-vaul-drawer]'); + for (const part of selector.split(',')) { + expect(part.trim().startsWith('[role="dialog"]')).toBe(false); + } }); - it.each(['left', 'right'] as const)('a %s sheet is not matched', (side) => { + it.each(['left', 'right', 'bottom', 'top'] as const)('a %s sheet is not matched', (side) => { expect(renderSheet(side).matches(roundingSelector())).toBe(false); }); - it.each(['bottom', 'top'] as const)('a %s sheet keeps the rounded corners', (side) => { - expect(renderSheet(side).matches(roundingSelector())).toBe(true); - }); - - it('a centred dialog keeps the rounded corners', () => { + it('a centred dialog is not matched: it carries its own corner', () => { render( @@ -80,7 +85,9 @@ describe('edge sheets are not rounded by the dialog corner rule (#35411)', () => , ); - expect(screen.getByRole('dialog').matches(roundingSelector())).toBe(true); + const dialog = screen.getByRole('dialog'); + expect(dialog.matches(roundingSelector())).toBe(false); + expect(dialog.className.split(/\s+/)).toContain('sm:rounded-[12px]'); }); }); diff --git a/ui/apps/console/src/index.css b/ui/apps/console/src/index.css index 303259ad430..8172bd07a48 100644 --- a/ui/apps/console/src/index.css +++ b/ui/apps/console/src/index.css @@ -448,8 +448,10 @@ header.sticky { background-color: hsl(var(--background) / 0.6) !important; } -/* Soft, diffuse iOS elevation on floating surfaces (dialogs, menus, popovers). */ -[role="dialog"], +/* Soft, diffuse iOS elevation on floating surfaces (drawers, menus, popovers). + A modal dialog draws its own two-layer card (`dialog-surface`, + `packages/components/src/lib/dialog-surface.ts`) and is skipped here. */ +[role="dialog"]:not(.dialog-surface), [role="menu"], [data-radix-popper-content-wrapper] > * { box-shadow: @@ -513,11 +515,14 @@ header.sticky { background-color: hsl(135 59% 49%) !important; } -/* iOS sheet/dialog: extra-rounded corners, for surfaces that float or rise from - the bottom. A full-height edge drawer (the left/right Sheet, whose variant - pins it with `inset-y-0`) meets the viewport on three edges, so it keeps - square corners. */ -[role="dialog"]:not(.inset-y-0) { +/* iOS popover / bottom drawer: extra-rounded corners on the surfaces that float + beside a control or rise from the bottom. Keyed on their own containers — + a popover inside the floating layer's wrapper, the bottom drawer by its own + attribute — and no longer on every `[role="dialog"]`: a modal dialog carries + its own corner (`dialog-surface`), and a full-height edge drawer meets the + viewport on three edges, so it keeps square corners. */ +[data-radix-popper-content-wrapper] > [role="dialog"], +[data-vaul-drawer] { border-radius: 1.25rem !important; } @@ -551,8 +556,10 @@ header.sticky { * (CSS-only overrides; shadcn ui components not edited) * ------------------------------------------------------------ */ -/* iOS "spotlight"-style backdrop: blur + lighten the dim behind any - dialog / sheet / command palette overlay instead of a flat 80% black. */ +/* iOS "spotlight"-style backdrop for drawers: blur + lighten the dim behind a + sheet or a bottom drawer instead of a flat 80% black. A modal dialog's + overlay no longer carries `bg-black/80` (its faint, unblurred dim is + `DIALOG_OVERLAY_SURFACE`), so this rule reaches drawers only. */ .fixed.inset-0.z-50.bg-black\/80 { background-color: rgb(0 0 0 / 0.35) !important; -webkit-backdrop-filter: blur(8px) saturate(140%); diff --git a/ui/packages/components/shadcn-components.json b/ui/packages/components/shadcn-components.json index 99ae663eba4..35ecb764fad 100644 --- a/ui/packages/components/shadcn-components.json +++ b/ui/packages/components/shadcn-components.json @@ -34,7 +34,8 @@ ], "registryDependencies": [ "button" - ] + ], + "localEdits": "objectstack#35980 shared dialog surface: the overlay and the content each append one class token (`DIALOG_OVERLAY_SURFACE` / `DIALOG_CONTENT_SURFACE`, `packages/components/src/lib/dialog-surface.ts`), so a confirmation draws the same faint overlay and white two-layer card as every other dialog. Declared as data in `scripts/shadcn-local-patches.mjs` and re-applied on every `--update`; the vendored registry fixture regenerates the file byte for byte (`roundTrip: true`)." }, "aspect-ratio": { "source": "https://ui.shadcn.com/r/styles/default/aspect-ratio.json", @@ -131,7 +132,7 @@ "radix-ui" ], "registryDependencies": [], - "localEdits": "objectstack#5505 i18n close patch: `DialogContent` auto-renders an icon-only close button whose `sr-only` span IS its accessible name, and upstream hardcodes the English literal — so under zh/ja/es every modal in the console announced \"Close\" in English. The span is replaced by `` (`packages/components/src/lib/close-label.tsx`), which resolves `common.close` for the session locale and falls back to English with no I18nProvider mounted. It also carries the objectstack#29107 phone close touch-target patch: below `sm` the close button is a 44 px box with the 16 px glyph centred, and from `sm` up its classes are upstream's. Both edits are DECLARED as data in `scripts/shadcn-local-patches.mjs` and re-applied on every `--update`, and `pnpm shadcn:check` exits non-zero if either is ever missing from the file or can no longer be re-applied to upstream." + "localEdits": "objectstack#5505 i18n close patch: `DialogContent` auto-renders an icon-only close button whose `sr-only` span IS its accessible name, and upstream hardcodes the English literal — so under zh/ja/es every modal in the console announced \"Close\" in English. The span is replaced by `` (`packages/components/src/lib/close-label.tsx`), which resolves `common.close` for the session locale and falls back to English with no I18nProvider mounted. It also carries the objectstack#29107 phone close touch-target patch: below `sm` the close button is a 44 px box with the 16 px glyph centred, and from `sm` up its classes are upstream's. Both edits are DECLARED as data in `scripts/shadcn-local-patches.mjs` and re-applied on every `--update`, and `pnpm shadcn:check` exits non-zero if either is ever missing from the file or can no longer be re-applied to upstream. objectstack#35980 adds the shared dialog surface: one import and one class token each on the overlay and the content, naming `DIALOG_OVERLAY_SURFACE` / `DIALOG_CONTENT_SURFACE` (`packages/components/src/lib/dialog-surface.ts`), declared in the same file." }, "drawer": { "source": "https://ui.shadcn.com/r/styles/default/drawer.json", diff --git a/ui/packages/components/src/custom/mobile-dialog-content.tsx b/ui/packages/components/src/custom/mobile-dialog-content.tsx index dd2d1daed4f..8b5a660aa88 100644 --- a/ui/packages/components/src/custom/mobile-dialog-content.tsx +++ b/ui/packages/components/src/custom/mobile-dialog-content.tsx @@ -23,6 +23,7 @@ import { X } from 'lucide-react'; import { cn } from '../lib/utils'; import { CloseSrLabel } from '../lib/close-label'; import { DialogOverlay, DialogPortal } from '../ui/dialog'; +import { DIALOG_CONTENT_SURFACE } from '../lib/dialog-surface'; /** * Radix Select / Popover / DropdownMenu render their flyout into a portal at @@ -142,6 +143,9 @@ export const MobileDialogContent = React.forwardRef< 'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95', 'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]', 'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]', + // The look every modal dialog shares (objectstack#35980): white card, + // hairline edge, outer ring, compact controls from `sm` up. + DIALOG_CONTENT_SURFACE, className, )} {...props} diff --git a/ui/packages/components/src/lib/dialog-surface.ts b/ui/packages/components/src/lib/dialog-surface.ts new file mode 100644 index 00000000000..34fb0185929 --- /dev/null +++ b/ui/packages/components/src/lib/dialog-surface.ts @@ -0,0 +1,67 @@ +/** + * 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 look every modal dialog shares (objectstack-ai/objectstack#35980): the + * overlay behind it and the card it draws. `Dialog`, `AlertDialog` and the + * form dialog's `MobileDialogContent` each append these to their own class + * list, so a confirmation, a required-fields prompt and a create form are one + * surface. A call site's `className` still comes last and wins. + * + * The two Shadcn primitives reach this file through one declared import and + * one class token each (`scripts/shadcn-local-patches.mjs`); the look itself + * lives here, outside the regenerated `src/ui/**`. + * + * Until #35980 the console drew this look with global rules on every + * `[role="dialog"]`: a forced 20px corner, a 35% overlay with a blur behind + * it, and the page's own grey for the card. Those rules are gone; the dialog + * carries its look with it. + */ + +/** + * The overlay: a faint dim that says the page behind is out of reach for now, + * and no blur, so the page stays readable. Dark mode dims more, because ten + * per cent black on a near-black page is no change at all. + */ +export const DIALOG_OVERLAY_SURFACE = 'bg-black/10 dark:bg-black/40'; + +/** + * The 40px → 32px step for controls inside a dialog, from `sm` up: anything + * drawn at the shared 40px control height (`h-10`: the input, the select + * trigger, the default and icon buttons) draws at 32px. The phone sheet keeps + * its 44px touch targets, which ride their own `max-sm:` classes. + */ +export const DIALOG_COMPACT_CONTROLS = 'sm:[&_.h-10]:h-8 sm:[&_.h-10]:py-1 sm:[&_.h-10.w-10]:w-8'; + +/** + * The card, in two layers: + * + * - the INNER card is the element itself: the theme's card colour (white in + * light mode; the raised grey in dark, not the page's own background), a + * hairline edge and a 12px corner; + * - the OUTER ring is a 3px translucent band drawn as the first shadow, so it + * sits outside the card and is never clipped by a dialog that hides its + * own overflow (the form dialog scrolls its body inside). With the card's + * 12px corner, the band's outer corner is 15px. Three soft, wide shadows + * follow it. + * + * Controls inside it take {@link DIALOG_COMPACT_CONTROLS}. + * + * `dialog-surface` is a marker, not a utility: the console's shared shadow + * for floating surfaces (menus, popovers, drawers) skips an element that + * carries it, because this card draws its own. + */ +export const DIALOG_CONTENT_SURFACE = [ + 'dialog-surface', + 'bg-card text-card-foreground', + 'border-black/[0.07] dark:border-white/[0.09]', + 'sm:rounded-[12px]', + 'shadow-[0_0_0_3px_rgb(255_255_255/0.6),0_1px_2px_rgb(16_16_32/0.04),0_6px_16px_-4px_rgb(16_16_32/0.08),0_24px_48px_-12px_rgb(16_16_32/0.14)]', + 'dark:shadow-[0_0_0_3px_rgb(255_255_255/0.07),0_1px_2px_rgb(0_0_0/0.3),0_8px_24px_-6px_rgb(0_0_0/0.45),0_24px_48px_-12px_rgb(0_0_0/0.55)]', + DIALOG_COMPACT_CONTROLS, +].join(' '); diff --git a/ui/packages/components/src/ui/alert-dialog.tsx b/ui/packages/components/src/ui/alert-dialog.tsx index bc1b1a29420..e44c8eb3aaa 100644 --- a/ui/packages/components/src/ui/alert-dialog.tsx +++ b/ui/packages/components/src/ui/alert-dialog.tsx @@ -10,6 +10,7 @@ import * as React from "react" import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog" +import { DIALOG_CONTENT_SURFACE, DIALOG_OVERLAY_SURFACE } from "../lib/dialog-surface" import { cn } from "../lib/utils" import { buttonVariants } from "./button" @@ -27,6 +28,7 @@ const AlertDialogOverlay = React.forwardRef< , + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName + +const AlertDialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + +)) +AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName + +const AlertDialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +AlertDialogHeader.displayName = "AlertDialogHeader" + +const AlertDialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+) +AlertDialogFooter.displayName = "AlertDialogFooter" + +const AlertDialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName + +const AlertDialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogDescription.displayName = + AlertDialogPrimitive.Description.displayName + +const AlertDialogAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName + +const AlertDialogCancel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName + +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +} diff --git a/ui/scripts/__tests__/shadcn-local-patches.test.ts b/ui/scripts/__tests__/shadcn-local-patches.test.ts index a188c4ff16c..7ddb130392c 100644 --- a/ui/scripts/__tests__/shadcn-local-patches.test.ts +++ b/ui/scripts/__tests__/shadcn-local-patches.test.ts @@ -143,6 +143,13 @@ interface RegistryFixture { * impossible to do quietly. */ const REGISTRY_FIXTURES: Record = { + 'alert-dialog': { + url: 'https://ui.shadcn.com/r/styles/default/alert-dialog.json', + repoPath: 'apps/v4/public/r/styles/default/alert-dialog.json', + headSha: '8a7701ec27eb9cb8e0377db769fbe6d744113c52', + sha256: '49927179b99719522e455f7326c10d3d324f17fbc4ffd544569e0a94fbb292c7', + roundTrip: true, + }, sheet: { url: 'https://ui.shadcn.com/r/styles/default/sheet.json', repoPath: 'apps/v4/public/r/styles/default/sheet.json', @@ -435,8 +442,9 @@ describe('shadcn local patches — application to fresh upstream (objectstack#55 'dialog-phone-close-touch-target', ]); expect(result.failed[0].found).toBe(0); - // The close-label family is independent of the class list and still lands. - expect(result.applied).toHaveLength(2); + // The close-label family (2) and the dialog surface family (3, + // objectstack#35980) are independent of the Close's class list and still land. + expect(result.applied).toHaveLength(5); expect(result.content).not.toContain('max-sm:size-11'); }); diff --git a/ui/scripts/shadcn-local-patches.mjs b/ui/scripts/shadcn-local-patches.mjs index b7b9483539e..7a8f3cfa8da 100644 --- a/ui/scripts/shadcn-local-patches.mjs +++ b/ui/scripts/shadcn-local-patches.mjs @@ -823,6 +823,71 @@ const tabsTouchTargetPatches = [ }), ]; +/** + * The shared dialog surface (objectstack-ai/objectstack#35980), for `dialog` + * and `alert-dialog`. + * + * Every modal dialog draws one look: a faint overlay with no blur, a white + * card with a hairline edge and a translucent outer ring, and controls one + * step smaller. Upstream draws an 80% black overlay and a `bg-background` + * card with `sm:rounded-lg`; the console used to restyle both with global + * `[role="dialog"]` rules, which also caught every popover and drawer. + * + * The payload stays OUT of `src/ui/`: the classes live in + * `packages/components/src/lib/dialog-surface.ts`. Each primitive gets one + * import and one class token on its overlay and on its content, placed just + * before `className`, so `tailwind-merge` resolves them over upstream's and a + * call site's own classes still win. Every `find` was written from the + * vendored registry bytes (`dialog.registry.txt`, `alert-dialog.registry.txt`). + * + * @param {string} primitive Human-readable primitive name, for messages. + * @param {string} importAnchor The upstream import line the new import follows. + * @returns {LocalPatch[]} + */ +function dialogSurfacePatches(primitive, importAnchor) { + const id = primitive.toLowerCase().replace(/\s+/g, '-'); + const surfaceImport = + 'import { DIALOG_CONTENT_SURFACE, DIALOG_OVERLAY_SURFACE } from "../lib/dialog-surface"'; + const overlayEnd = 'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",\n'; + const contentEnd = 'sm:rounded-lg",\n'; + return [ + { + id: `${id}-surface-import`, + issue: 'objectstack#35980', + reason: `Imports the shared dialog surface classes ${primitive}'s overlay and content append.`, + find: importAnchor, + replace: `${importAnchor}\n${surfaceImport}`, + marker: surfaceImport, + occurrences: 1, + }, + { + id: `${id}-surface-overlay`, + issue: 'objectstack#35980', + reason: + `${primitive}'s overlay takes the shared faint dim in place of upstream's ` + + '80% black. Anchored on the end of the overlay class string, the only ' + + 'string in the file that ends in `fade-in-0`.', + find: overlayEnd, + replace: `${overlayEnd} DIALOG_OVERLAY_SURFACE,\n`, + marker: ' DIALOG_OVERLAY_SURFACE,\n', + occurrences: 1, + }, + { + id: `${id}-surface-content`, + issue: 'objectstack#35980', + reason: + `${primitive}'s content takes the shared card (white, hairline edge, ` + + 'outer ring, 12px corner, compact controls) over upstream\'s ' + + '`bg-background` / `shadow-lg` / `sm:rounded-lg`. Anchored on the end of ' + + 'the content class string.', + find: contentEnd, + replace: `${contentEnd} DIALOG_CONTENT_SURFACE,\n`, + marker: ' DIALOG_CONTENT_SURFACE,\n', + occurrences: 1, + }, + ]; +} + /** * Component name (as tracked in `shadcn-components.json`) → patches it needs. * @@ -830,7 +895,15 @@ const tabsTouchTargetPatches = [ */ export const LOCAL_PATCHES = { sheet: [...i18nCloseLabelPatches('Sheet'), ...sheetHideOverlayPatches, ...sheetCloseTouchTargetPatches], - dialog: [...i18nCloseLabelPatches('Dialog'), ...phoneCloseTouchTargetPatches('Dialog')], + dialog: [ + ...i18nCloseLabelPatches('Dialog'), + ...phoneCloseTouchTargetPatches('Dialog'), + ...dialogSurfacePatches('Dialog', 'import { X } from "lucide-react"'), + ], + 'alert-dialog': dialogSurfacePatches( + 'AlertDialog', + 'import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"', + ), sidebar: [ ...sidebarCookieReadPatches, ...sidebarOptionalContextPatches, From ee705f72a6c67d9e8330b443945b77e06a2798a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:42:54 +0000 Subject: [PATCH 02/11] =?UTF-8?q?feat(ui):=20create=20dialog=20gets=20?= =?UTF-8?q?=E3=80=8CCreate=20more=E3=80=8D,=20a=20=E2=8C=98=E2=86=B5=20sav?= =?UTF-8?q?e=20and=20a=20tighter=20header?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ModalForm draws its title at 16px after the object's icon, trims the dialog's padding to 20px (and drops the stray sm:p-6 gutter the content kept), and saves on ⌘↵ / Ctrl+Enter, which the Save button shows as keycaps. A host that passes createMore gets the footer switch on a create: with it on, a save keeps the dialog open, draws the form again from its opening values and focuses the first field, and onSuccess is told { createMore: true }. The switch is remembered per object in this browser. The console's record dialog offers it, refreshes the list behind and stays where it is instead of leaving for the new record. New label form.createMore in every locale. Claude-Session: https://claude.ai/code/session_01L6bhgWL2r2CuFr34ENybDB Co-authored-by: Claude --- .../app-shell/src/console/AppContent.tsx | 16 +- ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 3 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + ui/packages/plugin-form/src/ModalForm.tsx | 156 ++++++++++++++++-- ui/packages/plugin-form/src/createMore.ts | 114 +++++++++++++ .../plugin-form/src/initialFieldFocus.ts | 2 +- .../plugin-form/src/subformHosts.test.tsx | 4 +- 16 files changed, 287 insertions(+), 18 deletions(-) create mode 100644 ui/packages/plugin-form/src/createMore.ts diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 9e115400ed1..f8b4f11560a 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -1070,13 +1070,22 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = // the drawer over the still-intact list; a heavy one is the detail route. // `replace: true` swaps out the transient `?form=…` entry so Back returns // to the pre-create origin. - const handleRecordFormSuccess = useCallback(async (saved: any) => { + const handleRecordFormSuccess = useCallback(async (saved: any, outcome?: { createMore?: boolean }) => { // Child task (objectstack-ai/objectstack#2604 D3): the parent detail must stay EXACTLY as it was — // active tab, scroll, everything. So do NOT go through crud_success; // the child's open related lists refetch on their own via the // invalidation bus (#2269): the dataSource write already emitted a // MutationEvent that the bridge fans out — no manual notify needed. const feedback = answerWarningClaim.current?.take(saved); + // 「Create more」 (objectstack-ai/objectstack#35980): the dialog stays open + // on an empty form for the next record. Say the save landed and refresh + // the list behind (a child task's related lists refetch on the bus), but + // neither close the form nor leave for the new record. + if (outcome?.createMore) { + toastRecordSave(toast, recordSaveMessage(saved), feedback); + if (!isChildFormTask) setRefreshKey(k => k + 1); + return; + } if (isChildFormTask) { toastRecordSave(toast, recordSaveMessage(saved), feedback); closeRecordForm(); @@ -1758,6 +1767,11 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = : [], onSuccess: handleRecordFormSuccess, onCancel: handleDialogCancel, + // The footer's 「Create more」 switch on a create, for the + // list's 「New」 and a related list's child create alike + // (objectstack-ai/objectstack#35980). ModalForm shows it on a + // create only. + createMore: true, // objectstack-ai/objectstack#26843 — the selected form view's // `buttons`, `layout` and `defaults` over this dialog's own // defaults (`resolveFormViewChrome` states the precedence). A diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index a8662a39b50..71954d3a30a 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -243,6 +243,7 @@ const ar = { noChildObject: "لم يُكوَّن كائن فرعي لهذه اللوحة: عيّن {{property}} إلى الكائن الذي تسرد صفوفه.", }, keepEditing: "متابعة التحرير", + createMore: "إنشاء المزيد", discard: "تجاهل", conflictTitle: "تعارض في الحفظ", conflictMessage: "قام شخص آخر بتغيير هذا السجل أثناء تحريرك. الكتابة فوقه ستستبدل تغييراته بتغييراتك.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index c28730afb03..97b72219858 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -225,6 +225,7 @@ const de = { noChildObject: "Für dieses Panel ist kein untergeordnetes Objekt konfiguriert: Setzen Sie {{property}} auf das Objekt, dessen Zeilen es auflistet.", }, keepEditing: "Weiter bearbeiten", + createMore: "Weitere erstellen", discard: "Verwerfen", conflictTitle: "Speicherkonflikt", conflictMessage: "Dieser Datensatz wurde während Ihrer Bearbeitung von jemand anderem geändert. Beim Überschreiben werden dessen Änderungen durch Ihre ersetzt.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index eb9bc691952..759b1a5c836 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -360,6 +360,9 @@ const en = { noChildObject: 'This panel has no child object configured: set {{property}} to the object whose rows it lists.', }, keepEditing: 'Keep editing', + // The create dialog's 「Create more」 switch (objectstack#35980): on, a save + // keeps the dialog open on an empty form for the next record. + createMore: 'Create more', discard: 'Discard', conflictTitle: 'Save conflict', conflictMessage: 'This record was changed by someone else while you were editing. Overwriting will replace their changes with yours.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 9c4f0fea8ed..5d0674cca6a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -233,6 +233,7 @@ const es = { noChildObject: "Este panel no tiene configurado ningún objeto secundario: establezca {{property}} en el objeto cuyas filas enumera.", }, keepEditing: "Seguir editando", + createMore: "Crear más", discard: "Descartar", conflictTitle: "Conflicto al guardar", conflictMessage: "Otra persona modificó este registro mientras lo editaba. Sobrescribir reemplazará sus cambios por los suyos.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 194ec44f701..c4550c2b40c 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -228,6 +228,7 @@ const fr = { noChildObject: "Aucun objet enfant n'est configuré pour ce panneau : définissez {{property}} sur l'objet dont il liste les lignes.", }, keepEditing: "Continuer l'édition", + createMore: "Créer d'autres", discard: "Abandonner", conflictTitle: "Conflit d'enregistrement", conflictMessage: "Cet enregistrement a été modifié par quelqu'un d'autre pendant votre édition. L'écrasement remplacera ses modifications par les vôtres.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 77546734323..f878c833618 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -225,6 +225,7 @@ const ja = { noChildObject: "このパネルには子オブジェクトが設定されていません。{{property}} に、行を一覧表示するオブジェクトを設定してください。", }, keepEditing: "編集を続ける", + createMore: "続けて作成", discard: "破棄", conflictTitle: "保存の競合", conflictMessage: "編集中にこのレコードが他のユーザーによって変更されました。上書きすると、相手の変更はあなたの内容で置き換えられます。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index cf92773dbd9..557ae09c402 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -225,6 +225,7 @@ const ko = { noChildObject: "이 패널에 하위 개체가 구성되지 않았습니다. {{property}}을(를) 행을 나열할 개체로 설정하세요.", }, keepEditing: "계속 편집", + createMore: "계속 만들기", discard: "버리기", conflictTitle: "저장 충돌", conflictMessage: "편집하는 동안 다른 사용자가 이 레코드를 변경했습니다. 덮어쓰면 상대방의 변경 내용이 내 내용으로 대체됩니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 2cc6ae0e496..ea8c460bf8c 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -228,6 +228,7 @@ const pt = { noChildObject: "Este painel não tem nenhum objeto filho configurado: defina {{property}} como o objeto cujas linhas ele lista.", }, keepEditing: "Continuar editando", + createMore: "Criar mais", discard: "Descartar", conflictTitle: "Conflito ao salvar", conflictMessage: "Outra pessoa alterou este registro enquanto você editava. Sobrescrever substituirá as alterações dela pelas suas.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 73e8aaa2b9c..f317b07b298 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -234,6 +234,7 @@ const ru = { noChildObject: "Для этой панели не настроен дочерний объект: укажите в {{property}} объект, строки которого она выводит.", }, keepEditing: "Продолжить редактирование", + createMore: "Создать ещё", discard: "Отменить", conflictTitle: "Конфликт сохранения", conflictMessage: "Пока вы редактировали, эту запись изменил другой пользователь. Перезапись заменит его изменения вашими.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index ea8cb5bffb2..f89c6b6bd41 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -237,6 +237,7 @@ const zh = { noChildObject: '此面板未配置子对象:请将 {{property}} 设为其所列行所属的对象。', }, keepEditing: '继续编辑', + createMore: '连续创建', discard: '放弃', conflictTitle: '保存冲突', conflictMessage: '您编辑期间,这条记录已被其他人修改。覆盖保存将用您的内容替换对方的修改。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 73654cf2632..dc0c8e0027d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -237,6 +237,7 @@ const zhHant = { noChildObject: '此面板未配置子物件:請將 {{property}} 設為其所列行所屬的物件。', }, keepEditing: '繼續編輯', + createMore: '連續建立', discard: '放棄', conflictTitle: '儲存衝突', conflictMessage: '您編輯期間,這條記錄已被其他人修改。覆蓋儲存將用您的內容替換對方的修改。', diff --git a/ui/packages/plugin-form/src/ModalForm.tsx b/ui/packages/plugin-form/src/ModalForm.tsx index a670c018891..69c9162340c 100644 --- a/ui/packages/plugin-form/src/ModalForm.tsx +++ b/ui/packages/plugin-form/src/ModalForm.tsx @@ -36,6 +36,8 @@ import { RecordTopBarButton, toast, FormSectionNavContext, + Switch, + resolveIcon, } from '@object-ui/components'; import { Loader2, Maximize2, Minimize2 } from 'lucide-react'; import { MasterDetailForm } from './MasterDetailForm'; @@ -87,10 +89,11 @@ import { import { hasInlineFieldSource, noSubmitTargetError } from './submitTarget'; import { useRecordInvalidation } from './recordInvalidation'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; -import { useInitialFieldFocus } from './initialFieldFocus'; +import { focusFirstEditableField, useInitialFieldFocus } from './initialFieldFocus'; import { FormSectionNav, useFormSectionNav } from './FormSectionNav'; import { FormDirtyReportContext } from './formDirtyReport'; import { useModalFormMaximized } from './modalMaximize'; +import { isSubmitShortcut, submitShortcutLabel, useModalFormCreateMore } from './createMore'; // Localized strings for the unsaved-changes guard and, since objectui#11039, // the form's own chrome (the default submit and cancel labels and the @@ -125,6 +128,8 @@ const useDiscardTranslation = createSafeTranslation( // keys and labels (objectstack-ai/objectstack#34604). 'detail.maximize': 'Maximize', 'detail.restoreSize': 'Restore size', + // The create dialog's 「Create more」 switch (objectstack-ai/objectstack#35980). + 'form.createMore': 'Create more', }, 'form.discardTitle', ); @@ -266,9 +271,27 @@ export interface ModalFormSchema { */ submitHandler?: ObjectFormSchema['submitHandler']; - onSuccess?: (data: any) => void | Promise; + /** + * Called with the saved record. `outcome.createMore` is `true` when the + * dialog stays open for the next record (the 「Create more」 switch, + * {@link ModalFormSchema.createMore}): the host refreshes what lists the + * record and stays where it is, instead of closing or leaving for the new + * record. + */ + onSuccess?: (data: any, outcome?: { createMore?: boolean }) => void | Promise; onError?: (error: Error) => void; onCancel?: () => void; + /** + * Offer the 「Create more」 switch in a `create` dialog's footer + * (objectstack-ai/objectstack#35980). On, a successful save keeps the dialog + * open: the form is drawn again from its opening values, focus returns to + * the first field, and `onSuccess` is told so. The switch is remembered per + * object in this browser. Off by default: a host offers it where creating + * several records in a row makes sense (a list's 「New」), and not where the + * create returns a record to its caller (a lookup's inline 「+ New」). + * Ignored by the master-detail arm, whose form owns its own Save bar. + */ + createMore?: boolean; className?: string; /** Inline child collections — renders the modal as an atomic master-detail * form. Each entry needs only `childObject` (FK + columns derived). */ @@ -526,6 +549,15 @@ const ModalFormBody: React.FC = ({ // column count — reads that effective size. const { maximized, toggleMaximized } = useModalFormMaximized(schema.objectName); + // The 「Create more」 switch (objectstack-ai/objectstack#35980): offered on + // a create dialog whose host asked for it, remembered per object. A save + // with it on draws the form again (`formResetKey`) instead of closing. + const createMoreOffered = schema.createMore === true && schema.mode === 'create'; + const { createMore, setCreateMore } = useModalFormCreateMore(schema.objectName); + const createMoreOn = createMoreOffered && createMore; + const [formResetKey, setFormResetKey] = useState(0); + const contentRef = useRef(null); + // 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 @@ -770,6 +802,29 @@ const ModalFormBody: React.FC = ({ endLoading(); }, [objectSchema, schema.fields, schema.customFields, schema.sections, schema.readOnly, schema.mode, dataSource]); + // 「Create more」 (objectstack-ai/objectstack#35980): after a save that keeps + // the dialog open, draw the form again from its opening values — a new + // `formResetKey` remounts the form renderer, so every typed value and the + // dirty state go with it — and put focus back on the first field. + const startNextRecord = useCallback(() => { + setIsDirty(false); + setFormResetKey((k) => k + 1); + }, []); + useEffect(() => { + if (formResetKey === 0) return; + // The remounted form draws its fields on a later frame (lazy widgets), so + // keep trying for a short while until the first field takes focus. + let tries = 0; + let frame = 0; + const attempt = () => { + const content = contentRef.current; + if (content && focusFirstEditableField(content)) return; + if (++tries < 30) frame = window.requestAnimationFrame(attempt); + }; + frame = window.requestAnimationFrame(attempt); + return () => window.cancelAnimationFrame(frame); + }, [formResetKey]); + // Handle form submission const handleSubmit = useCallback(async (data: Record) => { // An upload is still in flight (objectui#10166). Saving now writes the @@ -790,6 +845,11 @@ const ModalFormBody: React.FC = ({ // adapter-less submit, bypassing a declared host seam and persisting // nothing (objectui#6300). See `submitTarget.ts` for the whole rule. if (!dataSource && !schema.submitHandler && hasInlineFieldSource(schema)) { + if (createMoreOn) { + await schema.onSuccess?.(data, { createMore: true }); + startNextRecord(); + return data; + } if (schema.onSuccess) { await schema.onSuccess(data); } @@ -864,6 +924,13 @@ const ModalFormBody: React.FC = ({ // bus change held while it was dirty (its own write's echo included) is // replayed now rather than behind input that is no longer unsaved. recordSaved(); + // 「Create more」 (objectstack-ai/objectstack#35980): the record is + // made, and the dialog stays for the next one. + if (createMoreOn) { + await schema.onSuccess?.(result, { createMore: true }); + startNextRecord(); + return result; + } if (schema.onSuccess) { await schema.onSuccess(result); } @@ -878,7 +945,7 @@ const ModalFormBody: React.FC = ({ } finally { setIsSubmitting(false); } - }, [schema, dataSource, objectSchema, perms, saveWithOcc, formData, uploadGate.uploading, uploadGate.reason, recordSaved]); + }, [schema, dataSource, objectSchema, perms, saveWithOcc, formData, uploadGate.uploading, uploadGate.reason, recordSaved, createMoreOn, startNextRecord]); // Actually close the modal, firing onCancel only when the close originated // from the explicit Cancel button. @@ -1269,7 +1336,39 @@ const ModalFormBody: React.FC = ({ // 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'; + const headerClass = 'shrink-0 px-4 pt-4 sm:px-5 sm:pr-20 pb-3'; + + // The title (objectstack-ai/objectstack#35980): 16px, after the object's + // own icon when it declares one, in both arms. + // `resolveIcon` caches one component per name, so this is no hook. + const ObjectIconGlyph = resolveIcon((objectSchema as any)?.icon); + const dialogTitle = schema.title ? ( + + {ObjectIconGlyph && ( + + ) : null; + + // ⌘↵ / Ctrl+Enter saves (objectstack-ai/objectstack#35980), the shortcut the + // Save button shows. Only a keydown inside this dialog's own DOM: the + // discard and conflict alerts are React children, so their keydowns bubble + // here through React, but they are portalled outside the content. + const handleContentKeyDown = (event: React.KeyboardEvent) => { + if (!isSubmitShortcut({ ...event, isComposing: event.nativeEvent.isComposing })) return; + if (!event.currentTarget.contains(event.target as Node)) return; + if (!showSubmit || isSubmitting || uploadGate.uploading) return; + const form = event.currentTarget.ownerDocument.getElementById(formId); + if (!(form instanceof HTMLFormElement)) return; + event.preventDefault(); + event.stopPropagation(); + form.requestSubmit(); + }; // Unsaved-changes guard — rendered INSIDE DialogContent so its portal // inherits the Dialog's Radix layer context (focus scope + dismissable @@ -1315,12 +1414,12 @@ const ModalFormBody: React.FC = ({ showCloseButton={showCloseButton} onOpenAutoFocus={initialFieldFocus.onOpenAutoFocus} onCloseAutoFocus={initialFieldFocus.onCloseAutoFocus} - className={cn(sizeClass, 'flex flex-col overflow-hidden p-0', heightClass, className, schema.className)} + className={cn(sizeClass, 'flex flex-col overflow-hidden p-0 sm:p-0', heightClass, className, schema.className)} data-maximized={maximized ? '' : undefined} > {(schema.title || schema.description) && ( - {schema.title && {schema.title}} + {dialogTitle} {schema.description ? ( {schema.description} ) : ( @@ -1383,15 +1482,17 @@ const ModalFormBody: React.FC = ({ return ( {(schema.title || schema.description) && ( - {schema.title && {schema.title}} + {dialogTitle} {schema.description ? ( {schema.description} ) : ( @@ -1409,7 +1510,7 @@ const ModalFormBody: React.FC = ({ their containing block, so it clips them and they scroll with it, instead of overflowing the `overflow-hidden` dialog box, which a scroll could then move off its title and footer (objectstack#35092). */} -
+
{/* Every upload widget below reports into this scope, however deep — a section, a tab, a subform row (objectui#10166). */} @@ -1417,7 +1518,9 @@ const ModalFormBody: React.FC = ({ {/* The dialog owns its body's wait (objectui#12559) — see `ModalFormBodyPending`. */} }> - {renderContent()} + {/* A new key after a 「Create more」 save draws the form again + from its opening values (objectstack-ai/objectstack#35980). */} + {renderContent()}
@@ -1425,12 +1528,25 @@ const ModalFormBody: React.FC = ({ {/* Sticky footer — always visible action buttons */} {hasFooter && ( -
+
{/* The REASON the Save below is disabled (objectui#10166). Above the row rather than inside it so it reads before the dead control, and so a long sentence never squeezes the buttons. */} -
+
+ {/* 「Create more」 (objectstack-ai/objectstack#35980): at the + footer's start, away from the buttons. */} + {createMoreOffered && showSubmit && ( + + )} {showCancel && ( )}
@@ -1488,8 +1614,10 @@ const ModalFormBody: React.FC = ({ * action bar the flat arm's footer padding. */ const MODAL_MASTER_DETAIL_FRAME: MasterDetailFrame = { - bodyClassName: '@container px-4 sm:px-6 py-4', - actionsClassName: 'px-4 sm:px-6 py-3', + bodyClassName: '@container px-4 sm:px-5 py-4', + // The card's own colour (objectstack-ai/objectstack#35980): the bar's + // `bg-background` is the page's grey, a strip on the dialog's white card. + actionsClassName: 'bg-card px-4 sm:px-5 py-3', }; /** diff --git a/ui/packages/plugin-form/src/createMore.ts b/ui/packages/plugin-form/src/createMore.ts new file mode 100644 index 00000000000..3552688fe6b --- /dev/null +++ b/ui/packages/plugin-form/src/createMore.ts @@ -0,0 +1,114 @@ +/** + * 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 create dialog's 「Create more」 switch and its save shortcut + * (objectstack-ai/objectstack#35980). + * + * Package-internal: `ModalForm` is its only reader, and neither `index.tsx` + * nor `core.ts` re-exports it. + * + * With the switch on, a successful create keeps the dialog open: the form is + * drawn again from its opening values, focus returns to the first field, and + * the host learns the dialog stays (`onSuccess`'s `{ createMore: true }`), so + * it refreshes the list behind instead of leaving for the new record. + * + * The switch is a per-object PREFERENCE (ui AGENTS.md #8), the way the + * maximize switch is (`modalMaximize.ts`): one object's create dialog reopens + * with the switch as the user last left it, in this browser. It lives in + * `localStorage` under {@link modalFormCreateMoreStorageKey}; every access is + * guarded, so a private window or a blocked store reads as "off" 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 create dialog has 「Create more」 on. */ +export function modalFormCreateMoreStorageKey(objectName: string): string { + return `modal-form-create-more:${objectName}`; +} + +/** Whether `objectName`'s create dialog was last left with 「Create more」 on; `false` when nothing is stored or storage is out of reach. */ +export function readModalFormCreateMore(objectName: string): boolean { + if (!objectName || typeof window === 'undefined') return false; + try { + return window.localStorage.getItem(modalFormCreateMoreStorageKey(objectName)) === '1'; + } catch { + return false; + } +} + +/** Remember the choice for `objectName`. Turning it off removes the entry, so the stored default stays "off". */ +export function writeModalFormCreateMore(objectName: string, on: boolean): void { + if (!objectName || typeof window === 'undefined') return; + try { + const key = modalFormCreateMoreStorageKey(objectName); + if (on) 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 switch's state for `objectName`: seeded from the remembered choice, + * re-read when the dialog is handed another object, written back on change. + */ +export function useModalFormCreateMore(objectName: string): { + createMore: boolean; + setCreateMore: (on: boolean) => void; +} { + const [state, setState] = useState(() => ({ + objectName, + createMore: readModalFormCreateMore(objectName), + })); + let current = state; + if (state.objectName !== objectName) { + current = { objectName, createMore: readModalFormCreateMore(objectName) }; + setState(current); + } + const setCreateMore = (on: boolean) => { + writeModalFormCreateMore(objectName, on); + setState({ objectName, createMore: on }); + }; + return { createMore: current.createMore, setCreateMore }; +} + +/** + * Whether a keydown is the dialog's save shortcut: ⌘↵ on Apple platforms, + * Ctrl+Enter elsewhere — either modifier is accepted on every platform, as + * neither means anything else in a form. Shift and Alt keep their own + * meanings, and a keydown that ends an IME composition is the composition's. + */ +export function isSubmitShortcut(event: { + key: string; + metaKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; + altKey: boolean; + isComposing?: boolean; +}): boolean { + if (event.key !== 'Enter' || event.isComposing) return false; + if (event.shiftKey || event.altKey) return false; + return event.metaKey || event.ctrlKey; +} + +/** Whether this browser runs on an Apple platform, where the save shortcut reads ⌘↵. */ +export function isApplePlatform(): boolean { + if (typeof navigator === 'undefined') return false; + const platform = + (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ?? + navigator.platform ?? + ''; + return /mac|iphone|ipad|ipod/i.test(platform); +} + +/** The keycap text the save button shows: `⌘↵` on Apple platforms, `Ctrl ↵` elsewhere. */ +export function submitShortcutLabel(): string { + return isApplePlatform() ? '⌘↵' : 'Ctrl ↵'; +} diff --git a/ui/packages/plugin-form/src/initialFieldFocus.ts b/ui/packages/plugin-form/src/initialFieldFocus.ts index 29cfb98039b..e2e1840b681 100644 --- a/ui/packages/plugin-form/src/initialFieldFocus.ts +++ b/ui/packages/plugin-form/src/initialFieldFocus.ts @@ -75,7 +75,7 @@ export function findFirstEditableField(root: ParentNode): HTMLElement | null { * with `display: none`) refuses focus in a browser, and the caller keeps * waiting instead of reading that as done. */ -function focusFirstEditableField(root: HTMLElement): boolean { +export function focusFirstEditableField(root: HTMLElement): boolean { const control = findFirstEditableField(root); if (!control) return false; control.focus({ preventScroll: true }); diff --git a/ui/packages/plugin-form/src/subformHosts.test.tsx b/ui/packages/plugin-form/src/subformHosts.test.tsx index 925d28be197..7ae57272a88 100644 --- a/ui/packages/plugin-form/src/subformHosts.test.tsx +++ b/ui/packages/plugin-form/src/subformHosts.test.tsx @@ -178,7 +178,7 @@ describe('master-detail Save bar sits at the record dialog bottom (objectstack#3 expect(has(bar, 'sticky')).toBe(false); expect(has(bar, 'bottom-0')).toBe(false); expect(bar.getAttribute('class') ?? '').not.toMatch(/(^|\s)after:/); - expect(has(bar, 'shrink-0', 'border-t', 'bg-background', 'px-4', 'sm:px-6', 'py-3')).toBe(true); + expect(has(bar, 'shrink-0', 'border-t', 'bg-card', 'px-4', 'sm:px-5', 'py-3')).toBe(true); // Nothing between the bar and the dialog scrolls: the body's scroller is // the bar's sibling, so the bar is outside the scrolled content. @@ -187,7 +187,7 @@ describe('master-detail Save bar sits at the record dialog bottom (objectstack#3 } expect(body.contains(bar)).toBe(false); expect(body.nextElementSibling).toBe(bar); - expect(has(body, 'min-h-0', 'flex-1', 'overflow-y-auto', '@container', 'px-4', 'sm:px-6', 'py-4')).toBe(true); + expect(has(body, 'min-h-0', 'flex-1', 'overflow-y-auto', '@container', 'px-4', 'sm:px-5', 'py-4')).toBe(true); expect(body.querySelector('form')).not.toBeNull(); // The form's root fills the dialog's frame, which fills the dialog below From 3612541e1b690c8f22c1791c0cc8ab890ceb17b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:10:17 +0000 Subject: [PATCH 03/11] feat(ui): a short dialog that declares no columns is one column in the lg size Up to eight fields, and no columns declared on the form or any section: the dialog draws one field per row in the narrow lg size (672px). This reverses, for such a dialog, the two-column floor of objectui#12521 / #34607 and the two-per-row effect ruling 6204264665 had on its undeclared sections. Nine fields or more, any declared columns, an authored modalSize or a maximized dialog keep the earlier layout. Claude-Session: https://claude.ai/code/session_01L6bhgWL2r2CuFr34ENybDB Co-authored-by: Claude --- .../plugin-form/src/FormSectionNav.test.tsx | 2 +- ui/packages/plugin-form/src/ModalForm.tsx | 23 +++++- .../dialogContainerColumns-34607.test.tsx | 81 ++++++++++++++++++- .../dialogDefaultLayout-12521.test.tsx | 14 +++- ui/packages/plugin-form/src/autoLayout.ts | 41 +++++++++- .../src/fieldGroupSections.test.tsx | 8 +- .../plugin-form/src/modalFieldGroups.test.tsx | 5 +- 7 files changed, 157 insertions(+), 17 deletions(-) diff --git a/ui/packages/plugin-form/src/FormSectionNav.test.tsx b/ui/packages/plugin-form/src/FormSectionNav.test.tsx index e2d7591aeae..536f51e7a6b 100644 --- a/ui/packages/plugin-form/src/FormSectionNav.test.tsx +++ b/ui/packages/plugin-form/src/FormSectionNav.test.tsx @@ -572,7 +572,7 @@ describe('FormSectionNav is a jump bar: hidden when the sections fit, a click ma renderModal(); await waitFor(() => expect(nav()).not.toBeNull()); // With the bar drawn, the bar is the separator under the header. - expect(header().classList.contains('border-b')).toBe(false); + await waitFor(() => expect(header().classList.contains('border-b')).toBe(false)); sizeScroller(600, 420); resized(); diff --git a/ui/packages/plugin-form/src/ModalForm.tsx b/ui/packages/plugin-form/src/ModalForm.tsx index 69c9162340c..79647f9d934 100644 --- a/ui/packages/plugin-form/src/ModalForm.tsx +++ b/ui/packages/plugin-form/src/ModalForm.tsx @@ -55,6 +55,7 @@ import { inferColumns, inferModalSize, dialogUndeclaredColumns, + dialogDrawsSingleColumn, sectionedFormColumns, sectionedGridLayout, CONTAINER_GRID_COLS, @@ -346,7 +347,9 @@ const modalSizeClasses: Record = { /** * The least grid the dialog draws where the author declared no `columns` * (objectui#12521): two from the container's `@md` tier up, one below it, so - * the phone sheet keeps its single column. A field-heavy form draws more — + * the phone sheet keeps its single column — except in a short dialog that + * declares nothing, which draws one column in the narrow `lg` size + * (`dialogDrawsSingleColumn`, objectstack-ai/objectstack#35980). A field-heavy form draws more — * three in a bounded dialog, four in a `full` one — by * `dialogUndeclaredColumns` (objectstack-ai/objectstack#34607), whose * docblock carries the rule and the measured tier. @@ -565,19 +568,31 @@ const ModalFormBody: React.FC = ({ // undeclared grid is at least `DIALOG_DEFAULT_COLUMNS` wide whatever the // size, so the size reads that floor and never the count it then bounds // (objectstack-ai/objectstack#34607). + // objectstack-ai/objectstack#35980 — at most eight fields and no declared + // `columns` anywhere: one per row, in the narrow `lg` dialog. Maximized, + // the user asked for the room, and the form spreads as it did before. + const singleColumn = !maximized && dialogDrawsSingleColumn( + layoutFieldCount, + schema.columns, + (effectiveSections ?? []).map((s) => s.columns), + ); const effectiveModalSize = useMemo(() => { if (maximized) return 'full'; if (schema.modalSize) return schema.modalSize; + // A short dialog that declares no columns anywhere is one column in the + // narrow `lg` size (objectstack-ai/objectstack#35980). + if (singleColumn) return inferModalSize(1); 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))); - }, [maximized, schema.modalSize, schema.columns, effectiveSections, layoutFieldCount]); + }, [maximized, schema.modalSize, schema.columns, effectiveSections, layoutFieldCount, singleColumn]); // The count an undeclared form or section draws in THIS dialog // (objectstack-ai/objectstack#34607): from the field count, bounded by the - // dialog's size — `dialogUndeclaredColumns`. - const undeclaredColumns = dialogUndeclaredColumns(layoutFieldCount, effectiveModalSize); + // dialog's size — `dialogUndeclaredColumns` — and one in a short dialog + // that declares nothing (`dialogDrawsSingleColumn`, #35980). + const undeclaredColumns = singleColumn ? 1 : dialogUndeclaredColumns(layoutFieldCount, effectiveModalSize); // Compute auto-layout for flat fields (no sections). A form that declares no // `columns` lays out at the dialog's undeclared count through the same diff --git a/ui/packages/plugin-form/src/__tests__/dialogContainerColumns-34607.test.tsx b/ui/packages/plugin-form/src/__tests__/dialogContainerColumns-34607.test.tsx index e9d90ab6569..4f3d26fc75e 100644 --- a/ui/packages/plugin-form/src/__tests__/dialogContainerColumns-34607.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/dialogContainerColumns-34607.test.tsx @@ -33,7 +33,9 @@ import '@object-ui/components'; import { ModalForm } from '../ModalForm'; import { ObjectForm } from '../ObjectForm'; import { + dialogDrawsSingleColumn, dialogUndeclaredColumns, + DIALOG_SINGLE_COLUMN_MAX_FIELDS, sectionedGridLayout, UNDECLARED_SECTION_COLUMNS, } from '../autoLayout'; @@ -214,10 +216,11 @@ describe('#34607 — undeclared sections and field groups in the dialog take the expect(ladder('notes')).toEqual([1, 1, 1]); }); - it('a light form keeps the two-wide floor in the same xl dialog', async () => { + it('a light form that declares nothing is one column in the lg dialog (#35980)', async () => { const dialog = await openDialog(FIVE); - expect(dialog.className).toContain('sm:max-w-5xl'); - expect(ladder('f0')).toEqual([2, 2, 2]); + expect(dialog.className).toContain('sm:max-w-2xl'); + expect(dialog.className).not.toContain('sm:max-w-5xl'); + expect(ladder('f0')).toEqual([1, 1, 1]); }); }); @@ -252,3 +255,75 @@ describe('#34607 dialogUndeclaredColumns', () => { expect(dialogUndeclaredColumns(16, 'lg')).toBe(3); }); }); + +/** + * objectstack-ai/objectstack#35980 — a short dialog that declares nothing is + * one column in the narrow `lg` size; past eight fields, or with any declared + * `columns`, the dialog is as #34607 left it. + */ +describe('#35980 — up to eight fields and nothing declared: one column, lg', () => { + const EIGHT = { + name: 'thing', + fields: Object.fromEntries(PLAIN.slice(0, 8).map((n) => [n, { type: 'text', label: `Field ${n}` }])), + }; + const NINE = { + name: 'thing', + fields: Object.fromEntries(PLAIN.slice(0, 9).map((n) => [n, { type: 'text', label: `Field ${n}` }])), + }; + + it('the predicate: count, form columns and every section columns', () => { + expect(DIALOG_SINGLE_COLUMN_MAX_FIELDS).toBe(8); + expect([0, 1, 5, 8].map((n) => dialogDrawsSingleColumn(n, undefined))).toEqual([true, true, true, true]); + expect(dialogDrawsSingleColumn(9, undefined)).toBe(false); + expect(dialogDrawsSingleColumn(5, 2)).toBe(false); + expect(dialogDrawsSingleColumn(5, 1)).toBe(false); + expect(dialogDrawsSingleColumn(5, undefined, [undefined, undefined])).toBe(true); + expect(dialogDrawsSingleColumn(5, undefined, [undefined, 3])).toBe(false); + }); + + it('eight flat fields: one per row in the lg dialog', async () => { + const dialog = await openDialog(EIGHT); + expect(dialog.className).toContain('sm:max-w-2xl'); + expect(ladder('f0')).toEqual([1, 1, 1]); + }); + + it('nine flat fields: the wide dialog and its grid, as before', async () => { + const dialog = await openDialog(NINE); + expect(dialog.className).toContain('sm:max-w-5xl'); + expect(ladder('f0')).toEqual([2, 3, 3]); + }); + + it('undeclared sections of eight fields in all: one per row too', async () => { + const dialog = await openDialog(EIGHT, { + sections: [ + { name: 'a', label: 'A', fields: PLAIN.slice(0, 4) }, + { name: 'b', label: 'B', fields: PLAIN.slice(4, 8) }, + ], + }); + expect(dialog.className).toContain('sm:max-w-2xl'); + expect(ladder('f0')).toEqual([1, 1, 1]); + expect(ladder('f4')).toEqual([1, 1, 1]); + }); + + it('a declared form columns is drawn as written, in the size it drew before', async () => { + const dialog = await openDialog(FIVE, { columns: 2 }); + expect(dialog.className).toContain('sm:max-w-5xl'); + expect(ladder('f0')).toEqual([2, 2, 2]); + }); + + it('one declared section keeps the dialog as it was: its neighbour draws two', async () => { + const dialog = await openDialog(EIGHT, { + sections: [ + { name: 'a', label: 'A', fields: PLAIN.slice(0, 5) }, + { name: 'b', label: 'B', columns: 3, fields: PLAIN.slice(5, 8) }, + ], + }); + expect(dialog.className).toContain('sm:max-w-5xl'); + expect(ladder('f0')).toEqual([2, 2, 2]); + }); + + it('an authored modalSize wins over the narrow size', async () => { + const dialog = await openDialog(FIVE, { modalSize: 'xl' }); + expect(dialog.className).toContain('sm:max-w-5xl'); + }); +}); diff --git a/ui/packages/plugin-form/src/__tests__/dialogDefaultLayout-12521.test.tsx b/ui/packages/plugin-form/src/__tests__/dialogDefaultLayout-12521.test.tsx index d4f69b6937a..fe5f4587a04 100644 --- a/ui/packages/plugin-form/src/__tests__/dialogDefaultLayout-12521.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/dialogDefaultLayout-12521.test.tsx @@ -155,7 +155,9 @@ describe('a dialog with no authored layout (objectui#12521)', () => { it('a short form gets the lg bound, not a dialog wider than its fields', async () => { const { dialog, grid } = await openDialog(TWO); expect(dialog.className).toContain('sm:max-w-2xl'); - expect(grid?.className).toBe(DEFAULT_GRID); + // objectstack-ai/objectstack#35980: at most eight fields and nothing + // declared is one column — no grid tiers (it was DEFAULT_GRID before). + expect(grid).toBeNull(); }); it('below sm the grid is one column, and the dialog is still the phone sheet', async () => { @@ -213,10 +215,16 @@ describe('an authored layout is used as written (objectui#12521)', () => { }); it("a field's authored span: 'full' takes the row in the default grid", async () => { + // Nine fields: past the one-column dialog (objectstack-ai/objectstack#35980), + // so the undeclared grid is drawn, three wide. const { spanOf } = await openDialog(TWELVE, { - sections: [{ name: 'a', label: 'A', fields: [{ field: 'name', span: 'full' }, 'code', 'email'] }], + sections: [{ + name: 'a', + label: 'A', + fields: [{ field: 'name', span: 'full' }, 'code', 'email', 'phone', 'website', 'status', 'stage', 'source', 'amount'], + }], }); - expect(spanOf('name')).toEqual(['@md:col-span-2']); + expect(spanOf('name')).toEqual(WIDE_ON_THREE); expect(spanOf('code')).toEqual([]); }); diff --git a/ui/packages/plugin-form/src/autoLayout.ts b/ui/packages/plugin-form/src/autoLayout.ts index 808ab16b389..1ac91da5803 100644 --- a/ui/packages/plugin-form/src/autoLayout.ts +++ b/ui/packages/plugin-form/src/autoLayout.ts @@ -591,6 +591,41 @@ export function inferModalSize(columns: number): 'sm' | 'default' | 'lg' | 'xl' return 'xl'; } +/** + * The most fields a dialog lays out in ONE column (objectstack-ai/objectstack#35980). + * See {@link dialogDrawsSingleColumn}. + */ +export const DIALOG_SINGLE_COLUMN_MAX_FIELDS = 8; + +/** + * Whether a dialog draws its fields one per row in the narrow `lg` size + * (objectstack-ai/objectstack#35980): it lays out at most + * {@link DIALOG_SINGLE_COLUMN_MAX_FIELDS} fields, and NOTHING in it declares + * `columns` — not the form, and no section. A short create or edit form then + * reads top to bottom, the way a list's 「New」 dialog is filled in. + * + * This reverses, for such a dialog, the floor of two its undeclared grid drew + * (objectui#12521, objectstack-ai/objectstack#34607) and the two-per-row + * effect the section-`columns` fork (ruled 6204264665) had on its undeclared + * sections: the maintainer approved 「字段少的用单列」 when the card was filed. + * One declared count anywhere keeps the dialog as it was — the declared count + * is drawn as written, the dialog is as wide as it needs, and an undeclared + * section beside it keeps {@link dialogUndeclaredColumns}. + * + * @param fieldCount The number of fields the dialog lays out. + * @param formColumns The form's authored `columns`. + * @param sectionColumns Each section's authored `columns` (empty for a flat form). + */ +export function dialogDrawsSingleColumn( + fieldCount: number, + formColumns: unknown, + sectionColumns: ReadonlyArray = [], +): boolean { + if (fieldCount > DIALOG_SINGLE_COLUMN_MAX_FIELDS) return false; + if (declaredColumns(formColumns) !== undefined) return false; + return sectionColumns.every((c) => declaredColumns(c) === undefined); +} + /** * How many fields per row a DIALOG draws where its author declared no * `columns` — on the form, and for a section on that section too @@ -602,8 +637,10 @@ export function inferModalSize(columns: number): 'sm' | 'default' | 'lg' | 'xl' * field-heavy business form spreads across a wide dialog while a light one is * never thinned out — with two bounds: * - * - FLOOR two: the dialog's earlier fixed default (objectui#12521), so a form - * of up to eight fields draws exactly what it drew before. + * - FLOOR two: the dialog's earlier fixed default (objectui#12521). A dialog + * that declares nothing and lays out at most eight fields never reaches + * this count: it draws one column ({@link dialogDrawsSingleColumn}, + * objectstack-ai/objectstack#35980). * - CAP by the dialog's size: three in a bounded dialog, four only in a * `full` one. The grid's tiers are container queries * ({@link CONTAINER_GRID_COLS}), and the bounded `xl` dialog's field diff --git a/ui/packages/plugin-form/src/fieldGroupSections.test.tsx b/ui/packages/plugin-form/src/fieldGroupSections.test.tsx index 529397efac2..22de21acddb 100644 --- a/ui/packages/plugin-form/src/fieldGroupSections.test.tsx +++ b/ui/packages/plugin-form/src/fieldGroupSections.test.tsx @@ -119,8 +119,12 @@ describe.each(CONTAINERS)('%s — fieldGroups fallback (#4774)', (_name, Contain expect(forms[0].querySelectorAll('input').length).toBe(4); // The flat path's column inference survives the upgrade: 4 fields → a - // 2-column container grid, not a single-column stack. - expect(forms[0].querySelector('[class*="@md:grid-cols-2"]')).not.toBeNull(); + // 2-column container grid, not a single-column stack — except in the + // dialog, which draws four undeclared fields one per row + // (objectstack-ai/objectstack#35980). + const twoWide = forms[0].querySelector('[class*="@md:grid-cols-2"]'); + if (formType === 'modal') expect(twoWide).toBeNull(); + else expect(twoWide).not.toBeNull(); }); it('submits values from EVERY group in one create() payload', async () => { diff --git a/ui/packages/plugin-form/src/modalFieldGroups.test.tsx b/ui/packages/plugin-form/src/modalFieldGroups.test.tsx index 53ae06d7ce5..f4fed505262 100644 --- a/ui/packages/plugin-form/src/modalFieldGroups.test.tsx +++ b/ui/packages/plugin-form/src/modalFieldGroups.test.tsx @@ -89,8 +89,9 @@ describe('ModalForm fieldGroups fallback', () => { expect(forms[0].textContent).toContain('Tracking Info'); expect(forms[0].querySelectorAll('input').length).toBe(4); - // 4 input fields → 2-column auto-layout threaded onto the field container. - expect(forms[0].querySelector('[class*="@md:grid-cols-2"]')).not.toBeNull(); + // 4 input fields and no declared columns → one per row + // (objectstack-ai/objectstack#35980; it was a 2-column grid before). + expect(forms[0].querySelector('[class*="@md:grid-cols-2"]')).toBeNull(); }); it('submits values from EVERY group in a single create() payload', async () => { From 590414cc9410075155a175193a5b177b70720d0e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:23:33 +0000 Subject: [PATCH 04/11] =?UTF-8?q?test(ui):=20pin=20=E3=80=8CCreate=20more?= =?UTF-8?q?=E3=80=8D,=20the=20save=20shortcut,=20the=20title=20icon=20and?= =?UTF-8?q?=20the=20console's=20stay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ModalForm: the switch is offered only on a host-requested create, a save with it on keeps the dialog, empties the form, focuses the first field and saves again, the choice is remembered per object, ⌘↵ and Ctrl+Enter save while Shift/Alt chords do not, the Save button names the shortcut, and the title follows the object's icon. AppContent: a save told to stay neither closes the form nor lands on the new record (ablated: the pin fails when the createMore branch is skipped). Claude-Session: https://claude.ai/code/session_01L6bhgWL2r2CuFr34ENybDB Co-authored-by: Claude --- ...t.createLandingOriginPlural-11733.test.tsx | 34 +++- .../__tests__/modalMaximize-34604.test.tsx | 152 ++++++++++++++++++ 2 files changed, 185 insertions(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.createLandingOriginPlural-11733.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.createLandingOriginPlural-11733.test.tsx index 8d12ccc8736..b97f2e4a17d 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.createLandingOriginPlural-11733.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.createLandingOriginPlural-11733.test.tsx @@ -43,7 +43,9 @@ import { RECORD_SURFACE_PAGE_THRESHOLD } from '@object-ui/plugin-view'; /** The part of the modal's schema this file reads. */ interface ModalSchemaProbe { objectName?: string; - onSuccess: (saved: { id: string }) => Promise | void; + open?: boolean; + createMore?: boolean; + onSuccess: (saved: { id: string }, outcome?: { createMore?: boolean }) => Promise | void; } const { modalSchemas } = vi.hoisted(() => ({ modalSchemas: [] as ModalSchemaProbe[] })); @@ -205,3 +207,33 @@ describe('AppContent — a create that lands on the record page names the way ba expect(await originAfterCreate('en', 'showcase_note')).toBe('Note'); }); }); + +// objectstack-ai/objectstack#35980 — with 「Create more」 on, the dialog stays +// for the next record: the console neither closes the form nor leaves for +// the record it just made. +describe('AppContent — a 「Create more」 save stays on the list (objectstack-ai/objectstack#35980)', () => { + it('offers the switch, and a save told to stay does not land on the record page', async () => { + session.lang = 'en'; + const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + render( + + + + } /> + + + , + ); + await waitFor(() => expect(modalSchemas.length).toBeGreaterThan(0)); + const schema = modalSchemas[modalSchemas.length - 1]; + expect(schema.createMore).toBe(true); + + await schema.onSuccess({ id: 'r9' }, { createMore: true }); + await new Promise((r) => setTimeout(r, 300)); + expect(screen.queryByTestId('origin-label')).toBeNull(); + // The form is still the open dialog on the list's route. + const latest = modalSchemas[modalSchemas.length - 1]; + expect(latest.open).toBe(true); + expect(latest.objectName).toBe('showcase_project'); + }); +}); diff --git a/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx index 42239fc864b..1e979830983 100644 --- a/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx @@ -386,3 +386,155 @@ describe('#34604 — beside the section nav strip of a sectioned flat form', () expect(screen.getByTestId('form-section-nav')).toBe(nav); }); }); + +/** + * objectstack-ai/objectstack#35980 — the create dialog's 「Create more」 switch, + * its ⌘↵ / Ctrl+Enter save and the object icon before the title. The switch + * is a per-object preference like the maximize switch above, which is why its + * pins share this harness. + */ +describe('#35980 — 「Create more」, the save shortcut and the title icon', () => { + const createMoreSwitch = () => screen.queryByTestId('modal-form-create-more'); + const submitButton = () => screen.getByRole('button', { name: /^Create/ }); + + function renderCreate(extra: Record = {}, defs: Record = { deal: DEAL }) { + const onOpenChange = vi.fn(); + const onSuccess = vi.fn(); + const ds = flatDs(defs); + render( + , + ); + return { onOpenChange, onSuccess, ds }; + } + + it('is offered only when the host asks, and only on a create', async () => { + renderFlat('deal'); + await nameInput(); + expect(createMoreSwitch()).toBeNull(); + cleanup(); + + renderCreate({ mode: 'edit', recordId: 'r1' }); + await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy()); + expect(createMoreSwitch()).toBeNull(); + cleanup(); + + renderCreate(); + await nameInput(); + expect(createMoreSwitch()?.getAttribute('aria-checked')).toBe('false'); + expect(createMoreSwitch()?.closest('label')?.textContent).toContain('Create more'); + }); + + it('off: a save closes the dialog, and the host is not told to stay', async () => { + const { onOpenChange, onSuccess, ds } = renderCreate(); + fireEvent.change(await nameInput(), { target: { value: 'Acme' } }); + fireEvent.submit(document.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + expect(onSuccess).toHaveBeenCalledWith({ id: '1' }); + }); + + it('on: a save keeps the dialog, empties the form, focuses the first field, and saves again', async () => { + const { onOpenChange, onSuccess, ds } = renderCreate(); + fireEvent.change(await nameInput(), { target: { value: 'Acme' } }); + fireEvent.click(createMoreSwitch()!); + expect(createMoreSwitch()?.getAttribute('aria-checked')).toBe('true'); + expect(window.localStorage.getItem('modal-form-create-more:deal')).toBe('1'); + + fireEvent.submit(document.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + expect(ds.create.mock.calls[0][1]).toMatchObject({ name: 'Acme' }); + await waitFor(() => expect(onSuccess).toHaveBeenCalledWith({ id: '1' }, { createMore: true })); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + + // The form is drawn again from its opening values, and the first field has focus. + await waitFor(() => expect((document.querySelector('input[name="name"]') as HTMLInputElement).value).toBe('')); + await waitFor(() => expect(document.activeElement).toBe(document.querySelector('input[name="name"]'))); + + fireEvent.change(await nameInput(), { target: { value: 'Globex' } }); + fireEvent.submit(document.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(2)); + expect(ds.create.mock.calls[1][1]).toMatchObject({ name: 'Globex' }); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + + // Off again: the next save closes. + fireEvent.click(createMoreSwitch()!); + expect(window.localStorage.getItem('modal-form-create-more:deal')).toBeNull(); + fireEvent.change(await nameInput(), { target: { value: 'Initech' } }); + fireEvent.submit(document.querySelector('form') as HTMLFormElement); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + }); + + it('reopens with the switch as it was last left, per object', async () => { + window.localStorage.setItem('modal-form-create-more:deal', '1'); + renderCreate(); + await nameInput(); + expect(createMoreSwitch()?.getAttribute('aria-checked')).toBe('true'); + cleanup(); + + render( + , + ); + await nameInput(); + expect(createMoreSwitch()?.getAttribute('aria-checked')).toBe('false'); + }); + + it('⌘↵ and Ctrl+Enter save from a field; Shift or a lone Enter do not take the shortcut', async () => { + const { ds } = renderCreate({ createMore: false }); + const input = await nameInput(); + fireEvent.change(input, { target: { value: 'Acme' } }); + + fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true, shiftKey: true }); + fireEvent.keyDown(input, { key: 'Enter', altKey: true, metaKey: true }); + await new Promise((r) => setTimeout(r, 20)); + expect(ds.create).not.toHaveBeenCalled(); + + fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true }); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + }); + + it('⌘↵ saves too', async () => { + const { ds } = renderCreate({ createMore: false }); + const input = await nameInput(); + fireEvent.change(input, { target: { value: 'Acme' } }); + fireEvent.keyDown(input, { key: 'Enter', metaKey: true }); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + }); + + it('the Save button names the shortcut, with keycaps from sm up', async () => { + renderCreate(); + await nameInput(); + const btn = submitButton(); + expect(btn.getAttribute('aria-keyshortcuts')).toBe('Meta+Enter Control+Enter'); + const kbd = screen.getByTestId('modal-form-submit-shortcut'); + expect(btn.contains(kbd)).toBe(true); + expect(kbd.getAttribute('aria-hidden')).toBe('true'); + expect(kbd.className).toContain('hidden'); + expect(kbd.className).toContain('sm:inline'); + expect(['⌘↵', 'Ctrl ↵']).toContain(kbd.textContent); + }); + + it("the title is 16px and follows the object's own icon", async () => { + renderCreate({}, { deal: { ...DEAL, icon: 'briefcase' } }); + await nameInput(); + const title = screen.getByRole('heading', { name: 'New deal' }); + expect(title.className).toContain('text-base'); + const icon = await waitFor(() => screen.getByTestId('modal-form-title-icon')); + expect(title.contains(icon)).toBe(true); + expect(icon.getAttribute('aria-hidden')).toBe('true'); + }); + + it('an object with no icon draws the title alone', async () => { + renderCreate(); + await nameInput(); + expect(screen.queryByTestId('modal-form-title-icon')).toBeNull(); + }); +}); From 6e8a3744237ba5a1aa837d779c6ac6fc7632155f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:23:57 +0000 Subject: [PATCH 05/11] test(ui): the dialog snapshot reads the shared surface classes Claude-Session: https://claude.ai/code/session_01L6bhgWL2r2CuFr34ENybDB Co-authored-by: Claude --- .../__tests__/__snapshots__/snapshot-critical.test.tsx.snap | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/packages/components/src/__tests__/__snapshots__/snapshot-critical.test.tsx.snap b/ui/packages/components/src/__tests__/__snapshots__/snapshot-critical.test.tsx.snap index 2a1d09ad828..34887b904ee 100644 --- a/ui/packages/components/src/__tests__/__snapshots__/snapshot-critical.test.tsx.snap +++ b/ui/packages/components/src/__tests__/__snapshots__/snapshot-critical.test.tsx.snap @@ -448,7 +448,7 @@ exports[`Dialog snapshots > renders open dialog structure 1`] = `