diff --git a/.changeset/37575-first-render-grid-shell-passes.md b/.changeset/37575-first-render-grid-shell-passes.md new file mode 100644 index 00000000000..7cfe8c92621 --- /dev/null +++ b/.changeset/37575-first-render-grid-shell-passes.md @@ -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 + + + +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. diff --git a/ui/apps/console/src/pages/system/ProfilePage.tsx b/ui/apps/console/src/pages/system/ProfilePage.tsx index 5824dc38f93..a737095982b 100644 --- a/ui/apps/console/src/pages/system/ProfilePage.tsx +++ b/ui/apps/console/src/pages/system/ProfilePage.tsx @@ -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'; @@ -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. @@ -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(); diff --git a/ui/apps/console/src/pages/system/__tests__/ProfilePage.access.test.tsx b/ui/apps/console/src/pages/system/__tests__/ProfilePage.access.test.tsx index 7a8302469bb..7f9f2dca81e 100644 --- a/ui/apps/console/src/pages/system/__tests__/ProfilePage.access.test.tsx +++ b/ui/apps/console/src/pages/system/__tests__/ProfilePage.access.test.tsx @@ -50,7 +50,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({ vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), - useObjectTranslation: () => ({ t: translate, offerableLanguages: ['en', 'zh'], appContentLanguages: null }), + useObjectTranslation: () => ({ t: translate, offerableLanguages: ['en', 'zh'] }), })); vi.mock('@object-ui/react', async (importOriginal) => ({ diff --git a/ui/apps/console/src/pages/system/__tests__/ProfilePage.appLock-29748.test.tsx b/ui/apps/console/src/pages/system/__tests__/ProfilePage.appLock-29748.test.tsx index 797553b417c..06bb75472db 100644 --- a/ui/apps/console/src/pages/system/__tests__/ProfilePage.appLock-29748.test.tsx +++ b/ui/apps/console/src/pages/system/__tests__/ProfilePage.appLock-29748.test.tsx @@ -54,7 +54,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({ vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), - useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'], appContentLanguages: null }), + useObjectTranslation: () => ({ t: translate, language: 'en', offerableLanguages: ['en'] }), })); vi.mock('@object-ui/react', async (importOriginal) => ({ diff --git a/ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx b/ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx index 29463cf2257..2febd9e8e9f 100644 --- a/ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx +++ b/ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx @@ -102,8 +102,8 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ String(options?.[name] ?? ''), ), offerableLanguages: offerable.value, - appContentLanguages: appContent.value, }), + useAppContentLanguages: () => appContent.value, })); /** diff --git a/ui/apps/console/src/pages/system/__tests__/ProfilePage.pageHeader-12553.test.tsx b/ui/apps/console/src/pages/system/__tests__/ProfilePage.pageHeader-12553.test.tsx index af5fe1fea76..3c9f8e53157 100644 --- a/ui/apps/console/src/pages/system/__tests__/ProfilePage.pageHeader-12553.test.tsx +++ b/ui/apps/console/src/pages/system/__tests__/ProfilePage.pageHeader-12553.test.tsx @@ -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>()), - useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, offerableLanguages: ['en'], appContentLanguages: null }), + useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, offerableLanguages: ['en'] }), })); vi.mock('@object-ui/react', async (importOriginal) => ({ diff --git a/ui/apps/console/src/pages/system/__tests__/ProfilePage.sharedSelect-11865.test.tsx b/ui/apps/console/src/pages/system/__tests__/ProfilePage.sharedSelect-11865.test.tsx index f27e4760668..9e53b8be751 100644 --- a/ui/apps/console/src/pages/system/__tests__/ProfilePage.sharedSelect-11865.test.tsx +++ b/ui/apps/console/src/pages/system/__tests__/ProfilePage.sharedSelect-11865.test.tsx @@ -66,7 +66,6 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ useObjectTranslation: () => ({ t: (key: string, options?: Record) => String(options?.defaultValue ?? key), offerableLanguages: offerable.value, - appContentLanguages: null, }), })); diff --git a/ui/packages/app-shell/src/layout/LocaleSwitcher.tsx b/ui/packages/app-shell/src/layout/LocaleSwitcher.tsx index d933f849f3f..2fe9b30c41b 100644 --- a/ui/packages/app-shell/src/layout/LocaleSwitcher.tsx +++ b/ui/packages/app-shell/src/layout/LocaleSwitcher.tsx @@ -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: @@ -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'; @@ -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. diff --git a/ui/packages/app-shell/src/views/ObjectView.titleViewSwitcher-27594.test.tsx b/ui/packages/app-shell/src/views/ObjectView.titleViewSwitcher-27594.test.tsx index 83c5b147029..5da20cf71a9 100644 --- a/ui/packages/app-shell/src/views/ObjectView.titleViewSwitcher-27594.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.titleViewSwitcher-27594.test.tsx @@ -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(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 = () => @@ -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(); diff --git a/ui/packages/i18n/src/__tests__/provider-app-locale-restore.test.tsx b/ui/packages/i18n/src/__tests__/provider-app-locale-restore.test.tsx index 27c86a08914..961b7df2f29 100644 --- a/ui/packages/i18n/src/__tests__/provider-app-locale-restore.test.tsx +++ b/ui/packages/i18n/src/__tests__/provider-app-locale-restore.test.tsx @@ -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( @@ -46,7 +49,7 @@ function mountConsole( ...props, children, }); - return renderHook(() => useObjectTranslation(), { wrapper }); + return renderHook(() => useReaders(), { wrapper }); } beforeEach(() => { @@ -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 @@ -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'])); }); @@ -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(); diff --git a/ui/packages/i18n/src/__tests__/provider-appContentLanguages-37575.test.tsx b/ui/packages/i18n/src/__tests__/provider-appContentLanguages-37575.test.tsx new file mode 100644 index 00000000000..27cc351d189 --- /dev/null +++ b/ui/packages/i18n/src/__tests__/provider-appContentLanguages-37575.test.tsx @@ -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((resolve) => { answer = resolve; }); + + function TranslationReader() { + renders.translation += 1; + const { language } = useObjectTranslation(); + return {language}; + } + // 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 {languages ? languages.join(',') : 'unknown'}; + } + + render( + + + + , + ); + 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 {languages === null ? 'unknown' : languages.join(',')}; + } + render(); + expect(screen.getByTestId('app-languages')).toHaveTextContent('unknown'); + }); +}); diff --git a/ui/packages/i18n/src/index.ts b/ui/packages/i18n/src/index.ts index 15667463d99..e50c1b337de 100644 --- a/ui/packages/i18n/src/index.ts +++ b/ui/packages/i18n/src/index.ts @@ -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. diff --git a/ui/packages/i18n/src/provider.tsx b/ui/packages/i18n/src/provider.tsx index 5173012c6f3..7dd93afab7b 100644 --- a/ui/packages/i18n/src/provider.tsx +++ b/ui/packages/i18n/src/provider.tsx @@ -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(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(null); + /** * Re-render a reader when the store GAINS translations, not only when the * language changes (objectui#10382). @@ -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), + ), ); } @@ -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 */ diff --git a/ui/packages/layout/src/NavigationRenderer.tsx b/ui/packages/layout/src/NavigationRenderer.tsx index 9654e1482af..2d15e71b9e1 100644 --- a/ui/packages/layout/src/NavigationRenderer.tsx +++ b/ui/packages/layout/src/NavigationRenderer.tsx @@ -2185,6 +2185,8 @@ const NavigationItemRenderer = React.memo(NavigationItemRow, sameRowAnswers); type NavRowRendererProps = NavItemRendererProps; const ROW_TARGET_RESOLVERS = new Set(['resolveTargetLabel', 'resolveTargetIcon', 'resolveTargetColor']); +/** The props a leaf row is compared by what they answer for it, not by identity. */ +const ROW_ANSWER_PROPS = new Set([...ROW_TARGET_RESOLVERS, 'checkCap']); /** * objectstack#37575 — whether a row's new props draw what its current ones draw. @@ -2198,20 +2200,29 @@ const ROW_TARGET_RESOLVERS = new Set(['resolveTargetLabel', 'resolveTargetIcon', * has, which still give those answers. A group draws its entries, and each of * those asks its own questions, so a group with any new resolver is redrawn and * its entries are compared one by one. + * + * The capability checker is compared the same way: the host rebuilds it with + * the resolvers, and a leaf row asks it about its own `requiresObject` and + * `requiresService` only. */ function sameRowAnswers(prev: NavRowRendererProps, next: NavRowRendererProps): boolean { const keys = new Set([...Object.keys(prev), ...Object.keys(next)]); for (const key of keys) { - if (ROW_TARGET_RESOLVERS.has(key)) continue; + if (ROW_ANSWER_PROPS.has(key)) continue; if (!Object.is(prev[key as keyof NavRowRendererProps], next[key as keyof NavRowRendererProps])) return false; } if ( prev.resolveTargetLabel === next.resolveTargetLabel && prev.resolveTargetIcon === next.resolveTargetIcon && - prev.resolveTargetColor === next.resolveTargetColor + prev.resolveTargetColor === next.resolveTargetColor && + prev.checkCap === next.checkCap ) return true; const { item, t, locale } = next; if (item.type === 'group') return false; + const requiresObject = (item as { requiresObject?: string }).requiresObject; + const requiresService = (item as { requiresService?: string }).requiresService; + if (requiresObject && prev.checkCap('object', requiresObject) !== next.checkCap('object', requiresObject)) return false; + if (requiresService && prev.checkCap('service', requiresService) !== next.checkCap('service', requiresService)) return false; if (resolveNavItemLabel(item, t, prev.resolveTargetLabel, locale) !== resolveNavItemLabel(item, t, next.resolveTargetLabel, locale)) return false; if (resolveNavItemIcon(item, prev.resolveTargetIcon) !== resolveNavItemIcon(item, next.resolveTargetIcon)) return false; if (item.type === 'object' && item.objectName) { diff --git a/ui/packages/layout/src/__tests__/NavigationRenderer.rowMemo-37575.test.tsx b/ui/packages/layout/src/__tests__/NavigationRenderer.rowMemo-37575.test.tsx index c50f7489d9b..4abb2f6611c 100644 --- a/ui/packages/layout/src/__tests__/NavigationRenderer.rowMemo-37575.test.tsx +++ b/ui/packages/layout/src/__tests__/NavigationRenderer.rowMemo-37575.test.tsx @@ -131,6 +131,23 @@ describe('NavigationRenderer: a row with nothing new to draw is not redrawn (obj expect(screen.getByText('Opportunities')).toBeInTheDocument(); }); + it('a new capability checker that answers the same for every row redraws no leaf row, and one that hides a row removes it', () => { + const { drawn, view } = setup(); + const items = [ + ...ITEMS, + { id: 'nav_tenants', type: 'object', objectName: 'sys_tenant', requiresObject: 'sys_tenant' }, + ] as NavigationItem[]; + const r = resolvers({ ...LABELS, sys_tenant: 'Tenants' }); + const { rerender } = render(view({ ...r, items, checkCapability: () => true })); + expect(screen.getByText('Tenants')).toBeInTheDocument(); + drawn.length = 0; + rerender(view({ ...r, items, checkCapability: () => true })); + expect(drawn).toEqual([]); + rerender(view({ ...r, items, checkCapability: (kind, name) => !(kind === 'object' && name === 'sys_tenant') })); + expect(screen.queryByText('Tenants')).toBeNull(); + expect(drawn).toEqual([]); + }); + it('a prop other than the resolvers is still compared by identity: a new evaluator redraws every row', () => { const { drawn, view } = setup(); const r = resolvers(LABELS); diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index e6609742af5..a0dab57f1e4 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2372,10 +2372,18 @@ export const ObjectGrid: React.FC = ({ ); } + // The loading face draws inside the SAME root element the loaded table + // draws in (the final return below: same type, same place, same ref), so + // React keeps that element across the swap and `gridRoot` — and the list + // page's scope answer read off it — is already known when the rows first + // render: a list page's rows draw once, without row-end controls + // (objectstack#37575). return ( -
-
-

{t('grid.loading')}

+
+
+
+

{t('grid.loading')}

+
); } diff --git a/ui/packages/plugin-grid/src/__tests__/listGridFirstRender-37575.test.tsx b/ui/packages/plugin-grid/src/__tests__/listGridFirstRender-37575.test.tsx new file mode 100644 index 00000000000..a56ae92a14f --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/listGridFirstRender-37575.test.tsx @@ -0,0 +1,128 @@ +/** + * 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 — a list page's grid draws its rows once before they + * first paint. + * + * On a list page's first load three state writes each drew the whole table + * again between its rows' first render and their first paint: + * + * - the grid's root element was set only once the rows drew, so the rows drew + * first with row-end controls, then the list page scope answered and they + * drew again without them (and the table's right-edge shadow with them); + * - the inline-action fold held its host element in state, so mounting the + * host drew the grid again; + * - the record verdicts were published as a new (empty) map on every read, + * though nothing was answered yet, so the grid drew again for nothing. + */ +import { describe, it, expect, beforeEach } from 'vitest'; +import { render, renderHook, screen, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { useListPageScope } from '../listPageScope'; +import { useInlineRowActionFold } from '../objectGridInlineActionFold'; +import { __clearRecordCrudVerdictCache, useRecordCrudVerdicts } from '../hooks/useRecordCrudVerdicts'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; + +registerAllFields(); +beforeEach(() => __clearRecordCrudVerdictCache()); + +const apiFetch = async (): Promise => + ({ ok: true, status: 200, json: async () => ({ allowed: true, layers: [] }) }) as unknown as Response; + +const SCHEMA: any = { + type: 'object-grid', + objectName: 'test_object', + columns: [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount', type: 'number' }, + ], + data: { + provider: 'value', + items: [ + { id: '1', name: 'Alice', amount: 100 }, + { id: '2', name: 'Bob', amount: 200 }, + ], + }, + rowActionDefs: [{ name: 'clone', label: 'Clone' }], +}; + +/** A page bar that registers its page column as a list page scope, as the Console's do. */ +const PageBar: React.FC = () => { + const [scope, setScope] = React.useState(null); + useListPageScope(scope); + return
setScope(el?.parentElement ?? null)} data-testid="page-bar" />; +}; + +const Providers: React.FC<{ children: React.ReactNode }> = ({ children }) => ( + + {children} + +); + +describe('objectstack#37575 — a list page grid draws its rows once before they paint', () => { + it('a row-end control never enters the DOM of a list page grid, not even for its first render', async () => { + // Read off the nodes added AND removed: a control drawn by one commit and + // taken away by the next, before this observer runs, shows as removed. + const CONTROL = '[data-testid="row-action-trigger"], th[data-column-key="_actions"]'; + const seen: string[] = []; + const note = (node: Node) => { + if (node instanceof HTMLElement && (node.matches(CONTROL) || node.querySelector(CONTROL))) seen.push(node.tagName); + }; + const observer = new MutationObserver((records) => { + for (const record of records) { + record.addedNodes.forEach(note); + record.removedNodes.forEach(note); + } + }); + // The page bar is up before the grid mounts, as on a Console list page, + // where it draws while the rows are still being read. + const page = (withGrid: boolean) => ( + +
+ + {withGrid && {}} onDelete={() => {}} />} +
+
+ ); + const { rerender } = render(page(false)); + observer.observe(document.body, { childList: true, subtree: true }); + rerender(page(true)); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); + observer.disconnect(); + expect(seen).toEqual([]); + }); + + it('attaching the inline-action fold to its host does not render the grid again', () => { + let renders = 0; + const { result } = renderHook(() => { + renders += 1; + return useInlineRowActionFold([], '[]'); + }); + const before = renders; + const host = document.createElement('div'); + act(() => result.current.hostRef(host)); + act(() => result.current.hostRef(null)); + expect(renders).toBe(before); + }); + + it('record verdicts read again with nothing answered keep the same lookup', () => { + const { result, rerender } = renderHook( + ({ ids }: { ids: string[] }) => useRecordCrudVerdicts({ objectName: 'test_object', recordIds: ids, update: true }), + { wrapper: Providers, initialProps: { ids: [] as string[] } }, + ); + const first = result.current; + rerender({ ids: ['1', '2'] }); + expect(result.current).toBe(first); + expect(result.current('1', 'update')).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts b/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts index c4a90335f0a..e87249b3caa 100644 --- a/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts +++ b/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts @@ -498,6 +498,12 @@ function lookupOf( return Object.assign(lookup, { requestVerdicts, pending, settling, current }); } +function sameVerdicts(a: ReadonlyMap, b: ReadonlyMap): boolean { + if (a.size !== b.size) return false; + for (const [key, verdict] of a) if (b.get(key) !== verdict) return false; + return true; +} + export function useRecordCrudVerdicts(opts: { /** The object the rows belong to; absent (element data source) = no question to ask. */ objectName?: string; @@ -549,7 +555,15 @@ export function useRecordCrudVerdicts(opts: { // What was published last, written in the same stroke as `setVerdicts`: a // wait re-asked as soon as the wire settles runs before the re-render that // publishes the answer, so it reads the answer here (objectstack#35795). - const publishedRef = React.useRef>(new Map()); + const publishedRef = React.useRef>(verdicts); + // Publishes only an answer that differs: re-publishing the same verdicts as + // a new map would draw every row of the grid again for nothing — on a + // list's first load, between its rows' first render and their first paint. + const publishVerdicts = React.useCallback((next: ReadonlyMap) => { + if (sameVerdicts(publishedRef.current, next)) return; + publishedRef.current = next; + setVerdicts(next); + }, []); const current = React.useCallback( (recordId, operation) => recordId == null ? undefined : publishedRef.current.get(`${operation}:${String(recordId)}`), @@ -577,8 +591,7 @@ export function useRecordCrudVerdicts(opts: { if (wantUpdate) operations.push('update'); if (wantDelete) operations.push('delete'); if (!objectName || ids.length === 0 || operations.length === 0) { - publishedRef.current = new Map(); - setVerdicts(publishedRef.current); + publishVerdicts(new Map()); setPending(false); wireRef.current = null; return; @@ -600,8 +613,7 @@ export function useRecordCrudVerdicts(opts: { if (typeof verdict === 'boolean') next.set(`${operation}:${id}`, verdict); } } - publishedRef.current = next; - setVerdicts(next); + publishVerdicts(next); }; const settled: Promise[] = []; @@ -642,7 +654,7 @@ export function useRecordCrudVerdicts(opts: { return () => { cancelled = true; }; - }, [objectName, ids, wantUpdate, wantDelete, updateOnMount, demanded, apiFetch, principal, invalidationNonce]); + }, [objectName, ids, wantUpdate, wantDelete, updateOnMount, demanded, apiFetch, principal, invalidationNonce, publishVerdicts]); return React.useMemo( () => lookupOf(verdicts, requestVerdicts, pending, settling, current), diff --git a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts index e02f996eb02..3d92f90d08f 100644 --- a/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts +++ b/ui/packages/plugin-grid/src/objectGridInlineActionFold.ts @@ -62,7 +62,6 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { folded: boolean; actionsFrozen: boolean; } { - const [host, setHost] = React.useState(null); const [folded, setFolded] = React.useState(false); // The decision the readings act on, written only where it is made. const foldedRef = React.useRef(false); @@ -79,8 +78,13 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { setFolded(false); }, [rows, columnsKey]); - React.useLayoutEffect(() => { - if (!host || typeof window === 'undefined') return undefined; + // The host is watched from its ref, not held in state: mounting it must not + // draw the grid a second time before its first paint. + const detachRef = React.useRef<(() => void) | null>(null); + const hostRef = React.useCallback((host: HTMLElement | null) => { + detachRef.current?.(); + detachRef.current = null; + if (!host || typeof window === 'undefined') return; let resizes: ResizeObserver | null = null; let mounts: MutationObserver | null = null; let watched: HTMLElement | null = null; @@ -167,12 +171,12 @@ export function useInlineRowActionFold(rows: unknown, columnsKey: string): { }); mounts.observe(host, { childList: true, subtree: true }); } - return () => { + detachRef.current = () => { if (frame) window.cancelAnimationFrame(frame); mounts?.disconnect(); resizes?.disconnect(); }; - }, [host]); + }, []); - return { hostRef: setHost, folded, actionsFrozen }; + return { hostRef, folded, actionsFrozen }; } diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index c926e890845..0b797714097 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -497,10 +497,13 @@ describe('ListView.contractEnvelope-6917', () => { } as unknown as ListViewSchema); /** - * Render against a `find()` answering `answer` and return the record-count - * bar's text. Scoped by test id rather than queried globally: the digits of a - * total can collide with row text, and `queryByText` throws on multiple - * matches exactly as it does on none. + * Render against a `find()` answering `answer` and return the record count's + * text. A grid draws the count in its resident footer row + * (`data-table-summary-lead`, objectstack#35702), and the record-count bar is + * then not drawn; it showed here only for the frames before the grid said so, + * so it is not read. Scoped by test id rather than queried globally: the + * digits of a total can collide with row text, and `queryByText` throws on + * multiple matches exactly as it does on none. */ async function recordCountText(answer: unknown): Promise { const ds = makeDataSource(answer); @@ -513,12 +516,12 @@ describe('ListView.contractEnvelope-6917', () => { , ); - let bar!: HTMLElement; + let lead!: HTMLElement; await waitFor(() => { - bar = getByTestId('record-count-bar'); - expect(within(bar).getByText(/record/)).toBeInTheDocument(); + lead = getByTestId('data-table-summary-lead'); + expect(lead).toHaveTextContent(/record/); }); - return within(bar).getByText(/record/).textContent ?? ''; + return lead.textContent ?? ''; } describe('ListView find() envelope — objectui#6917', () => { diff --git a/ui/packages/react/src/index.ts b/ui/packages/react/src/index.ts index 9d3eb873a26..249307d9807 100644 --- a/ui/packages/react/src/index.ts +++ b/ui/packages/react/src/index.ts @@ -113,6 +113,7 @@ export { useObjectLabel, useSafeFieldLabel, useI18nContext, + useAppContentLanguages, createI18n, getDirection, getAvailableLanguages,