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
18 changes: 18 additions & 0 deletions .changeset/34228-print-zh-record-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/core': patch
'@object-ui/fields': patch
'@object-ui/components': patch
---

fix(console): a record page printed in a zh-CN organization shows dates in Chinese order, fits its line-items table to the sheet, and prints on white with plain values

Clause-②: no
Metadata-protocol: none

A print page (a record page that declares `print`), printed by `@objectstack/service-print` or by the console's Print button, now reads as a document:

- **Dates in the locale's own order.** A `date` field authored `format: 'short'` drew `11月 15, '26` in `zh-CN`: only the month was translated into the English compact layout `Nov 15, '26`. That compact layout is now kept only for a locale that writes a date month first, then day, then year (`en`, `en-US`). Every other locale gets its own date with the year: `2026年11月15日` in `zh-CN` and `ja`, `15. Nov. 2026` in `de`, `15 Nov 2026` in `en-GB`. This is the face `formatDate` already drew for the default style with the year shown. It applies on screen as well as on paper, and to every reader of `formatDate(value, 'short', { locale })`.
- **Tables fit the printable width.** On a print page, a data table's cells drop their on-screen minimum width and single line on paper, so the columns shrink and wrap to the box. Before, a five-column `record:line_items` table on A4 portrait with 15 mm margins was 647 px wide in a 630 px box. Its last column ran past the box's border, and that border was drawn through the column. The running header and footer table is not affected.
- **White page, plain values.** On paper the page and everything around it are white instead of the app's background. A link, such as a lookup's referenced record, prints in the surrounding text colour with no underline. A select value drawn as a coloured badge prints as its label with no pill. The select badge carries a new inert attribute, `data-select-badge`, for this rule. Every rule sits inside `@media print` and is scoped to the print page, so the screen is unchanged.

`avoidBreakInside` is unchanged: it still keeps each block whole on one sheet when the block fits.
138 changes: 138 additions & 0 deletions ui/packages/components/src/__tests__/page-print-paper-34228.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
* 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#34228 — the print stylesheet puts a record page on paper as a
* document: a data table fits the printable width, and the page prints on
* white with links and select badges as plain text.
*
* Measured in Chromium (A4 portrait, 15 mm side margins) before the change: a
* five-column `record:line_items` grid was 647 px wide in its 630 px box, its
* last column under the box's right border; the page and its ancestors
* printed the app's grey; a lookup printed in the link colour and a select as
* a coloured pill. The readings are in the pull request.
*
* Two halves here, as in `page-print-stylesheet-11958.test.tsx`: the rules'
* text, every one inside `@media print` and scoped to the print page, and the
* rules' selectors against a real render — the fit rule reaches a data table
* on the page and never the running-region table. ⚠️ `@media print` does not
* apply under happy-dom, so nothing here shows a rule taking effect on paper.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, cleanup } from '@testing-library/react';
import React from 'react';
import { SchemaRenderer } from '@object-ui/react';
import '../renderers';
// `PageRenderer` reaches `react-page.tsx`, which loads this dynamically: pay the load at collection.
import '@object-ui/react-runtime';
import {
buildPagePrintStylesheet,
PRINT_PAGE_ATTRIBUTE,
PRINT_PLAIN_BADGE_ATTRIBUTE,
PRINT_RUNNING_ATTRIBUTE,
} from '../renderers/layout/page-print';

afterEach(() => cleanup());

const PAGE = `[${PRINT_PAGE_ATTRIBUTE}]`;

/** Each rule of the sheet as `[selector, body]`, the `@page` rule left out. */
function rulesOf(css: string): Array<[string, string]> {
const rules: Array<[string, string]> = [];
for (const line of css.split('\n')) {
const rule = /^\s*(.+?) \{ (.*) \}$/.exec(line);
if (rule && !rule[1].startsWith('@')) rules.push([rule[1], rule[2]]);
}
return rules;
}

describe('the print stylesheet fits a data table to the printable width (objectstack#34228)', () => {
it('drops the cells’ screen minimum width and single line, and holds the table to the box', () => {
const css = buildPagePrintStylesheet({});
const table = `${PAGE} table:not([${PRINT_RUNNING_ATTRIBUTE}])`;
expect(css).toContain(`${table} { width: 100% !important; }`);
expect(css).toContain(`${table} :is(th, td) { min-width: 0 !important; white-space: normal !important;`);
});

it('every declaration shape carries the rules, whatever `print` declares', () => {
for (const print of [{}, { avoidBreakInside: true }, { repeatHeader: true, repeatFooter: true }]) {
expect(buildPagePrintStylesheet(print)).toContain(`${PAGE} table:not([${PRINT_RUNNING_ATTRIBUTE}]) { width: 100% !important; }`);
}
});
});

describe('the print stylesheet prints the page on white, links and select badges as plain text (objectstack#34228)', () => {
it('the page and every box around it print on white', () => {
expect(buildPagePrintStylesheet({})).toContain(`:has(${PAGE}), ${PAGE} { background: #fff !important; }`);
});

it('a link prints in the colour around it, with no underline', () => {
expect(buildPagePrintStylesheet({})).toContain(`${PAGE} a[href] { color: inherit !important; text-decoration: none !important; }`);
});

it('a select badge prints as its label: no fill, no border colour, no padding, no pill', () => {
const [, body] = rulesOf(buildPagePrintStylesheet({})).find(([sel]) => sel === `${PAGE} [${PRINT_PLAIN_BADGE_ATTRIBUTE}]`)!;
for (const declaration of [
'background: none !important',
'border-color: transparent !important',
'color: inherit !important',
'padding: 0 !important',
'border-radius: 0 !important',
]) {
expect(body).toContain(declaration);
}
});

it('every rule sits inside `@media print` and names the print page, so the screen and every other page are untouched', () => {
const css = buildPagePrintStylesheet({ avoidBreakInside: true, repeatHeader: true });
expect(css.startsWith('@media print {')).toBe(true);
const rules = rulesOf(css);
expect(rules.length).toBeGreaterThan(0);
for (const [selector] of rules) {
expect(selector, selector).toContain(PAGE);
}
});
});

const page = (print: Record<string, unknown>) => ({
type: 'record',
name: 'invoice_print',
label: 'Invoice',
print,
regions: [
{ name: 'header', components: [{ type: 'text', value: 'ACME Ltd' }] },
{
name: 'main',
components: [
{
type: 'table',
columns: [{ header: 'Product', accessorKey: 'p' }, { header: 'Total', accessorKey: 't' }],
data: [{ p: 'Widget', t: '12,345,678.90' }],
},
],
},
],
});

describe('the fit rule’s selectors against a real print page (objectstack#34228)', () => {
it('reach a data table on the page and its cells, and never the running-region table', () => {
const declaration = { repeatHeader: true };
const { container } = render(<SchemaRenderer schema={page(declaration) as never} />);
const [[tableSelector], [cellSelector]] = rulesOf(buildPagePrintStylesheet(declaration)).filter(([sel]) => sel.includes('table:not('));
const running = container.querySelector(`table[${PRINT_RUNNING_ATTRIBUTE}]`)!;
const data = [...container.querySelectorAll('table')].find((t) => t !== running)!;
expect(running).not.toBeNull();
expect(data).toBeDefined();
expect(data.matches(tableSelector)).toBe(true);
expect(data.querySelector('td')!.matches(cellSelector)).toBe(true);
expect(data.querySelector('th')!.matches(cellSelector)).toBe(true);
// CONTROL — the running-region table lays out regions, and keeps its own layout.
expect(running.matches(tableSelector)).toBe(false);
expect(running.querySelector(':scope > thead > tr > td')!.matches(cellSelector)).toBe(false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ import React from 'react';
import { ComponentRegistry } from '@object-ui/core';
import { SchemaRenderer, usePrintPage } from '@object-ui/react';
import '../renderers';
// `PageRenderer` reaches `react-page.tsx`, which loads this dynamically: pay the load at collection.
import '@object-ui/react-runtime';
import { buildPagePrintStylesheet, PRINT_PAGE_ATTRIBUTE, PRINT_RUNNING_ATTRIBUTE } from '../renderers/layout/page-print';

afterEach(() => cleanup());
Expand Down Expand Up @@ -84,7 +86,9 @@ describe('buildPagePrintStylesheet — one print-CSS rule per declared key (obje
expect(css).toContain(`${table} > thead { display: table-header-group !important; }`);
expect(css).toContain(`${table} > tfoot { display: table-footer-group !important; }`);
}
expect(buildPagePrintStylesheet({})).not.toContain(PRINT_RUNNING_ATTRIBUTE + ']) {');
// The running region's block rule, spelled whole: the data-table fit rule
// (objectstack#34228) names the attribute too, to exclude that table.
expect(buildPagePrintStylesheet({})).not.toContain(`:has(> table[${PRINT_RUNNING_ATTRIBUTE}]) {`);
expect(buildPagePrintStylesheet({})).not.toContain(`${table} {`);
});

Expand Down
52 changes: 49 additions & 3 deletions ui/packages/components/src/renderers/layout/page-print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@
* not repeat;
* - `avoidBreakInside` → `break-inside: avoid` on every block of a region.
*
* Besides the keys, two rules every print page needs: everything on the
* Besides the keys, the rules every print page needs: everything on the
* document that is not the print page, an ancestor of it, or inside it is
* hidden on paper (the console chrome, and the record view's own panels
* around the page), and the ancestors' viewport-height clipping is released
* so the page runs onto as many sheets as it needs.
* around the page); the ancestors' viewport-height clipping is released so
* the page runs onto as many sheets as it needs; a data table fits the
* printable width; and the page prints on white, with links and select
* badges as plain text (objectstack#34228).
*
* ⚠️ Values are WRITTEN INTO A STYLESHEET, so only the spec's own values pass:
* an enum member for `paperSize` / `orientation`, a finite non-negative number
Expand All @@ -61,6 +63,13 @@ export const PRINT_PAGE_ATTRIBUTE = 'data-print-page';
/** The DOM attribute on the running-region table `PageRenderer` draws for `repeatHeader` / `repeatFooter`. */
export const PRINT_RUNNING_ATTRIBUTE = 'data-print-running';

/**
* The DOM attribute on a value drawn as a coloured badge that prints as plain
* text: the select cell's option badge (`SelectCellRenderer` in
* `@object-ui/fields`, which spells the same literal).
*/
export const PRINT_PLAIN_BADGE_ATTRIBUTE = 'data-select-badge';

const PAPER_SIZES: ReadonlySet<string> = new Set(['A4', 'A5', 'Letter', 'Legal']);
const ORIENTATIONS: ReadonlySet<string> = new Set(['portrait', 'landscape']);
const MARGIN_SIDES = ['top', 'right', 'bottom', 'left'] as const;
Expand Down Expand Up @@ -111,6 +120,42 @@ function runningRegionRules(print: PagePrintDeclaration, page: string): string[]
];
}

/**
* A data table fits the sheet's printable width (objectstack#34228). On screen
* a table's cells keep a comfortable minimum width and one line, and the table
* scrolls sideways inside its box when they do not fit; paper has no scroll,
* so the table ran past its box: measured in Chromium on A4 portrait with
* 15 mm margins, a five-column `record:line_items` grid was 647 px wide in a
* 630 px box, its last column under the box's right border. On paper the
* minimum widths and the single line are dropped, so the columns shrink and
* wrap to the box. The running-region table is excluded: it lays out regions,
* not data.
*/
function paperFitRules(page: string): string[] {
const table = `${page} table:not([${PRINT_RUNNING_ATTRIBUTE}])`;
return [
`${table} { width: 100% !important; }`,
`${table} :is(th, td) { min-width: 0 !important; white-space: normal !important; overflow-wrap: break-word; }`,
];
}

/**
* A printed document is a white sheet with plain values (objectstack#34228):
* the page and every box around it print on white, not the app's background;
* a link (a lookup's reference) prints as plain text in the colour around
* it; and a select value drawn as a coloured badge
* ({@link PRINT_PLAIN_BADGE_ATTRIBUTE}) prints as its label in that colour,
* with no pill. The `!important` beats the inline colours a hex option
* colour sets on its badge.
*/
function paperFaceRules(page: string): string[] {
return [
`:has(${page}), ${page} { background: #fff !important; }`,
`${page} a[href] { color: inherit !important; text-decoration: none !important; }`,
`${page} [${PRINT_PLAIN_BADGE_ATTRIBUTE}] { background: none !important; border-color: transparent !important; color: inherit !important; padding: 0 !important; border-radius: 0 !important; font-size: inherit !important; font-weight: inherit !important; }`,
];
}

/**
* Build the print stylesheet for a page that declares `print`. Pure: the same
* declaration always yields the same text, so it is pinned as text.
Expand All @@ -135,5 +180,6 @@ export function buildPagePrintStylesheet(print: PagePrintDeclaration): string {
if (print.avoidBreakInside === true) {
rules.push(`${page} [data-region] > * { break-inside: avoid; }`);
}
rules.push(...paperFitRules(page), ...paperFaceRules(page));
return `@media print {\n ${rules.join('\n ')}\n}\n`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* 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#34228 — `formatDate`'s `'short'` face follows the locale's own
* date order.
*
* The face was a fixed English layout with only the month token localized,
* so a `zh-CN` record page, and the document `service-print` printed from it,
* read `11月 15, '26`. The compact layout is kept where it IS the locale's
* order (month → day → year); every other locale gets its own face with the
* year, the default face's with the year shown.
*/
import { describe, it, expect } from 'vitest';
import { formatDate } from '../date-display';

/** A date-only value: its day is the same in every zone. */
const DAY = '2026-11-15';

describe("formatDate 'short' — the locale's date order (objectstack#34228)", () => {
it.each([
['zh-CN', '2026年11月15日'],
['zh', '2026年11月15日'],
['ja-JP', '2026年11月15日'],
['ko-KR', '2026년 11월 15일'],
['de-DE', '15. Nov. 2026'],
['en-GB', '15 Nov 2026'],
])('%s writes the date in its own order, with the year', (locale, face) => {
expect(formatDate(DAY, 'short', { locale })).toBe(face);
});

it.each([
['en', "Nov 15, '26"],
['en-US', "Nov 15, '26"],
])('CONTROL — %s, a month-first locale, keeps the compact face', (locale, face) => {
expect(formatDate(DAY, 'short', { locale })).toBe(face);
});

it('the face is the default face with the year shown, so the two never drift apart', () => {
expect(formatDate(DAY, 'short', { locale: 'zh-CN' })).toBe(formatDate(DAY, undefined, { locale: 'zh-CN', alwaysShowYear: true }));
});
});
52 changes: 46 additions & 6 deletions ui/packages/core/src/utils/date-display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,36 @@ function inZone(timeZone: string | undefined): Intl.DateTimeFormatOptions {
return timeZone ? { timeZone } : {};
}

/** Per locale tag (`''` for the runtime default): whether it writes a date month → day → year. */
const monthDayYearLocales = new Map<string, boolean>();

/**
* Whether `locale` writes a date with the month first, then the day, then the
* year (`en-US`: `Nov 15, 2026`), the order `formatDate`'s compact `'short'`
* face is laid out in. `zh-CN` (`2026年11月15日`), `de` (`15. Nov. 2026`) and
* `en-GB` (`15 Nov 2026`) do not. Asked of `Intl` itself, so no table of
* locales is kept here. A tag `Intl` refuses answers `true`: the compact face
* then runs as it always did and meets the same refusal.
*/
function writesMonthDayYear(locale: string | undefined): boolean {
const key = locale ?? '';
let answer = monthDayYearLocales.get(key);
if (answer === undefined) {
try {
const order = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: 'numeric' })
.formatToParts(new Date(2026, 10, 15))
.filter((p) => p.type === 'year' || p.type === 'month' || p.type === 'day')
.map((p) => p.type)
.join(',');
answer = order === 'month,day,year';
} catch {
answer = true;
}
monthDayYearLocales.set(key, answer);
}
return answer;
}

const dayPartsFormats = new Map<string, Intl.DateTimeFormat>();

/** The calendar day `date` falls on in `timeZone` (the viewer's when `undefined`); `month` is 0-based. */
Expand Down Expand Up @@ -595,12 +625,22 @@ export function formatDate(value: string | Date | number, style?: string, option
const zone = zoneFor(date);

if (effectiveStyle === 'short') {
// Compact format for mobile: "Jan 15, '24" / "1月 15, '24".
// Only the MONTH token is localized: the surrounding compact shape (day,
// apostrophe + 2-digit year) is a deliberate fixed layout for narrow
// cards, not a locale-derived one. The tag comes from `options.locale`
// like the default branch below — hardcoding `'en-US'` here made this the
// one branch that ignored a locale its caller had threaded (objectui#4272).
// Compact format with the year: "Jan 15, '24". The tag comes from
// `options.locale` like the default branch below — hardcoding `'en-US'`
// here made this the one branch that ignored a locale its caller had
// threaded (objectui#4272).
//
// The compact layout (day, apostrophe + 2-digit year after the month) is
// the order a month-first locale writes a date in, and only there. A
// locale that writes the date in another order gets its OWN face with the
// year, the one the default branch below draws with the year shown
// (objectstack#34228): `2026年11月15日` in `zh-CN`, `15. Nov. 2026` in
// `de`. Before, only the month token was localized into the fixed layout,
// so a `zh-CN` record page and its printed document read `11月 15, '26` —
// an English-order date in Chinese month words.
if (!writesMonthDayYear(options?.locale)) {
return date.toLocaleDateString(options?.locale, { year: 'numeric', month: 'short', day: 'numeric', ...inZone(zone) });
}
const month = date.toLocaleDateString(options?.locale, { month: 'short', ...inZone(zone) });
const { day, year } = dayIn(date, zone);
return `${month} ${day}, '${String(year).slice(-2)}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,14 @@ const OCT = new Date(2026, 9, 15, 12, 0, 0);
const INSTANT = new Date(2024, 0, 5, 8, 30, 0);

describe("formatDate 'short' honors the threaded locale (objectui#4272)", () => {
/**
* The two non-English faces below were `8月 15, '26` and `Okt 15, '26` until
* objectstack#34228: only the month token was localized into the English
* compact layout. A locale that does not write month → day → year now gets
* its own face with the year; the month is still the threaded locale's.
*/
it('zh renders the Chinese month, not the hardcoded English one', () => {
expect(formatDate(AUG, 'short', { locale: 'zh' })).toBe("8月 15, '26");
expect(formatDate(AUG, 'short', { locale: 'zh' })).toBe('2026年8月15日');
});

/**
Expand All @@ -63,7 +69,7 @@ describe("formatDate 'short' honors the threaded locale (objectui#4272)", () =>
* abbreviates it `Aug` — so this case is deliberately October.
*/
it('de renders the German month abbreviation', () => {
expect(formatDate(OCT, 'short', { locale: 'de' })).toBe("Okt 15, '26");
expect(formatDate(OCT, 'short', { locale: 'de' })).toBe('15. Okt. 2026');
});

/**
Expand Down
Loading
Loading