diff --git a/.changeset/34615-phone-card-amount-tab-strip.md b/.changeset/34615-phone-card-amount-tab-strip.md new file mode 100644 index 00000000000..79f6a4df75c --- /dev/null +++ b/.changeset/34615-phone-card-amount-tab-strip.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +--- + +fix(ui): a phone list card shows its amount in full, and a form's tab strip no longer widens a phone screen + +Clause-②: no +Metadata-protocol: none + +- Phone list cards: the card's amount is the first shown column whose field type is `currency`. It used to share the subtitle line with the next column and was truncated with it (`CN¥1,2…`). It now has a line of its own under the subtitle, right-aligned and never truncated, with the status chip at that line's left. The subtitle shows the next shown column in its place. A list with no currency column draws its cards as before. +- Form field tabs (`fieldTabs`, also used by tabbed modal and tabbed forms): below the `sm` breakpoint a horizontal tab strip is capped at its container's width, and tabs that do not fit scroll sideways with no scrollbar drawn, so the page no longer scrolls sideways. The active tab is kept in view: on a tap, on `defaultFieldTab`, and when a failed submit jumps to the tab with the first error, whose red dot stays on the trigger. Desktop strips and vertical strips are unchanged. diff --git a/ui/packages/components/src/renderers/form/__tests__/form-field-tabs.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-field-tabs.test.tsx index 50ec3f8c02e..331fb29e2cb 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-field-tabs.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-field-tabs.test.tsx @@ -27,6 +27,8 @@ import { toast } from '../../../ui/sonner'; // cold transform is billed to `hookTimeout`, which is why this carried a raised // timeout. See object-ui/no-dynamic-import-in-test-hook (objectui#3010/#3021). import '../../../renderers'; +// The renderer barrel reaches `react-page.tsx`, which loads this dynamically: pay the load at collection. +import '@object-ui/react-runtime'; beforeEach(() => { vi.spyOn(toast, 'error').mockImplementation(() => 'id' as any); @@ -179,3 +181,146 @@ describe('form renderer — fieldTabs (#2959)', () => { expect(document.body.querySelector('[data-field="description"]')).toBeTruthy(); }); }); + +/** + * objectstack#34615 — at phone width the horizontal tab strip never widens the + * page: below `sm` it is capped at its container's width and the tabs that do + * not fit scroll sideways inside it, with no scrollbar drawn, and the ACTIVE + * tab is always scrolled into the strip's visible window — a tap, a + * `defaultFieldTab`, or a failed submit jumping to the offending tab. Every + * added class is `max-sm:`-gated, so the desktop strip is unchanged. + * + * jsdom has no layout engine: the strip's overflow (`scrollWidth > + * clientWidth`) and the triggers' boxes are stubbed below, standing for a + * 375 px phone with five tabs. The real geometry was measured once in Chromium + * on the pull request. + */ +describe('form renderer — fieldTabs strip at phone width (objectstack#34615)', () => { + const FIVE_FIELDS = ['name', 'forecast', 'qualification', 'notes', 'activity'].map((name) => ({ + name, + label: name, + type: 'input', + required: name === 'activity', + })); + const FIVE_TABS = [ + { key: 'overview', label: 'Overview', fields: ['name'] }, + { key: 'forecast', label: 'Forecast', fields: ['forecast'] }, + { key: 'qualification', label: 'Qualification', fields: ['qualification'] }, + { key: 'notes', label: 'Description', fields: ['notes'] }, + { key: 'activity', label: 'Activity', fields: ['activity'] }, + ]; + // A 343 px strip (375 px less the gutters) holding 600 px of tabs, 120 px each. + const STRIP = { left: 16, width: 343, content: 600 }; + + /** Lay the strip and its triggers out as a phone would; returns the scrollLeft writes. */ + function layOutStrip(overflowing: boolean) { + const strip = screen.getByTestId('form-tab-strip'); + let scrollLeft = 0; + const writes: number[] = []; + Object.defineProperty(strip, 'clientWidth', { configurable: true, value: STRIP.width }); + Object.defineProperty(strip, 'scrollWidth', { configurable: true, value: overflowing ? STRIP.content : STRIP.width }); + Object.defineProperty(strip, 'scrollLeft', { + configurable: true, + get: () => scrollLeft, + set: (v: number) => { scrollLeft = v; writes.push(v); }, + }); + const rect = (left: number, width: number) => + ({ left, right: left + width, width, top: 0, bottom: 44, height: 44, x: left, y: 0, toJSON: () => ({}) }) as DOMRect; + strip.getBoundingClientRect = () => rect(STRIP.left, STRIP.width); + screen.getAllByRole('tab').forEach((trigger, i) => { + trigger.getBoundingClientRect = () => rect(STRIP.left + 4 + i * 120 - scrollLeft, 120); + }); + return writes; + } + + const renderFive = (overrides: Record = {}) => + renderTabbedForm({ fields: FIVE_FIELDS, fieldTabs: FIVE_TABS, ...overrides }); + + it('caps the horizontal strip and scrolls it sideways below sm, with every added class phone-gated', () => { + renderFive(); + const strip = screen.getByTestId('form-tab-strip'); + expect(strip).toHaveClass( + 'max-sm:max-w-full', + 'max-sm:overflow-x-auto', + 'max-sm:justify-start', + 'max-sm:[scrollbar-width:none]', + 'max-sm:[&::-webkit-scrollbar]:hidden', + ); + const ungated = [...strip.classList].filter((c) => /^(max-w-|overflow-|justify-start|\[scrollbar|\[&::-webkit-scrollbar\])/.test(c)); + expect(ungated, 'the desktop strip keeps its look').toEqual([]); + }); + + it('leaves a vertical strip without the phone scroll classes', () => { + renderFive({ fieldTabsPosition: 'left' }); + expect(screen.getByTestId('form-tab-strip').className).not.toContain('overflow-x-auto'); + }); + + it('scrolls the fifth tab into the strip when it is tapped', () => { + renderFive(); + const writes = layOutStrip(true); + fireEvent.mouseDown(tab(/Activity/), { button: 0 }); + fireEvent.click(tab(/Activity/)); + expect(tab(/Activity/)).toHaveAttribute('data-state', 'active'); + // Its right edge (16 + 4 + 4·120 + 120 = 620) is brought to the strip's (359). + expect(writes).toEqual([620 - 359]); + }); + + it('a failed submit that jumps to an off-screen tab scrolls it into view, error dot and all', async () => { + renderFive(); + const writes = layOutStrip(true); + submit(); + await waitFor(() => expect(tab(/Activity/)).toHaveAttribute('data-state', 'active')); + expect(tab(/Activity/)).toHaveAttribute('data-error', 'true'); + expect(tab(/Activity/).querySelector('.bg-destructive'), 'the error dot rides on the trigger').not.toBeNull(); + expect(writes).toEqual([620 - 359]); + }); + + it('opens on an off-screen defaultFieldTab already scrolled to it', () => { + // The strip must be laid out before the mount effect reads it, so the + // stubs go on the prototypes for this one render and come off after. + const writes: number[] = []; + const isStrip = (el: Element) => (el as HTMLElement).dataset.testid === 'form-tab-strip'; + const saved = (['scrollWidth', 'clientWidth', 'scrollLeft'] as const).map( + (key) => [key, Object.getOwnPropertyDescriptor(Element.prototype, key)] as const, + ); + Object.defineProperty(Element.prototype, 'scrollWidth', { + configurable: true, + get(this: Element) { return isStrip(this) ? STRIP.content : 0; }, + }); + Object.defineProperty(Element.prototype, 'clientWidth', { + configurable: true, + get(this: Element) { return isStrip(this) ? STRIP.width : 0; }, + }); + Object.defineProperty(Element.prototype, 'scrollLeft', { + configurable: true, + get() { return 0; }, + set(this: Element, v: number) { if (isStrip(this)) writes.push(v); }, + }); + const rect = (left: number, width: number) => + ({ left, right: left + width, width, top: 0, bottom: 44, height: 44, x: left, y: 0, toJSON: () => ({}) }) as DOMRect; + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { + if (isStrip(this)) return rect(STRIP.left, STRIP.width); + const i = FIVE_TABS.findIndex((t) => (this as HTMLElement).dataset.testid === `form-tab:${t.key}`); + return i >= 0 ? rect(STRIP.left + 4 + i * 120, 120) : rect(0, 0); + }); + try { + renderFive({ defaultFieldTab: 'activity' }); + expect(tab(/Activity/)).toHaveAttribute('data-state', 'active'); + expect(writes).toEqual([620 - 359]); + } finally { + for (const [key, desc] of saved) { + if (desc) Object.defineProperty(Element.prototype, key, desc); + else delete (Element.prototype as unknown as Record)[key]; + } + } + }); + + it('CONTROL: a strip that fits (every desktop strip) is never scrolled', () => { + renderFive(); + const writes = layOutStrip(false); + fireEvent.mouseDown(tab(/Activity/), { button: 0 }); + fireEvent.click(tab(/Activity/)); + expect(tab(/Activity/)).toHaveAttribute('data-state', 'active'); + expect(writes).toEqual([]); + }); +}); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 95e447bac1c..a9e84974b32 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2732,6 +2732,25 @@ ComponentRegistry.register('form', return out; }, [fieldTabs, tabKeyByFieldName, rejectedFieldNames]); + // objectstack#34615 — below `sm` a horizontal tab strip that does not fit + // scrolls sideways inside its own box (see the strip's classes) instead of + // widening the page. The ACTIVE tab must stay in that box's visible window: + // a pick, `defaultFieldTab`, or a failed submit jumping to the first + // offending tab can each select a trigger scrolled out of view. Only the + // strip's own `scrollLeft` moves, never an outer scroller, and a strip + // that fits (every desktop strip) is left untouched. + const fieldTabListRef = React.useRef(null); + React.useEffect(() => { + const list = fieldTabListRef.current; + if (!list || activeFieldTab === undefined || list.scrollWidth <= list.clientWidth) return; + const trigger = list.querySelector('[role="tab"][data-state="active"]'); + if (!trigger) return; + const box = list.getBoundingClientRect(); + const tab = trigger.getBoundingClientRect(); + if (tab.left < box.left) list.scrollLeft -= box.left - tab.left; + else if (tab.right > box.right) list.scrollLeft += tab.right - box.right; + }, [activeFieldTab]); + // Cascade clear (#2284): when a select/radio's option list narrows — because a // controlling field changed or a role/context predicate flipped — a previously // chosen value may no longer be offered. Drop it so the form never submits a @@ -4606,13 +4625,26 @@ ComponentRegistry.register('form', className={cn('flex w-full', isVerticalFieldTabs ? 'gap-4' : 'flex-col')} > {visibleFieldTabGroups.map((group) => ( diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 50d222c6629..823a2fe2e93 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -3362,7 +3362,17 @@ export const ObjectGrid: React.FC = ({ // or empty value rather than drawing it. const statusKey = detectStatusField(objectSchema); const statusCol = statusKey !== null ? bodyColumns.find((c) => c.accessorKey === statusKey) : undefined; - const subtitleColumns = bodyColumns.filter((c) => c !== statusCol).slice(0, 2); + // objectstack#34615 — the card's AMOUNT is the first shown body column whose + // field type is `currency` (the column draft's resolved type, so a view + // that presents the field as another type keeps it a plain value). It + // never shares the subtitle's width: it gets a line of its own under the + // subtitle, drawn whole at the right edge, and the status chip moves to + // that line's left so the two never compete for one row. A masked amount + // is not promoted; it stays a subtitle candidate, which skips it. + const amountCol = bodyColumns.find( + (c) => c !== statusCol && c.type === 'currency' && !isMaskedCardColumn(c.accessorKey), + ); + const subtitleColumns = bodyColumns.filter((c) => c !== statusCol && c !== amountCol).slice(0, 2); const isEmptyCardValue = (value: unknown) => value == null || value === ''; const cardCell = (col: ObjectGridColumnDraft, row: any): React.ReactNode => { const value = row[col.accessorKey]; @@ -3374,6 +3384,15 @@ export const ObjectGrid: React.FC = ({ (col) => !isMaskedCardColumn(col.accessorKey) && !isEmptyCardValue(row[col.accessorKey]), ); const showStatus = statusCol !== undefined && !isEmptyCardValue(row[statusCol.accessorKey]); + const showAmount = amountCol !== undefined && !isEmptyCardValue(row[amountCol.accessorKey]); + // With an amount column every card of the list draws the status on the + // amount line, an empty amount included, so the cards keep one shape. + const statusOnAmountLine = amountCol !== undefined; + const statusChip = (className: string) => statusCol !== undefined && ( +
+ {cardCell(statusCol, row)} +
+ ); return (
= ({ ))}
)} + {statusOnAmountLine && (showStatus || showAmount) && ( +
+ {showStatus && statusChip('min-w-0 truncate text-xs')} + {showAmount && ( +
+ {cardCell(amountCol, row)} +
+ )} +
+ )} - {showStatus && ( -
- {cardCell(statusCol, row)} -
- )} + {showStatus && !statusOnAmountLine && statusChip('max-w-[45%] shrink-0 truncate text-xs')} {/* objectstack#29150 — the row's actions, the desktop row's own resolver and handlers in one 44 px "⋮" (inline budget 0, as the row context menu reads it). The menu stops its own clicks, so a diff --git a/ui/packages/plugin-grid/src/__tests__/mobileCardFieldCurrency-10423.test.tsx b/ui/packages/plugin-grid/src/__tests__/mobileCardFieldCurrency-10423.test.tsx index 4ef5dfa390f..4f75ab0a9fa 100644 --- a/ui/packages/plugin-grid/src/__tests__/mobileCardFieldCurrency-10423.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/mobileCardFieldCurrency-10423.test.tsx @@ -9,8 +9,9 @@ /** * objectui#10423: the mobile card's amount reads the FIELD's currency, exactly * as the desktop cell of the same row does. Since objectstack#28484 the card - * draws the amount on its subtitle line through that same desktop cell, so the - * two faces are one face. + * draws the amount through that same desktop cell, so the two faces are one + * face; since objectstack#34615 it sits on the card's own amount line + * (`grid-card-amount`) rather than inside the subtitle. * * objectui#10354 made the desktop cell and the summary footer carry the * field's `currencyConfig`. The mobile card's amount line did not follow: it @@ -64,7 +65,7 @@ const OBJECT = 'os_10423_deal'; const FIELDS: Record> = { id: { type: 'text' }, name: { type: 'text', label: 'Deal Name' }, - // The first subtitle value after the title. + // The card's amount (its first `currency` column). amount: { type: 'currency', label: 'Yen Amount', @@ -114,13 +115,13 @@ async function renderGrid(schemaExtra: Record) { return utils; } -/** The card's amount: the first value of its subtitle line. */ +/** The card's amount: its own amount slot (objectstack#34615). */ async function cardAmountLine(schemaExtra: Record): Promise { setWidth(390); const { container } = await renderGrid(schemaExtra); expect(container.querySelector('table'), 'expected the mobile card layout, not the table').toBeNull(); - const line = container.querySelector('[data-testid="grid-card-subtitle-part"]'); - expect(line, 'the card rendered no subtitle value').not.toBeNull(); + const line = container.querySelector('[data-testid="grid-card-amount"]'); + expect(line, 'the card rendered no amount').not.toBeNull(); return (line!.textContent ?? '').trim(); } diff --git a/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx b/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx new file mode 100644 index 00000000000..448a20ea372 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx @@ -0,0 +1,157 @@ +/** + * 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#34615 — on a phone the list card's AMOUNT is drawn whole. The + * card's amount is its first shown body column whose field type is + * `currency`. It does not take a subtitle slot (where it split the width with + * the account name and both were truncated); it sits on a line of its own + * under the subtitle, at the right edge, `shrink-0` and never truncated, and + * the status chip moves to that line's left. + * + * Pinned at 375 px. jsdom has no layout engine, so "drawn whole" is pinned as + * the full formatted text in the amount slot plus no truncating box between + * that slot and the card; the geometry itself was measured once in Chromium + * on the pull request. + * + * ── Directions on the base tree (predicted before the first run) ───────── + * amount slot exists, holds the full amount RED (no slot; in subtitle) + * subtitle carries no amount RED + * status chip on the amount line, left of it RED (card's last child) + * control: no currency column keeps the old row GREEN + */ +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; +import { render, cleanup, waitFor, screen, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; +import { registerAllFields } from '@object-ui/fields'; + +beforeAll(() => { + registerAllFields(); + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView']; + } +}); + +const ORIGINAL_INNER_WIDTH = window.innerWidth; + +function setWidth(px: number) { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: px }); +} + +afterEach(() => { + cleanup(); + setWidth(ORIGINAL_INNER_WIDTH); +}); + +const OBJECT = 'crm_opportunity_34615'; + +const FIELDS = { + id: { type: 'text' }, + name: { type: 'text', label: 'Opportunity' }, + account: { type: 'text', label: 'Account' }, + amount: { type: 'currency', label: 'Amount' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'negotiation', label: 'Negotiation' }, + { value: 'proposal', label: 'Proposal' }, + ], + }, + next_step: { type: 'text', label: 'Next Step' }, +}; + +const ROWS = [ + { id: 'o1', name: 'Wayne Enterprise License', account: 'Wayne Enterprises', amount: 1200000, stage: 'negotiation', next_step: 'Sign by 11-27' }, + { id: 'o2', name: 'Acme Platform Upgrade', account: 'Acme Corporation', amount: null, stage: 'proposal', next_step: 'Demo' }, +]; + +/** The amount sits between the subtitle's columns, as a real list view puts it. */ +const COLUMNS = ['name', 'account', 'amount', 'stage', 'next_step'].map((field) => ({ field })); + +function renderGrid(columns: unknown[] = COLUMNS) { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: ROWS.length, hasMore: false, pageSize: 50 })), + getObjectSchema: async (name: string) => ({ name, nameField: 'name', fields: structuredClone(FIELDS) }), + } as never; + return render( + + + + + + + , + ); +} + +const cards = () => [...document.querySelectorAll('[data-testid="grid-mobile-card"]')] as HTMLElement[]; +const cardOf = (title: string) => + cards().find((card) => within(card).queryByTestId('grid-card-title')?.textContent === title)!; + +async function phoneCards(columns?: unknown[]) { + setWidth(375); + renderGrid(columns); + // The status chip reads its label off the object schema, so it proves the + // field defs (and with them the `currency` type) have arrived. + await waitFor(() => expect(screen.getByText('Negotiation')).toBeInTheDocument()); + expect(document.querySelector('table'), 'the card layout, not the table').toBeNull(); +} + +describe('the phone list card draws its amount whole, on a line of its own (objectstack#34615)', () => { + it('draws the full amount in its own slot, with no truncating box between it and the card', async () => { + await phoneCards(); + const card = cardOf('Wayne Enterprise License'); + const amount = within(card).getByTestId('grid-card-amount'); + expect(amount.textContent).toBe('CN¥1,200,000.00'); + expect(amount).toHaveClass('shrink-0', 'whitespace-nowrap'); + for (let el: HTMLElement | null = amount; el && el !== card; el = el.parentElement) { + expect(el.className, `no truncation on ${el.dataset.testid ?? el.tagName}`).not.toMatch(/\btruncate\b|\boverflow-hidden\b/); + } + }); + + it('keeps the amount out of the subtitle, which takes the next shown column instead', async () => { + await phoneCards(); + const card = cardOf('Wayne Enterprise License'); + expect(within(card).getByTestId('grid-card-subtitle').textContent).toBe('Wayne Enterprises · Sign by 11-27'); + expect(within(card).getByTestId('grid-card-subtitle')).not.toContainElement(within(card).getByTestId('grid-card-amount')); + }); + + it('puts the status chip at the left of the amount line, not beside the title block', async () => { + await phoneCards(); + const card = cardOf('Wayne Enterprise License'); + const line = within(card).getByTestId('grid-card-amount-line'); + const chips = within(card).getAllByTestId('grid-card-status'); + expect(chips).toHaveLength(1); + expect(chips[0].textContent).toBe('Negotiation'); + expect([...line.children]).toEqual([chips[0], within(card).getByTestId('grid-card-amount')]); + }); + + it('a row with no amount keeps the same shape: the chip still on the amount line, no amount slot', async () => { + await phoneCards(); + const card = cardOf('Acme Platform Upgrade'); + expect(within(card).queryByTestId('grid-card-amount')).toBeNull(); + expect(within(card).getByTestId('grid-card-amount-line')).toContainElement(within(card).getByTestId('grid-card-status')); + }); + + it('CONTROL: a view with no currency column keeps the objectstack#28484 row (chip at the right, no amount line)', async () => { + await phoneCards(['name', 'account', 'stage', 'next_step'].map((field) => ({ field }))); + const card = cardOf('Wayne Enterprise License'); + expect(within(card).queryByTestId('grid-card-amount-line')).toBeNull(); + expect(card.lastElementChild).toBe(within(card).getByTestId('grid-card-status')); + expect(within(card).getByTestId('grid-card-subtitle').textContent).toBe('Wayne Enterprises · Sign by 11-27'); + }); +});