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
28 changes: 28 additions & 0 deletions .changeset/37575-first-render-grid-shell-passes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@object-ui/plugin-grid': patch
'@object-ui/i18n': patch
'@object-ui/react': patch
'@object-ui/layout': patch
'@object-ui/app-shell': patch
'@object-ui/console': patch
'@objectstack/console': patch
---

perf(console): a list page draws its rows once before they paint, and the shell re-renders less during first load

Clause-②: yes (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value, metadata type or stored row is added, removed or renamed, so there is nothing for `objectstack migrate meta` to rewrite. What narrows is the value two React hooks of @object-ui/i18n return: `useObjectTranslation()` and `useI18nContext()` no longer carry `appContentLanguages`, which moved to its own hook. Its consumer is code, and the compiler names every reader left behind. `runtime-interface-only` does not fit on a checked fact: the context value's interface is not exported, so it cannot be named by path. -->

On a list page's first load the grid drew its whole table several times between the rows' first render and their first paint: once with row-end controls before the list page scope was known, once when the inline-action fold found its host, and once when the record verdicts were republished with nothing new in them. The rows now draw once, without row-end controls, and those passes are gone.

The shell does less during first load too. The app's own locale list lands after the console has drawn; it used to re-render every component that reads a translation, about 1,900 of them. It is now read with `useAppContentLanguages()` from `@object-ui/i18n`, and only the language menus re-render for it. `useObjectTranslation()` and `useI18nContext()` no longer carry `appContentLanguages`. A sidebar entry is not redrawn when a new capability checker gives it the same answer.

Nothing changes in what the list, the sidebar or the language menus show.

**BREAKING** (`@object-ui/i18n`, and `@object-ui/react`, which re-exports the same two hooks: their return values), shipped as `patch`: the change is not to the metadata protocol (`Metadata-protocol: none`).

- Removed: the `appContentLanguages` field from what `useObjectTranslation()` and `useI18nContext()` return, whether they are imported from `@object-ui/i18n` or from `@object-ui/react`. It was added there by #36040.
- Use instead: `useAppContentLanguages()`, which both entries now export: `@object-ui/i18n`, and `@object-ui/react` beside the two hooks. It returns the same value, the app's declared content languages or `null` while they are unknown, and `null` outside an `I18nProvider`.
- Why: the list lands after the console has drawn. While it rode on the translation context, its arrival re-rendered every component that reads a translation, about 1,900 of them on first load. In its own context only the components that read it re-render.
7 changes: 4 additions & 3 deletions ui/apps/console/src/pages/system/ProfilePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
import { useUpload } from '@object-ui/fields';
import { toast } from 'sonner';
import { ConsolePageHeader } from '@object-ui/app-shell';
import { resolveBuiltInLanguage, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
import { resolveBuiltInLanguage, useAppContentLanguages, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
import { useAdapter, extractFieldErrors, extractWriteErrorMessage } from '@object-ui/react';
import { usePermissions } from '@object-ui/permissions';
import { resolveFieldAffordance } from '@object-ui/core';
Expand Down Expand Up @@ -589,7 +589,7 @@ interface LanguageCardProps {
* (every platform locale table language, as table tags, objectstack#35425),
* which is what `LocaleSwitcher` renders too. ⛔ No second list is introduced here.
* A chosen language the deployment's own content is not translated into
* (outside the provider's `appContentLanguages`, when that is known) carries
* (outside `useAppContentLanguages()`, when that is known) carries
* the same one-line hint the globe menu shows on that row.
* A stored tag that is not in that set is prepended so the control shows the
* truth rather than rendering blank.
Expand All @@ -606,7 +606,8 @@ interface LanguageCardProps {
* card's own "hidden ... rather than rendering a control that answers 403".
*/
function LanguageCard({ userId }: LanguageCardProps) {
const { t, offerableLanguages, appContentLanguages } = useObjectTranslation();
const { t, offerableLanguages } = useObjectTranslation();
const appContentLanguages = useAppContentLanguages();
const adapter = useAdapter();
const perms = usePermissions();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({

vi.mock('@object-ui/i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useObjectTranslation: () => ({ t: translate, offerableLanguages: ['en', 'zh'], appContentLanguages: null }),
useObjectTranslation: () => ({ t: translate, offerableLanguages: ['en', 'zh'] }),
}));

vi.mock('@object-ui/react', async (importOriginal) => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({

vi.mock('@object-ui/i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'], appContentLanguages: null }),
useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'] }),
}));

vi.mock('@object-ui/react', async (importOriginal) => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
String(options?.[name] ?? ''),
),
offerableLanguages: offerable.value,
appContentLanguages: appContent.value,
}),
useAppContentLanguages: () => appContent.value,
}));

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({
/** Each call site's key, so the pin names the pack key it reads. */
vi.mock('@object-ui/i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, offerableLanguages: ['en'], appContentLanguages: null }),
useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, offerableLanguages: ['en'] }),
}));

vi.mock('@object-ui/react', async (importOriginal) => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
useObjectTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) => String(options?.defaultValue ?? key),
offerableLanguages: offerable.value,
appContentLanguages: null,
}),
}));

Expand Down
7 changes: 4 additions & 3 deletions ui/packages/app-shell/src/layout/LocaleSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* (objectstack#35425, which reversed the narrowing to the app's own locale
* list). A language the app's own content is not translated into stays
* selectable and carries one muted line saying that content shows in the
* default language; the provider's `appContentLanguages` says which those are,
* default language; `useAppContentLanguages()` says which those are,
* and a page that does not know (signed out) marks none. This file owns the
* *labels* and that hint, because the native
* names are the one piece of that no API response supplies:
Expand All @@ -34,7 +34,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@object-ui/components';
import { resolveBuiltInLanguage, useObjectTranslation } from '@object-ui/i18n';
import { resolveBuiltInLanguage, useAppContentLanguages, useObjectTranslation } from '@object-ui/i18n';
import { PLATFORM_LOCALES } from '@objectstack/spec/system';
import { confirmUnsavedLeave } from '../chrome/unsavedEdits.js';
import { useLanguageSelection } from '../hooks/useUserLocale.js';
Expand Down Expand Up @@ -82,7 +82,8 @@ export function localeLabel(code: string): string {
}

export function LocaleSwitcher() {
const { t, language, offerableLanguages, appContentLanguages } = useObjectTranslation();
const { t, language, offerableLanguages } = useObjectTranslation();
const appContentLanguages = useAppContentLanguages();
// ⛔ Not the i18n context's bare `changeLanguage`: while signed in the switch
// has to reach `sys_user.locale`, or the globe and the profile page go on
// naming two settings (objectui#10059). Signed out it IS the bare switch.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,16 @@ function openSwitcher() {
return screen.getByTestId('list-view-switcher-menu');
}

/** The list's footer once its load settled: it says how many records the view holds. */
/**
* The list's footer count once its load settled: it says how many records the
* view holds. A grid draws it in its resident footer row
* (`data-table-summary-lead`, objectstack#35702) and the record-count bar then
* not at all; any other view draws it in the bar.
*/
const FOOTER_COUNT = '[data-testid="data-table-summary-lead"], [data-testid="record-count-bar"]';
const footerCountElement = () => document.querySelector<HTMLElement>(FOOTER_COUNT);
const footerCount = () =>
waitFor(() => expect(screen.getByTestId('record-count-bar')).toHaveTextContent('1 record'), { timeout: 5000 });
waitFor(() => expect(footerCountElement()).toHaveTextContent('1 record'), { timeout: 5000 });

/** The ids of the rows in the dropdown's All section, in order. */
const allRowIds = () =>
Expand Down Expand Up @@ -308,7 +315,7 @@ describe('objectstack#27594 — the list title is the view switcher', () => {
// phone as it was).
await footerCount();
expect(screen.getByTestId('list-view-switcher-count')).toHaveClass('max-sm:hidden');
expect(screen.getByTestId('list-toolbar-leading').contains(screen.getByTestId('record-count-bar'))).toBe(false);
expect(screen.getByTestId('list-toolbar-leading').contains(footerCountElement())).toBe(false);
expect(screen.queryByTestId('view-tab-bar')).toBeNull();
expect(screen.queryByTestId('view-tab-row')).toBeNull();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ import { describe, it, expect, beforeEach } from 'vitest';
import { renderHook, act, waitFor } from '@testing-library/react';
import React from 'react';
import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
import { I18nProvider, useObjectTranslation, LOCALE_STORAGE_KEY } from '../provider';
import { I18nProvider, useAppContentLanguages, useObjectTranslation, LOCALE_STORAGE_KEY } from '../provider';

/** The translation hook and the app-content answer, read together. */
const useReaders = () => ({ ...useObjectTranslation(), appContentLanguages: useAppContentLanguages() });

/** The console's wiring: app packs fetched on demand, nothing in `resources`. */
function mountConsole(
Expand All @@ -46,7 +49,7 @@ function mountConsole(
...props,
children,
});
return renderHook(() => useObjectTranslation(), { wrapper });
return renderHook(() => useReaders(), { wrapper });
}

beforeEach(() => {
Expand Down Expand Up @@ -178,7 +181,7 @@ describe('app-locale restore (lockstep with the switcher)', () => {
config: { defaultLanguage: 'en', detectBrowserLanguage: false },
children,
});
const { result } = renderHook(() => useObjectTranslation(), { wrapper });
const { result } = renderHook(() => useReaders(), { wrapper });

// Nothing can fetch `th` here, so accepting it would be the very "locked to
// a locale with no translations" state the guard exists to prevent. The
Expand Down Expand Up @@ -272,7 +275,7 @@ describe('appContentLanguages — the table languages the app list covers', () =
loadLocales: async () => ['en', 'zh', 'th'],
children,
});
const { result } = renderHook(() => useObjectTranslation(), { wrapper });
const { result } = renderHook(() => useReaders(), { wrapper });

await waitFor(() => expect(result.current.appContentLanguages).toEqual(['en', 'zh-Hans']));
});
Expand All @@ -297,7 +300,7 @@ describe('appContentLanguages — the table languages the app list covers', () =
children,
}),
);
const { result, rerender } = renderHook(() => useObjectTranslation(), { wrapper });
const { result, rerender } = renderHook(() => useReaders(), { wrapper });

await waitFor(() => expect(result.current.appContentLanguages).toEqual(['en', 'zh-Hans']));
rerender();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* 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#37575: the app's locale list lands after the console has drawn,
* and only its readers re-render for it.
*
* In the provider's main context it gave every `useObjectTranslation` reader a
* new value: on a list page's first load that was one more pass over about
* 1,900 components before the rows drew, for an answer only a language menu
* reads.
*/
import { describe, it, expect } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { I18nProvider, useAppContentLanguages, useObjectTranslation } from '../provider';

describe('the app locale list reaches its readers only (objectstack#37575)', () => {
it('a translation reader is not re-rendered when the list lands; a reader of the list is', async () => {
const renders = { translation: 0 };
let answer: (codes: string[]) => void = () => {};
const loadLocales = () => new Promise<string[]>((resolve) => { answer = resolve; });

function TranslationReader() {
renders.translation += 1;
const { language } = useObjectTranslation();
return <span>{language}</span>;
}
// Memoised, as a component deep in the console is under a parent that
// does not re-render: only a context it reads can redraw it.
const Reader = React.memo(TranslationReader);
function ListReader() {
const languages = useAppContentLanguages();
return <span data-testid="app-languages">{languages ? languages.join(',') : 'unknown'}</span>;
}

render(
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} loadLocales={loadLocales}>
<Reader />
<ListReader />
</I18nProvider>,
);
expect(screen.getByTestId('app-languages')).toHaveTextContent('unknown');
const before = renders.translation;

answer(['en', 'zh']);
await waitFor(() => expect(screen.getByTestId('app-languages')).toHaveTextContent('en,zh-Hans'));
expect(renders.translation).toBe(before);
});

it('outside a provider the list is not known', () => {
function ListReader() {
const languages = useAppContentLanguages();
return <span data-testid="app-languages">{languages === null ? 'unknown' : languages.join(',')}</span>;
}
render(<ListReader />);
expect(screen.getByTestId('app-languages')).toHaveTextContent('unknown');
});
});
1 change: 1 addition & 0 deletions ui/packages/i18n/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export {
export {
I18nProvider,
useObjectTranslation,
useAppContentLanguages,
useI18nContext,
// Language-preference persistence: the key the provider writes, and the
// reader apps that bring their own i18next instance need to honour it.
Expand Down
58 changes: 35 additions & 23 deletions ui/packages/i18n/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -494,28 +494,22 @@ interface I18nContextValue {
* is no longer narrowed to the app's own locale list: a language the app
* ships no translation for is still selectable — the interface renders in
* it, the app's own content falls back to the deployment's default language
* — and {@link I18nContextValue.appContentLanguages} says which those are.
* — and {@link useAppContentLanguages} says which those are.
* Never `null`: the list does not wait on the app's answer any more.
*/
offerableLanguages: readonly string[];
/**
* The table languages the app's own locale list covers (objectui#4039), as
* table tags, de-duplicated, in the app's order: the languages in which the
* app's content (object, field and view labels) is translated too. A menu
* marks every other offered language with a hint that the app's content
* shows in the default language (objectstack#35425).
*
* `null` means "not known": still asking, no
* {@link I18nProviderProps.loadLocales} wiring, a signed-out page (the
* console asks only with a session), a failed read, or an answer that names
* no table language. Mark nothing then: a hint on every row would claim a
* fact nobody has read.
*/
appContentLanguages: readonly string[] | null;
}

const ObjectI18nContext = createContext<I18nContextValue | null>(null);

/**
* The table languages the app's own content is translated into, in a context
* of its own ({@link useAppContentLanguages}). The app's list lands after the
* console has drawn; in the main context it gave every translated component a
* new value to re-render for, though only a language menu reads it.
*/
const AppContentLanguagesContext = createContext<readonly string[] | null>(null);

/**
* Re-render a reader when the store GAINS translations, not only when the
* language changes (objectui#10382).
Expand Down Expand Up @@ -910,15 +904,18 @@ export function I18nProvider({
direction,
i18n: i18nInstance,
offerableLanguages,
appContentLanguages,
}),
[language, direction, i18nInstance, loadLanguage, offerableLanguages, appContentLanguages],
[language, direction, i18nInstance, loadLanguage, offerableLanguages],
);

return React.createElement(
ObjectI18nContext.Provider,
{ value: contextValue },
React.createElement(I18nextProvider, { i18n: i18nInstance }, children),
React.createElement(
AppContentLanguagesContext.Provider,
{ value: appContentLanguages },
React.createElement(I18nextProvider, { i18n: i18nInstance }, children),
),
);
}

Expand Down Expand Up @@ -1014,14 +1011,29 @@ export function useObjectTranslation(ns?: string) {
* (objectstack#35425), inside a provider or not.
*/
offerableLanguages: context ? context.offerableLanguages : BUILT_IN_LANGUAGE_CODES,
/**
* The table languages the app's own content is translated into, or `null`
* when not known. Outside a provider there is nobody to ask: `null`.
*/
appContentLanguages: context ? context.appContentLanguages : null,
};
}

/**
* The table languages the app's own locale list covers (objectui#4039), as
* table tags, de-duplicated, in the app's order: the languages in which the
* app's content (object, field and view labels) is translated too. A menu
* marks every other offered language with a hint that the app's content
* shows in the default language (objectstack#35425).
*
* `null` means "not known": still asking, no
* {@link I18nProviderProps.loadLocales} wiring, a signed-out page (the
* console asks only with a session), a failed read, an answer that names no
* table language, or no provider at all. Mark nothing then: a hint on every
* row would claim a fact nobody has read.
*
* Its own hook, not a field of {@link useObjectTranslation}: the answer lands
* after first paint, and only its readers re-render for it (objectstack#37575).
*/
export function useAppContentLanguages(): readonly string[] | null {
return useContext(AppContentLanguagesContext);
}

/**
* Hook to access the i18n context directly
*/
Expand Down
Loading
Loading