Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/34615-phone-card-amount-tab-strip.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<string, unknown> = {}) =>
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<string, unknown>)[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([]);
});
});
34 changes: 33 additions & 1 deletion ui/packages/components/src/renderers/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLDivElement>(null);
React.useEffect(() => {
const list = fieldTabListRef.current;
if (!list || activeFieldTab === undefined || list.scrollWidth <= list.clientWidth) return;
const trigger = list.querySelector<HTMLElement>('[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
Expand Down Expand Up @@ -4606,13 +4625,26 @@ ComponentRegistry.register('form',
className={cn('flex w-full', isVerticalFieldTabs ? 'gap-4' : 'flex-col')}
>
<TabsList
ref={fieldTabListRef}
data-testid="form-tab-strip"
className={cn(
// `self-start` keeps the strip its content's size instead of
// being stretched by the flex container above.
'self-start',
isVerticalFieldTabs
? cn('h-auto flex-col', fieldTabsPosition === 'right' && 'order-last')
: fieldTabsPosition === 'bottom' ? 'order-last mt-4' : 'mb-4',
: cn(
fieldTabsPosition === 'bottom' ? 'order-last mt-4' : 'mb-4',
// objectstack#34615 — below `sm` the strip never
// outgrows its container: it is capped at the
// container's width and the tabs that do not fit
// scroll sideways, with no scrollbar drawn (the
// active tab is kept in view by the effect on
// `fieldTabListRef`). Left-packed, because a centred
// overflowing row cannot scroll to its first tab.
'max-sm:max-w-full max-sm:justify-start max-sm:overflow-x-auto max-sm:overflow-y-hidden',
'max-sm:[scrollbar-width:none] max-sm:[&::-webkit-scrollbar]:hidden',
),
)}
>
{visibleFieldTabGroups.map((group) => (
Expand Down
40 changes: 34 additions & 6 deletions ui/packages/plugin-grid/src/ObjectGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3362,7 +3362,17 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
// 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];
Expand All @@ -3374,6 +3384,15 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
(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 && (
<div data-testid="grid-card-status" className={className}>
{cardCell(statusCol, row)}
</div>
);

return (
<div
Expand Down Expand Up @@ -3411,12 +3430,21 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
))}
</div>
)}
{statusOnAmountLine && (showStatus || showAmount) && (
<div data-testid="grid-card-amount-line" className="mt-1 flex min-w-0 items-center gap-2">
{showStatus && statusChip('min-w-0 truncate text-xs')}
{showAmount && (
<div
data-testid="grid-card-amount"
className="ml-auto shrink-0 whitespace-nowrap text-sm font-semibold tabular-nums"
>
{cardCell(amountCol, row)}
</div>
)}
</div>
)}
</div>
{showStatus && (
<div data-testid="grid-card-status" className="max-w-[45%] shrink-0 truncate text-xs">
{cardCell(statusCol, row)}
</div>
)}
{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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -64,7 +65,7 @@ const OBJECT = 'os_10423_deal';
const FIELDS: Record<string, Record<string, unknown>> = {
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',
Expand Down Expand Up @@ -114,13 +115,13 @@ async function renderGrid(schemaExtra: Record<string, unknown>) {
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<string, unknown>): Promise<string> {
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();
}

Expand Down
Loading
Loading