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/27498-display-locale-after-language-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/console': patch
---

fix(console): after a language switch, date and number cells format in the new language, not until the next page load

Clause-②: no
Metadata-protocol: none

Switching the language from the avatar menu changes the UI language first and writes the signed-in user's `sys_user.locale` second. The switch remounts `LocalizationFetchProvider`, whose read of `GET /api/v1/auth/me/localization` could reach the server before that write committed and answer the previous language (or, for a user with no stored language yet, the browser's `Accept-Language`). `useDisplayLocale` ranks that answer above the UI language, so under 中文 a list grid's date cells kept reading `Oct 11` beside Chinese headers until a full page load, while a record page opened by URL read `2026年10月11日`.

The provider now reads again on every write to the signed-in user's own `sys_user` row that reaches the data-invalidation bus (the language switch's write and the profile page's). The re-read starts after the write has settled and opts out of joining a request still in flight from before it, so its answer is the one that lands. The single date formatter (`formatDate` through `useDisplayLocale`) is unchanged.
107 changes: 105 additions & 2 deletions ui/apps/console/src/LocalizationFetchProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { LOCALE_SEED_STORAGE_KEY, LOCALE_STORAGE_KEY, useLocalization } from '@object-ui/i18n';
import { formatDateTime, setDisplayTimeZone } from '@object-ui/core';
import { act } from 'react';
import { LOCALE_SEED_STORAGE_KEY, LOCALE_STORAGE_KEY, useDisplayLocale, useLocalization } from '@object-ui/i18n';
import { formatDate, formatDateTime, setDisplayTimeZone } from '@object-ui/core';
import { notifyDataChanged } from '@object-ui/react';
// Test-only and off the `@object-ui/types` barrel; the vitest alias makes this
// the same module instance the provider's `sharedGetJson` uses.
import { resetInflightGetsForTesting } from '../../../packages/types/src/http-inflight';
import { LocalizationFetchProvider } from './LocalizationFetchProvider';
// Not on the `@object-ui/auth` barrel; the vitest alias maps that barrel to
// `packages/auth/src`, so this deep path is the SAME module instance the
Expand All @@ -26,6 +31,13 @@ import { SessionUserScope } from '../../../packages/auth/src/ActiveOrganizationS

const ENDPOINT = '/api/v1/auth/me/localization';

/** The signed-in user, swapped per test; `null` = signed out (the default). */
let authUser: { id: string } | null = null;
vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: authUser }),
}));

const ok = (body: unknown) => ({
ok: true,
status: 200,
Expand Down Expand Up @@ -255,4 +267,95 @@ describe('LocalizationFetchProvider', () => {
expect(screen.getByTestId('zone')).toHaveTextContent('∅|Sep 2, 2026, 03:00 AM');
});
});

// objectstack#27498 — the language switch writes `sys_user.locale` AFTER it
// remounts this provider, so the remount's read can answer the old language.
describe('re-reads after a write to the signed-in user\'s own row', () => {
const fetchMock = () => globalThis.fetch as never as ReturnType<typeof vi.fn>;

/** The date face a grid cell paints, with the locale `useDisplayLocale` hands it. */
function DisplayProbe() {
const locale = useDisplayLocale();
return (
<span data-testid="display">
{`${locale}|${formatDate('2026-10-11', undefined, { locale, alwaysShowYear: true })}`}
</span>
);
}

function renderDisplayProbe() {
return render(
<LocalizationFetchProvider endpoint={ENDPOINT}>
<DisplayProbe />
</LocalizationFetchProvider>,
);
}

const write = (recordId: string) =>
act(() => { notifyDataChanged({ objectName: 'sys_user', recordId }); });

// A request a failing case left pending would otherwise be joined by the
// next case's boot read through the shared in-flight registry.
afterEach(() => { authUser = null; resetInflightGetsForTesting(); });

it('a read that lost the race with the language write is replaced after the write', async () => {
authUser = { id: 'u1' };
fetchMock()
.mockResolvedValueOnce(ok({ authenticated: true, currency: null, locale: 'en-US', timezone: 'UTC' }))
.mockResolvedValueOnce(ok({ authenticated: true, currency: null, locale: 'zh-CN', timezone: 'UTC' }));

renderDisplayProbe();
await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('en-US|Oct 11, 2026'));

write('u1');

await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日'));
expect(fetchMock()).toHaveBeenCalledTimes(2);
});

it('the re-read does not join a request still in flight from before the write', async () => {
authUser = { id: 'u1' };
let answerStale: (v: unknown) => void = () => {};
fetchMock()
.mockImplementationOnce(() => new Promise((resolve) => { answerStale = resolve; }))
.mockResolvedValueOnce(ok({ authenticated: true, currency: null, locale: 'zh-CN', timezone: 'UTC' }));

renderDisplayProbe();
await waitFor(() => expect(fetchMock()).toHaveBeenCalledTimes(1));

write('u1');

// A second request went out of its own, and its answer is the one that lands.
await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日'));
expect(fetchMock()).toHaveBeenCalledTimes(2);
// The request that left before the write settles late and is dropped.
await act(async () => {
answerStale(ok({ authenticated: true, currency: null, locale: 'en-US', timezone: 'UTC' }));
});
expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日');
});

it('a write to another user\'s row reads nothing again', async () => {
authUser = { id: 'u1' };
fetchMock().mockResolvedValue(ok({ authenticated: true, currency: null, locale: 'en-US', timezone: 'UTC' }));

renderDisplayProbe();
await waitFor(() => expect(fetchMock()).toHaveBeenCalledTimes(1));

write('u2');
await new Promise((r) => setTimeout(r, 20));
expect(fetchMock()).toHaveBeenCalledTimes(1);
});

it('signed out, a sys_user write reads nothing again', async () => {
fetchMock().mockResolvedValue(ok({ authenticated: false }));

renderDisplayProbe();
await waitFor(() => expect(fetchMock()).toHaveBeenCalledTimes(1));

write('u1');
await new Promise((r) => setTimeout(r, 20));
expect(fetchMock()).toHaveBeenCalledTimes(1);
});
});
});
37 changes: 35 additions & 2 deletions ui/apps/console/src/LocalizationFetchProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,31 @@
* `MePermissionsProvider` but not its policy: that one is fail-closed and holds
* its loading state across the waits, this one keeps rendering throughout and
* simply fills the value in if and when an attempt succeeds.
*
* ## Read again after the signed-in user's own row changes (objectstack#27498)
*
* The answer's `locale` is the caller's language: their own `sys_user.locale`
* when set, else the request's `Accept-Language`, else the deployment default.
* `useDisplayLocale` ranks it above the active UI language, so every date and
* number renderer formats with whatever this provider last read. The language
* switch changes the UI language first and writes the column second
* (`useLanguageSelection`), and the switch remounts this provider through the
* console shell's `key={language}`. The remount's read can reach the server
* before the column write commits; it then answers the OLD language (on a user
* with no column yet, the browser's `Accept-Language`), and nothing read again,
* so under 中文 the grid's date cells said `Oct 11` until a full page load.
*
* So the read re-runs on every mutation of the signed-in user's `sys_user` row
* that reaches the data-invalidation bus, which every adapter write does
* (`useMutationInvalidationBridge`): the language switch's own write, and the
* profile page's. That re-read starts after the write has settled, and it does
* not join a request still in flight from before it (the shared in-flight
* registry would hand back the stale answer), so it is the one that lands.
*/
import { useEffect, useState } from 'react';
import { LocalizationProvider, cacheLanguageSeed, type LocalizationValue } from '@object-ui/i18n';
import { getSessionOwnerChangeCount } from '@object-ui/auth';
import { getSessionOwnerChangeCount, useAuth } from '@object-ui/auth';
import { useDataInvalidation } from '@object-ui/react';
import {
HttpFetchError,
backoffMs,
Expand Down Expand Up @@ -62,9 +83,17 @@ export function LocalizationFetchProvider({
children: React.ReactNode;
}) {
const [value, setValue] = useState<LocalizationValue>({});
const { user } = useAuth();
const userId = user?.id ? String(user.id) : undefined;
// Bumps on every write to the signed-in user's own row (objectstack#27498).
const userRowWrites = useDataInvalidation(userId ? 'sys_user' : undefined, userId);

useEffect(() => {
let cancelled = false;
// A re-read must not join a request that left before the write it answers
// to: `sharedGetJson` opts a request with a signal out of sharing. The
// boot read keeps sharing with `seedTenantLanguage()` (objectui#5544).
const reread = userRowWrites > 0 ? new AbortController() : undefined;

void (async () => {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
Expand All @@ -85,6 +114,7 @@ export function LocalizationFetchProvider({
const json = await sharedGetJson<MeLocalizationResponse>(endpoint, {
credentials: 'include',
headers: { Accept: 'application/json' },
signal: reread?.signal,
});
// Refresh the UI-language seed cache (objectui#4035) — the
// "revalidate" half of stale-while-revalidate. This boot has already
Expand Down Expand Up @@ -116,6 +146,8 @@ export function LocalizationFetchProvider({
});
return;
} catch (err) {
// Superseded by a later read (or unmounted): its abort is no failure.
if (cancelled) return;
// A real answer about this caller (401/403/404/500) will not change on
// a retry, and neither will the last attempt — either way, stop and
// leave the empty value. Cosmetic: renderers show plain numbers.
Expand All @@ -130,8 +162,9 @@ export function LocalizationFetchProvider({

return () => {
cancelled = true;
reread?.abort();
};
}, [endpoint]);
}, [endpoint, userRowWrites]);

return <LocalizationProvider value={value}>{children}</LocalizationProvider>;
}
Loading