Repository navigation
perf(core): render Text, Heading, Kbd, Button, IconButton and TopNav in React Server Components - #8443
perf(core): render Text, Heading, Kbd, Button, IconButton and TopNav in React Server Components#8443rhagigi wants to merge 5 commits into
Conversation
…d the platform glyph become client parts Text and Heading carried 'use client' only for the truncation tooltip, which measures overflow when maxLines > 0. That moves into a TruncatedText client part, rendered only when maxLines > 0 with the tooltip on. Kbd's only client-side work is picking the 'mod' glyph after hydration; shortcuts with 'mod' render a PlatformKbd client part, all others render on the server. Public APIs are unchanged; both client parts are listed as client islands in serverSafeComponents.test.ts.
Text and Heading rendered the TruncatedText client part only for maxLines > 0, so a caller toggling maxLines between a number and 0 (show more / less) switched the root element type and remounted the element and its children. Any explicit maxLines now takes the client part, which measures nothing at 0, so the element stays mounted; Text and Heading without maxLines still render on the server with no client code. KbdView's comment now says where platform detection happens.
`@astryxdesign/core/Button` and `/IconButton` gain a `react-server` export condition (first, so a bundler that also honors `source` picks it, and generated by scripts/sync-exports.js for any directory with an index.server.ts). It resolves a server shell, ButtonShell.tsx, which imports no client React API. A Button whose props are data renders on the server: the root element, classes, tokens, theme attributes and content the client Button renders for those props. Both renderers share buttonStyles.stylex.ts and ButtonContent.tsx. The client Button loads only for what needs it: - clickAction, isLoading, tooltip, a ref or any function prop render the client Button directly; - every server-rendered Button sits in ButtonContextGate, which reads the size, ButtonGroup, InputGroup and LinkProvider contexts a Server Component cannot, hands over to a lazily loaded client Button when one applies, and installs the shared touch press controller; - an icon in the slot is sized through IconSizeScope. pressable.ts holds the press marker without the controller's module state, and pressableCoverage.test.ts counts a server shell that spreads the marker and renders a marked gate as marked. Client imports and the public API are unchanged.
`@astryxdesign/core/TopNav` gains a `react-server` entry. TopNav and TopNavItem resolve server shells (TopNavShell.tsx, TopNavItemShell.tsx) that render the desktop bar and its items on the server with the markup the client components render in their default mode; the heading, menus, mega menu and render context stay client modules, as through index.ts. AppShell renders its `topNav` three times and tells each copy its mode through context, which a Server Component cannot read, so the shells sit in small client parts: - TopNavFrame renders the landmark, the mobile bar at once (TopNavMobileBar, shared with TopNav.tsx; AppShell has already loaded the drawer toggle) and, in the drawer, a lazily loaded client TopNav; - TopNavLocalizedFrame translates the default label, only for a TopNav without one, so a labelled TopNav loads no message catalog; - TopNavSlotScope sets the slot context menus read; - TopNavItemGate hands an item to a lazily loaded client TopNavItem in the drawer or under a LinkProvider, and installs the touch press controller. A ref or a function prop renders the client component. Client imports and the public API are unchanged.
serverSafeComponents.test.ts now checks every `react-server` entry: the condition comes first and points at index.server.ts, the entry exports the same names as index.ts, and its server graph runs no client React API and reaches exactly the client parts __tests__/serverEntryClientParts.ts lists, with the reason for each. serverRender.test.ts renders the entries under React's `react-server` build, with every `'use client'` module swapped for a client reference as an RSC bundler does: presentational Buttons, IconButtons, TopNav bars and items render with no hook call and reference only their gates; interactive props reference the client component; props crossing into a client part are serializable; Text, Heading and Kbd render with no client reference unless truncation or the `mod` key needs one.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
AI review status for this pull request.
|
There was a problem hiding this comment.
This change waits on an engineering-owner decision: no current record governs React Server Component entry points or 'use client' placement (architecture:component-style-authoring leaves them to a future RSC/module-boundary record), so an engineering owner needs to provide or identify that spec, or record the decision by commenting /approve-spec <full head SHA> on this pull request, which the author may do if they are an engineering owner. Whatever that decision, these changes are still needed:
- Split the 4,759-line change by component family (Text/Heading/Kbd, Button/IconButton, TopNav), each part with its own tests.
- Inside a ButtonGroup, size provider or LinkProvider, the first client render shows the provider-free markup until the client Button loads (
ButtonContextGate.tsx:78), so a disabled group's link stays navigable; render that fallback with the provider's state and add a first-commit test. - Rebase onto
main, where Kbd now resolves its labels throughuseTranslator(), and either keep Kbd a client module or give its labels a client part, since a directive-free Kbd cannot read the translator.
[Automated review]
| // and hydration keeps it. On a client render (a soft navigation) it shows | ||
| // standalone styling until the chunk arrives, which beats a missing Button. | ||
| return ( | ||
| <Suspense fallback={children}> |
There was a problem hiding this comment.
Once isProvided is true, this fallback is the provider-free server element. On a client render before the chunk loads, a member of a disabled ButtonGroup commits as an enabled <a href> or submit <button>, and a member under SizeProvider value="sm" as data-size="md" (Button FR10, FR4). Rendering the fallback from getButtonRootProps/ButtonContent with the group's disabled state and the inherited size the gate has already read would close that window.
| * accessible name for the shortcut is built from these words instead. | ||
| */ | ||
| const KEY_LABEL = new Map<string, string>([ | ||
| ['ctrl', 'Control'], |
There was a problem hiding this comment.
On main these labels are catalog keys resolved by useTranslator() (#7849, architecture:internationalization INV1a). A directive-free Kbd cannot read the translator (INV13), so on rebase this split either drops that localization or Kbd has to stay a client module, or move its labels into a client part.
PR Analysis Report
Generated by PR Enrichment workflow | View current CI run |
Primary intent
Performance: let an app that renders its header from React Server Components ship no component JavaScript for the parts of it that only present. This PR makes
Text,Heading,Kbd,Button,IconButton,TopNavandTopNavItemrender on the server. None of the other templates fits: it is not a defect, a visual change, or a new public capability (no prop, type or export changes), and unlike pure maintenance it changes where these components render and when their code loads.The rule: presentational paths render on the server; interactive behavior lives in client parts, loaded only when the props (or the client providers) that need it are used. Server-render tests are the evidence.
User or maintainer impact
Today every one of these components carries
'use client', so a Server Component that renders<TopNav>, a few<TopNavItem>links and a<Button href>ships and hydrates the whole client implementation of each: the clientTopNavwithMobileNav, the drawer toggle and the menus (theTopNavbarrel), and the clientButtonwithTooltip,Spinner, the loading live region and the i18n catalog.After this change, in a Server Component:
Text,HeadingandKbdrender on the server with no client code. Truncation with a tooltip (an explicitmaxLines) and the platformmodglyph are small client parts, rendered only when used.Button,IconButton, theTopNavdesktop bar andTopNavItemrender their markup on the server. Each sits in a small client part that reads the client context a Server Component cannot, and the interactive component loads lazily only where it is needed.Client imports are unchanged:
index.tsstays the default entry, so client code renders exactly what it rendered before.Problem and solution fit
'use client'module, so the server can only emit a client reference to it, and the browser loads and hydrates the full component.Why not just drop
'use client'(asText,HeadingandKbddo)?Button,TopNavandTopNavItemread client context that changes their output, and current authority requires it:Button.spec.mdFR4/ORD1 andarchitecture:component-size-cascadeINV3 to INV5: size comes from the nearest provider (Toolbar,SideNav,ButtonGroup);ButtonGroupdisables its members and owns their corners and elevation;as, thenLinkProvider, then a native anchor;topNavthree times and tells each copy its mode (desktop, mobile bar, drawer) through context.A Server Component cannot read context, and a directive-free module is also imported by client code, where dropping the context reads would break all of the above. So these three use the
react-serverexport condition from #823: the condition resolves a server shell, and the default condition keeps the client component.Deltas:
react-serverentries for./Button,./IconButtonand./TopNav, which resolve server shells (ButtonShell.tsx,IconButtonShell.tsx,TopNavShell.tsx,TopNavItemShell.tsx).Text,HeadingandKbdas server modules (first commit).buttonStyles.stylex.ts,ButtonContent.tsx,topNavStyles.ts,topNavItemStyles.stylex.ts,TopNavMobileBar.tsx.utils/pressable.ts: the press marker, split out of the controller module that holds module state.scripts/sync-exports.jsgenerates the condition.pressableCoverage.test.tsrecognizes a server shell's marker.Text/Headingfix (commit 2) keeps the first commit from remounting the element whenmaxLinestoggles.Authority
No current record governs RSC rendering; #823 is the design this follows (the
react-serverconditional export, server-safe modules where nothing reads context). Every component keeps its current contract:Button.spec.mdFR1 to FR17 and AR1 to AR6,family:buttons,family:navigation-destinations,architecture:component-size-cascadeINV3 to INV5, and the public API (architecture:public-component-apiINV1, INV9, INV12). The client parts exist so that a server-rendered component meets those rows.Review receipt: global baselines from
node scripts/review-global-baselines.mjs, authorityb7ea471a8fc7704cc5ad256f2c4d749962a433f5, head1f33e4a371ab4160e70fc498be7f0cbbc2ac4a35, triggersbehavior,public-apiandreact-runtime.architecture:public-component-apiarchitecture:react-component-runtimearchitecture:internationalizationTopNavLocalizedFrameand follows the provider (INV1a, INV3, INV4).design:bidirectionalityarchitecture:container-paddingspec:AST-002spec:AST-055,spec:AST-056,spec:AST-057,spec:AST-058,spec:AST-059Direct owners resolved first:
component:Button(Button.spec.md),component:IconButton,family:buttons,family:navigation-destinationsandarchitecture:component-size-cascade(inherited by Button). No knowledge record is created or changed.Change and evidence
Client parts and why each exists
Every client part below is a
'use client'module the server graph references.serverSafeComponents.test.tsfails if a shell reaches any client module not in__tests__/serverEntryClientParts.ts, or reaches client code without one.Button and IconButton (IconButton is Button with
isIconOnly, the same composition asIconButton.tsx)Button.tsx(the client Button)clickActionuseTransitionplus an in-flight ref guard, for fire-once dedupe:Button.tsx:334,:339,:405isLoadingSpinner('use client',:503); the live region holds its text for one frame withuseState/useEffect(:346,:349); the localized loading string comes fromuseTranslator(:329)tooltipuseTooltipattaches triggers to the element (:400,:592)ref, an event handler, any other function prop, or a componentasuseMergedRefs:536,handleClick:405,handleKeyDown:437)useSize:330,useButtonGroup:331,useInputGroup:332,useLinkComponent:379ButtonContextGate.tsxButtonContextGate.tsx:53to:56) and installs the document touch press controller (:52;Button.tsx:328, FR15)IconSizeScope.tsxiconis setIconSizeScope.tsx:31); it adds no DOMThere is no ripple. Press feedback is the shared document-level controller; the server markup carries its
data-astryx-pressablemarker, and the gate installs it.TopNav and TopNavItem
TopNavFrame.tsx(TopNavFrame)topNavits mode through context (AppShell.tsx:720,:922;TopNav.tsx:111). Desktop: the landmark around the server-rendered bar. Mobile bar:TopNavMobileBarat once, readinguseTopNavMobileContentanduseAppShellMobile(TopNavFrame.tsx:71,:72), with the toggle AppShell has already loaded. Drawer: the client TopNav, lazily (:37)TopNavFrame.tsx(TopNavSlotScope)TopNav.tsx:197to:216;TopNavMenu.tsx:364,TopNavMegaMenu.tsx:415); it adds no DOMTopNavLocalizedFrame.tsxlabeluseTranslator,TopNav.tsx:109). A labelled TopNav never loads the message catalogTopNav.tsx(the client TopNav)refor a function propMobileNav:155,Divider:163, drawer content from context:112TopNavItemGate.tsxTopNavItemGate.tsx:51,:52;TopNavItem.tsx:141,:142), installs the touch press controller (:50;TopNavItem.tsx:140)TopNavItem.tsx(the client item)onClick, arefor a componentascloseMobileNav,TopNavItem.tsx:165); handlers (:211)TopNavHeading,TopNavMenu,TopNavMegaMenuand their items stay client modules, re-exported unchanged from the server entry.Text, Heading and Kbd (no
react-serverentry: they read no context, so the same module serves both)Text/TruncatedText.tsxmaxLineswith the tooltip on (Text.tsx:306,Heading.tsx:303)useTruncation,TruncatedText.tsx:62) and lazily shows the full-text tooltip (:33). AtmaxLines={0}it measures nothing, so toggling keeps the element mountedKbd/PlatformKbd.tsxmod(Kbd.tsx:43)useSyncExternalStore,PlatformKbd.tsx:34); server and hydration markup agreeBundle
esbuild over the built package (minified, React and StyleX external): the JavaScript that loads eagerly for what a Server Component references. The client reference today is the
'use client'entry; after this change it is the client part.Buttonwith data propsButtonContextGate)iconIconSizeScope)TopNavwithTopNavItemsTopNavbarrel)TopNavFrame+TopNavItemGate)TopNav, items, aButtonlinkTopNavwithoutlabelTopNavLocalizedFramebrings the message catalog, which any other localized client component on the page already loadsClient imports cost a little more, because the shared modules are now separate files: the
Buttonentry goes from 37.4 KB to 37.7 KB and theTopNaventry from 57.0 KB to 57.6 KB.The lazy client components load only on the paths in the tables above.
Tests
serverRender.test.ts(new): renders under thereact-servercondition.react-serverbuild and swaps every'use client'module for a client reference, as an RSC bundler does.react-dom/serverrefuses to load under that condition, so a small resolver renders the tree instead. Under the server build any hook call throws, and the test asserts thatuseState,useContextandcreateContextare absent.Text,HeadingandKbdreference no client code unless truncation ormodneeds it.serverSafeComponents.test.ts(extended). For eachreact-serverentry:index.server.ts;index.ts;ButtonShell.test.tsxandTopNavShell.test.tsx(new): markup parity with the client components.childrenvslabel, widths, elevation, disabled, form attributes, links, rejected destinations, caller DOM props) and for IconButton.nullsize provider, an InputGroup and a LinkProvider.Text/TruncatedText.test.tsx(new): Text and Heading keep their element mounted whenmaxLinestoggles.pressableCoverage.test.ts: a server shell counts as marked when it spreadspressablePropsand renders a gate that callsusePressFeedback().Public exports
dist/index.d.ts,dist/Button/index.d.ts,dist/IconButton/index.d.tsanddist/TopNav/index.d.tsare byte-identical before and after.ButtonSizeandButtonVariantmoved tobuttonStyles.stylex.tsand are re-exported fromButton.tsx. A type-equality probe against the previous build passes forButtonSize,keyof ButtonProps, and aButtonVariantMapmodule augmentation.index.server.tsexports the same names as itsindex.ts(tested). The shells' helpers are not reachable from any package export.Known limitations
maxLinestoggles throughundefined. TogglingmaxLinesbetween a number andundefinedonTextorHeading(rather than0) still swaps the client part for the plain element, and so remounts it. So does togglinghasTruncateTooltip. An explicitmaxLines={0}in a Server Component loads the truncation part, which measures nothing at 0.withAstryx()source builds.withAstryx()aliases every@astryxdesign/core/*request to itssourceentry for every webpack layer, so its source builds still resolve the client components in Server Components (today's behavior). Apps on the published package resolve thereact-serverentry through standard conditions. See follow-ups.Follow-ups (not in this PR)
Avatarand theLinkvariants, then the remaining Tier 2 components from feat: RSC-native components viareact-serverconditional exports #823.TopNavHeading,TopNavMenuandTopNavMegaMenuserver shells, where their content is static.withAstryx()(issuerLayerrules for the React Server layers), so source builds resolve thereact-serverentries, with a build test.react-serverentry for the package root (@astryxdesign/core), whose barrel is'use client'.Scope
Testing
Commits (each passes its targeted suites,
tscandsync-exports --checkon its own):perf(core): render Text, Heading and Kbd on the server; truncation and the platform glyph become client partsfix(core): keep Text and Heading mounted when truncation togglesperf(core): render Button and IconButton in React Server Componentsperf(core): render the TopNav desktop bar in React Server Componentstest(core): prove the react-server entries render on the serverResults at the head commit:
pnpm test:ui: 599 of 600 files and 14,828 tests pass. The one failure,DropdownMenuLazySheet.test.tsx, is a hook timeout under full parallel load; it passes alone.serverRender,serverSafeComponentsandpressableCoverage, plus the newButtonShell,TopNavShellandTruncatedTexttests.pnpm test:node:--maxWorkers=4, 65 of 71 of those files pass.npm packor a fixturepnpm install. They fail identically onmainatb7ea471a8on this machine (setup-workspace,theme-checks,pack-check.lifecycle-output,integration-real-world,release/cache,global-local).packages/cli/api/render/render.test.mjs(render --reversemaps thebuttontarget to Button) passes.pnpm lint:strict: 0 errors. The warnings are pre-existing, and none is in a changed file.pnpm -F @astryxdesign/core typecheck: passes (tscand the docs typecheck).pnpm -F @astryxdesign/core build: passes.dist/*/index.d.tsis unchanged, anddist/*/index.server.jsis emitted for the three entries.node scripts/sync-exports.js --checkandpnpm check:repo: pass..changeset/server-render-header-shell.md([perf], patch).