An open source design system that's fully customizable and agent ready
TypeScript
fix(core): two copies of Core's modules share one React context (#10233)
Cindy Zhang422440a641f3
diff --git a/.changeset/core-shared-contexts.md b/.changeset/core-shared-contexts.mdnew file mode 100644index 0000000000..716cdb0228--- /dev/null+++ b/.changeset/core-shared-contexts.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Core registers every React context, and the English its components register, under a versioned key, so two copies of Core's modules on one page share them: a provider from one copy reaches consumers from the other, a layer boundary from either resets the layer-scoped contexts of both, and a component from either shows its English. A copy built against another version of a context keeps its own. No API changes.++@cixzhangdiff --git a/docs/specs/AST-110-swizzle-output/spec.md b/docs/specs/AST-110-swizzle-output/spec.mdindex 2d896cfab8..2e0be84134 100644--- a/docs/specs/AST-110-swizzle-output/spec.md+++ b/docs/specs/AST-110-swizzle-output/spec.md@@ -91,7 +91,9 @@ and the repository proves it before a change that could break it merges.reads a store of a different shape. A context that connects a provider to itsconsumers is coordinating state too: its context object lives under the samekind of versioned key, so a copied `useToast` reaches the package's- `LayerProvider`. A symbol that identifies objects across modules, such as a+ `LayerProvider`. Copies of Core on one React share each context; a context+ is never shared across two Reacts in one process, so one request never reads+ another's provided value. A symbol that identifies objects across modules, such as abrand or a context key, is registered under the same kind of key, so a copyand the package agree on it. The rule holds in both directions: a copy insidea package overlay, and package components inside a copied Dialog or other@@ -189,14 +191,12 @@ and the repository proves it before a change that could break it merges.- Copies include spec records and test files and leave out nested folders(FR2), and `swizzle --list` offers folders that are not components(`spec:AST-035` FR12).-- The layer stack, the modal outlet, the layer contexts, and `useAnnounce`- keep module state, so a copied Dialog, BottomSheet, or `useToast` starts its- own stack, misses the package's provider, or mounts a second pair of live- regions, breaking `spec:AST-086` FR9's one channel per document (FR3).-- In the reverse direction, package components inside a copied Dialog or- overlay do not see its layer boundary or modal: a package picker announces- outside the copied modal (`spec:AST-086` FR14), and package group context- crosses into it (`spec:AST-038` FR7) (FR3).+- The layer stack, the modal outlet, and `useAnnounce` keep module state, so+ a copied Dialog or BottomSheet starts its own stack, or mounts a second pair+ of live regions, breaking `spec:AST-086` FR9's one channel per document+ (FR3).+- In the reverse direction, a package picker inside a copied Dialog announces+ outside the copied modal (`spec:AST-086` FR14) (FR3).- The result does not yet report whether each shared module was written,reused or replaced (FR2's impact bullet); adding that receipt field is the CLIowner's call.@@ -216,17 +216,18 @@ and the repository proves it before a change that could break it merges.## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | Eject every offered component into a clean project; type-check and bundle | Every component in `swizzle --list`; Core, Lab, Charts, RichText, Vega; a component that imports an npm dependency | A type or resolve error, or an import of a path the owner's `exports` lacks or of `./internal/*`, fails, or a dependency the copy imports goes unreported |-| FR2 | Import graph of each output | Helpers in `utils`, `hooks`, `Layer`; nested folders; colocated tests and docs; a helper an earlier swizzle wrote, identical and different | A copied file imports a module that is neither in the output nor a public export, or a test, story, spec, or doc is copied, or an existing helper other than an owner module (FR4) is overwritten |-| FR3 | Render a copied and a package layer component together; inspect stores; open, stack, and Escape | Dialog over package Popover; BottomSheet over package Dialog; modality; a copied `useToast` under the package `LayerProvider`; a symbol-branded object passed between copy and package; a copied Dialog announcing beside a package component; a package picker inside a copied Dialog announcing a result count; a package grouped control inside a copied overlay | In either direction (copy under package, package under copy): two stores of one protocol version exist in a document, Escape and focus return differ from the package alone, a copied consumer misses the package provider, a brand check fails, a second live region appears instead of one announcer (`spec:AST-086` FR9), an announcement escapes the open modal (`spec:AST-086` FR14), or group context crosses the layer boundary (`spec:AST-038` FR7) |-| FR4 | Scan each output for private data-attribute names and selectors; compare copied owner modules with the package's | Components that reach an owner module | A hand-written private attribute name or selector, or an edited owner module, in the output |-| FR5 | Render package and copy side by side under a theme with component overrides; compare | Default; each variant; a theme component override; a copy built by `@astryxdesign/build` | A theme override, documented class name, data attribute, or theme target reaches one and not the other |-| FR6 | The component's own interaction and accessibility checks run against the copy | Keyboard, pointer, screen-reader tree | A check that passes on the package fails on the copy |-| FR7 | The required test lane's swizzle proof and the release-time proof; both cover Core's list and every integration package's components through `--package` | A change to component source; a change to the swizzle copy; an unrelated change; Core, Lab, Charts, RichText, Vega | An offered component missing from the proof, a failure that does not block, a new required context, the proof adding wall-clock time to the slowest required check, or the proof pushing its job past the pull-request time budget |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1 | Eject every offered component into a clean project; type-check and bundle | Every component in `swizzle --list`; Core, Lab, Charts, RichText, Vega; a component that imports an npm dependency | A type or resolve error, or an import of a path the owner's `exports` lacks or of `./internal/*`, fails, or a dependency the copy imports goes unreported |+| FR2 | Import graph of each output | Helpers in `utils`, `hooks`, `Layer`; nested folders; colocated tests and docs; a helper an earlier swizzle wrote, identical and different | A copied file imports a module that is neither in the output nor a public export, or a test, story, spec, or doc is copied, or an existing helper other than an owner module (FR4) is overwritten |+| FR3 | Render a copied and a package layer component together; inspect stores; open, stack, and Escape | Dialog over package Popover; BottomSheet over package Dialog; modality; a copied `useToast` under the package `LayerProvider`; a symbol-branded object passed between copy and package; a copied Dialog announcing beside a package component; a package picker inside a copied Dialog announcing a result count; a package grouped control inside a copied overlay | In either direction (copy under package, package under copy): two stores of one protocol version exist in a document, Escape and focus return differ from the package alone, a copied consumer misses the package provider, a brand check fails, a second live region appears instead of one announcer (`spec:AST-086` FR9), an announcement escapes the open modal (`spec:AST-086` FR14), or group context crosses the layer boundary (`spec:AST-038` FR7) |+| FR3 | `sharedContexts.test.tsx` "gives each React its own context under a key, and one per React": a second React instance loads a copy of the shared-context module | Two copies on one React; a copy on a second React in the same process | Two copies on one React getting different contexts, or a copy on a second React getting the same context object, fails |+| FR4 | Scan each output for private data-attribute names and selectors; compare copied owner modules with the package's | Components that reach an owner module | A hand-written private attribute name or selector, or an edited owner module, in the output |+| FR5 | Render package and copy side by side under a theme with component overrides; compare | Default; each variant; a theme component override; a copy built by `@astryxdesign/build` | A theme override, documented class name, data attribute, or theme target reaches one and not the other |+| FR6 | The component's own interaction and accessibility checks run against the copy | Keyboard, pointer, screen-reader tree | A check that passes on the package fails on the copy |+| FR7 | The required test lane's swizzle proof and the release-time proof; both cover Core's list and every integration package's components through `--package` | A change to component source; a change to the swizzle copy; an unrelated change; Core, Lab, Charts, RichText, Vega | An offered component missing from the proof, a failure that does not block, a new required context, the proof adding wall-clock time to the slowest required check, or the proof pushing its job past the pull-request time budget |-Known verification gap: none of these checks exist on `main`.+Known verification gap: only FR3's shared-context checks (`sharedContexts.test.tsx`) exist; the other rows have no check on `main`.## Decision logdiff --git a/packages/core/src/AppShell/AppShellMobileContext.tsx b/packages/core/src/AppShell/AppShellMobileContext.tsxindex 077ebd798b..85797885c6 100644--- a/packages/core/src/AppShell/AppShellMobileContext.tsx+++ b/packages/core/src/AppShell/AppShellMobileContext.tsx@@ -4,7 +4,7 @@/*** @file AppShellMobileContext.tsx- * @input Uses React createContext, use+ * @input Uses createSharedContext, use* @output Exports AppShellMobileContext, useAppShellMobile* @position Internal context for mobile nav state; consumed by MobileNavToggle, TopNav (future)*@@ -13,7 +13,8 @@* to adapt rendering based on mobile context.*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export interface AppShellMobileContextValue {/** Whether the viewport is below the mobile breakpoint */@@ -51,7 +52,11 @@ const defaultValue: AppShellMobileContextValue = {};export const AppShellMobileContext =- createContext<AppShellMobileContextValue>(defaultValue);+ createSharedContext<AppShellMobileContextValue>(+ 'AppShellMobileContext',+ 1,+ defaultValue,+ );AppShellMobileContext.displayName = 'AppShellMobileContext';/**diff --git a/packages/core/src/AppShell/useAppShellMainId.ts b/packages/core/src/AppShell/useAppShellMainId.tsindex 2f48727fe3..49e7357192 100644--- a/packages/core/src/AppShell/useAppShellMainId.ts+++ b/packages/core/src/AppShell/useAppShellMainId.ts@@ -11,8 +11,9 @@* @position Private to AppShell; keeps main-region ids unique on a page*/-import {createContext, use, useId, useState, useSyncExternalStore} from 'react';+import {use, useId, useState, useSyncExternalStore} from 'react';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {createSharedContext} from '../utils/sharedContext';/** The id of the first mounted shell's main region. Consumers link to it. */export const MAIN_CONTENT_ID = 'astryx-app-shell-main';@@ -21,7 +22,11 @@ export const MAIN_CONTENT_ID = 'astryx-app-shell-main';* True inside an AppShell. A shell nested in another shell's content never* takes the fixed id: the page's own shell keeps it.*/-export const AppShellNestingContext = createContext(false);+export const AppShellNestingContext = createSharedContext(+ 'AppShellNestingContext',+ 1,+ false,+);AppShellNestingContext.displayName = 'AppShellNestingContext';const claims: object[] = [];diff --git a/packages/core/src/Avatar/AvatarSizeContext.ts b/packages/core/src/Avatar/AvatarSizeContext.tsindex 5b3fa3fc7a..7cf3260840 100644--- a/packages/core/src/Avatar/AvatarSizeContext.ts+++ b/packages/core/src/Avatar/AvatarSizeContext.ts@@ -12,7 +12,7 @@* - /packages/core/src/Avatar/Avatar.doc.mjs*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';/*** Context that provides the resolved numeric avatar size (in pixels)@@ -20,5 +20,9 @@ import {createLayerScopedContext as createContext} from '../Layer/layerScopedCon** Default value of 36 matches the default 'md' avatar size.*/-export const AvatarSizeContext = createContext<number>(36);+export const AvatarSizeContext = createLayerScopedContext<number>(+ 'AvatarSizeContext',+ 1,+ 36,+);AvatarSizeContext.displayName = 'AvatarSizeContext';diff --git a/packages/core/src/Avatar/AvatarStatusLabelContext.ts b/packages/core/src/Avatar/AvatarStatusLabelContext.tsindex 5e5ba5fc54..db29f031f2 100644--- a/packages/core/src/Avatar/AvatarStatusLabelContext.ts+++ b/packages/core/src/Avatar/AvatarStatusLabelContext.ts@@ -4,7 +4,7 @@/*** @file AvatarStatusLabelContext.ts- * @input Uses React createContext, RefObject+ * @input Uses createSharedContext, RefObject* @output Exports AvatarStatusLabelContext, AvatarStatusLabelTarget* @position Internal context; provided by Avatar, consumed by AvatarStatusDot*@@ -12,7 +12,8 @@* - /packages/core/src/Avatar/Avatar.doc.mjs*/-import {createContext, type RefObject} from 'react';+import type {RefObject} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** The box a status element writes its label into.@@ -43,5 +44,9 @@ export interface AvatarStatusLabelTarget {* Avatar, where a standalone dot names itself and has nobody to report to.*/export const AvatarStatusLabelContext =- createContext<RefObject<AvatarStatusLabelTarget> | null>(null);+ createSharedContext<RefObject<AvatarStatusLabelTarget> | null>(+ 'AvatarStatusLabelContext',+ 1,+ null,+ );AvatarStatusLabelContext.displayName = 'AvatarStatusLabelContext';diff --git a/packages/core/src/AvatarGroup/AvatarGroupContext.ts b/packages/core/src/AvatarGroup/AvatarGroupContext.tsindex f6dae5f00d..201057768c 100644--- a/packages/core/src/AvatarGroup/AvatarGroupContext.ts+++ b/packages/core/src/AvatarGroup/AvatarGroupContext.ts@@ -9,7 +9,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import type {AvatarShape, AvatarSize} from '../Avatar';export interface AvatarGroupContextValue {@@ -19,9 +19,12 @@ export interface AvatarGroupContextValue {numericSize: number;}-export const AvatarGroupContext = createContext<AvatarGroupContextValue | null>(- null,-);+export const AvatarGroupContext =+ createLayerScopedContext<AvatarGroupContextValue | null>(+ 'AvatarGroupContext',+ 1,+ null,+ );AvatarGroupContext.displayName = 'AvatarGroupContext';export function useAvatarGroup(): AvatarGroupContextValue | null {diff --git a/packages/core/src/BottomSheet/BottomSheetHostContext.ts b/packages/core/src/BottomSheet/BottomSheetHostContext.tsindex 2140407a58..4f9c8a7981 100644--- a/packages/core/src/BottomSheet/BottomSheetHostContext.ts+++ b/packages/core/src/BottomSheet/BottomSheetHostContext.ts@@ -15,21 +15,25 @@* - /packages/core/src/BottomSheet/BottomSheetStacking.test.tsx*/+import {createSharedContext} from '../utils/sharedContext';+// A sheet rendered in another sheet's content is presented only while its// host is open. Without this, a host that closes from code would leave the// inner dialog open in the top layer with no box: an invisible modal that// blocks the page. The host never writes the inner sheet's state. At the// root the context is null, which reads as open.-import {createContext} from 'react';-export interface BottomSheetHostContextValue {/** Whether the host sheet is open; a closing host reads false at once. */isOpen: boolean;}export const BottomSheetHostContext =- createContext<BottomSheetHostContextValue | null>(null);+ createSharedContext<BottomSheetHostContextValue | null>(+ 'BottomSheetHostContext',+ 1,+ null,+ );BottomSheetHostContext.displayName = 'BottomSheetHostContext';export const OPEN_BOTTOM_SHEET_HOST: BottomSheetHostContextValue = {diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.tsindex 51b0b4ef6c..b8dfb174ea 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts+++ b/packages/core/src/BottomSheet/BottomSheetSwitcherContext.ts@@ -19,10 +19,11 @@ import type {MouseEvent as ReactMouseEvent,SyntheticEvent,} from 'react';-import {createContext} from 'react';+import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';import type {BottomSheetStackView} from './bottomSheetStack';+import {createSharedContext} from '../utils/sharedContext';export type BottomSheetSwitcherPhase =| 'entering'@@ -115,6 +116,10 @@ export interface BottomSheetSwitcherContextValue {}export const BottomSheetSwitcherContext =- createContext<BottomSheetSwitcherContextValue | null>(null);+ createSharedContext<BottomSheetSwitcherContextValue | null>(+ 'BottomSheetSwitcherContext',+ 1,+ null,+ );BottomSheetSwitcherContext.displayName = 'BottomSheetSwitcherContext';diff --git a/packages/core/src/BottomSheet/bottomSheetEscape.ts b/packages/core/src/BottomSheet/bottomSheetEscape.tsindex 1b0f1f0728..81179fc555 100644--- a/packages/core/src/BottomSheet/bottomSheetEscape.ts+++ b/packages/core/src/BottomSheet/bottomSheetEscape.ts@@ -14,8 +14,12 @@* is unchanged.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';/** Whether Escape may dismiss the sheet; `purpose="required"` still blocks it. */-export const BottomSheetEscapeContext = createContext(true);+export const BottomSheetEscapeContext = createSharedContext(+ 'BottomSheetEscapeContext',+ 1,+ true,+);BottomSheetEscapeContext.displayName = 'BottomSheetEscapeContext';diff --git a/packages/core/src/BottomSheet/bottomSheetStack.ts b/packages/core/src/BottomSheet/bottomSheetStack.tsindex 51759ef3af..d03a8fcb34 100644--- a/packages/core/src/BottomSheet/bottomSheetStack.ts+++ b/packages/core/src/BottomSheet/bottomSheetStack.ts@@ -52,6 +52,7 @@import {notifyTopLayerEntry} from '../Layer/modalOutlet';import {focusForLastInput, returnFocusForLastInput} from '../utils/focusReturn';+import {realmValue} from '../utils/sharedRealm';export interface BottomSheetStackView {/** Another modal sheet is presented alongside this one. */@@ -340,20 +341,11 @@ function createStackState(): StackState {};}-function acquireStackState(): StackState {- const holder = globalThis as {[STACK_STATE_KEY]?: StackState};- const shared = holder[STACK_STATE_KEY];- if (shared != null) {- // The key names the version, so a state found under it is this- // protocol's; the shape check is the guard against a key collision.- return shared.shape === STACK_STATE_SHAPE ? shared : createStackState();- }- const created = createStackState();- holder[STACK_STATE_KEY] = created;- return created;-}--const state = acquireStackState();+const state = realmValue(+ STACK_STATE_KEY,+ createStackState,+ shared => (shared as StackState | null)?.shape === STACK_STATE_SHAPE,+);function takeRank(): Rank {state.isBatchDirty = true;diff --git a/packages/core/src/Breadcrumbs/Breadcrumbs.tsx b/packages/core/src/Breadcrumbs/Breadcrumbs.tsxindex 4bc09272b3..cfb69085a4 100644--- a/packages/core/src/Breadcrumbs/Breadcrumbs.tsx+++ b/packages/core/src/Breadcrumbs/Breadcrumbs.tsx@@ -17,7 +17,7 @@*/import {useMemo, type ReactNode} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import * as stylex from '@stylexjs/stylex';import {spacingVars} from '../theme/tokens.stylex';import {mergeProps} from '../utils';@@ -55,10 +55,11 @@ export interface BreadcrumbContextValue {separator: ReactNode;}-export const BreadcrumbContext = createContext<BreadcrumbContextValue>({- variant: 'default',- separator: '/',-});+export const BreadcrumbContext =+ createLayerScopedContext<BreadcrumbContextValue>('BreadcrumbContext', 1, {+ variant: 'default',+ separator: '/',+ });BreadcrumbContext.displayName = 'BreadcrumbContext';// =============================================================================diff --git a/packages/core/src/Button/buttonHitArea.ts b/packages/core/src/Button/buttonHitArea.tsindex dfd0f06daa..b4524d4594 100644--- a/packages/core/src/Button/buttonHitArea.ts+++ b/packages/core/src/Button/buttonHitArea.ts@@ -4,14 +4,14 @@/*** @file buttonHitArea.ts- * @input Uses React createContext and the touch hit-area options type+ * @input Uses createSharedContext and the touch hit-area options type* @output Exports ButtonHitAreaContext, the touch hit-area options a Button* passes to useTouchHitArea, and BUTTON_HIT_AREA, their default* @position Internal to Core. A Core part that renders a Button and needs a* different band, such as InputClearButton, provides its own options.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';import type {TouchHitAreaOptions} from '../utils/touchHitArea';// The band is on the content wrapper, so a band tap lands on a descendant.@@ -21,6 +21,9 @@ export const BUTTON_HIT_AREA: TouchHitAreaOptions = {ownsDescendantTouches: false,};-export const ButtonHitAreaContext =- createContext<TouchHitAreaOptions>(BUTTON_HIT_AREA);+export const ButtonHitAreaContext = createSharedContext<TouchHitAreaOptions>(+ 'ButtonHitAreaContext',+ 1,+ BUTTON_HIT_AREA,+);ButtonHitAreaContext.displayName = 'ButtonHitAreaContext';diff --git a/packages/core/src/ButtonGroup/ButtonGroupContext.ts b/packages/core/src/ButtonGroup/ButtonGroupContext.tsindex be12798d6a..ca9bfd9a10 100644--- a/packages/core/src/ButtonGroup/ButtonGroupContext.ts+++ b/packages/core/src/ButtonGroup/ButtonGroupContext.ts@@ -10,7 +10,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export type ButtonGroupOrientation = 'horizontal' | 'vertical';@@ -19,9 +19,12 @@ export interface ButtonGroupContextValue {isDisabled: boolean;}-export const ButtonGroupContext = createContext<ButtonGroupContextValue | null>(- null,-);+export const ButtonGroupContext =+ createLayerScopedContext<ButtonGroupContextValue | null>(+ 'ButtonGroupContext',+ 1,+ null,+ );ButtonGroupContext.displayName = 'ButtonGroupContext';/**diff --git a/packages/core/src/Chat/ChatContext.tsx b/packages/core/src/Chat/ChatContext.tsxindex 4ac52cedad..c457cc476f 100644--- a/packages/core/src/Chat/ChatContext.tsx+++ b/packages/core/src/Chat/ChatContext.tsx@@ -12,8 +12,9 @@* ChatComposerInput, ChatSendButton, and custom inputs.*/-import {createContext, use, type RefObject} from 'react';+import {use, type RefObject} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';+import {createSharedContext} from '../utils/sharedContext';export type ChatMessageSender = 'user' | 'assistant' | 'system';export type ChatDensity = 'compact' | 'balanced' | 'spacious';@@ -24,7 +25,11 @@ export interface ChatMessageContextValue {}export const ChatMessageContext =- createLayerScopedContext<ChatMessageContextValue | null>(null);+ createLayerScopedContext<ChatMessageContextValue | null>(+ 'ChatMessageContext',+ 1,+ null,+ );ChatMessageContext.displayName = 'ChatMessageContext';export function useChatMessageContext(): ChatMessageContextValue | null {@@ -36,7 +41,11 @@ export interface ChatListContextValue {}export const ChatListContext =- createLayerScopedContext<ChatListContextValue | null>(null);+ createLayerScopedContext<ChatListContextValue | null>(+ 'ChatListContext',+ 1,+ null,+ );ChatListContext.displayName = 'ChatListContext';export function useChatListContext(): ChatListContextValue | null {@@ -83,7 +92,11 @@ export interface ChatComposerContextValue {}export const ChatComposerContext =- createContext<ChatComposerContextValue | null>(null);+ createSharedContext<ChatComposerContextValue | null>(+ 'ChatComposerContext',+ 1,+ null,+ );ChatComposerContext.displayName = 'ChatComposerContext';export function useChatComposerContext(): ChatComposerContextValue | null {@@ -101,9 +114,12 @@ export interface ChatLayoutContextValue {contentRef: (el: HTMLElement | null) => void;}-export const ChatLayoutContext = createContext<ChatLayoutContextValue | null>(- null,-);+export const ChatLayoutContext =+ createSharedContext<ChatLayoutContextValue | null>(+ 'ChatLayoutContext',+ 1,+ null,+ );ChatLayoutContext.displayName = 'ChatLayoutContext';export function useChatLayoutContext(): ChatLayoutContextValue | null {diff --git a/packages/core/src/CheckboxInput/CheckboxRowPressContext.ts b/packages/core/src/CheckboxInput/CheckboxRowPressContext.tsindex 3b7753a909..a655bec925 100644--- a/packages/core/src/CheckboxInput/CheckboxRowPressContext.ts+++ b/packages/core/src/CheckboxInput/CheckboxRowPressContext.ts@@ -18,5 +18,9 @@import {createLayerScopedContext} from '../Layer/layerScopedContext';-export const CheckboxRowPressContext = createLayerScopedContext(false);+export const CheckboxRowPressContext = createLayerScopedContext(+ 'CheckboxRowPressContext',+ 1,+ false,+);CheckboxRowPressContext.displayName = 'CheckboxRowPressContext';diff --git a/packages/core/src/CheckboxList/CheckboxListContext.tsx b/packages/core/src/CheckboxList/CheckboxListContext.tsxindex d572d5f81d..f3841ddc1a 100644--- a/packages/core/src/CheckboxList/CheckboxListContext.tsx+++ b/packages/core/src/CheckboxList/CheckboxListContext.tsx@@ -60,5 +60,9 @@ export interface CheckboxListContextValue {}export const CheckboxListContext =- createLayerScopedContext<CheckboxListContextValue | null>(null);+ createLayerScopedContext<CheckboxListContextValue | null>(+ 'CheckboxListContext',+ 1,+ null,+ );CheckboxListContext.displayName = 'CheckboxListContext';diff --git a/packages/core/src/Collapsible/CollapsibleGroupContext.tsx b/packages/core/src/Collapsible/CollapsibleGroupContext.tsxindex d3dacd6e86..7c9c8c6aae 100644--- a/packages/core/src/Collapsible/CollapsibleGroupContext.tsx+++ b/packages/core/src/Collapsible/CollapsibleGroupContext.tsx@@ -16,8 +16,8 @@* - /packages/cli/assets/templates/blocks/components/Collapsible/ (showcase blocks)*/-import {createContext} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';+import {createSharedContext} from '../utils/sharedContext';/*** Context value provided by CollapsibleGroup to coordinate collapsible children.@@ -34,7 +34,11 @@ export interface CollapsibleGroupContextValue {* When present, collapsible components defer their open/close state to the group.*/export const CollapsibleGroupContext =- createContext<CollapsibleGroupContextValue | null>(null);+ createSharedContext<CollapsibleGroupContextValue | null>(+ 'CollapsibleGroupContext',+ 1,+ null,+ );CollapsibleGroupContext.displayName = 'CollapsibleGroupContext';/**@@ -79,6 +83,10 @@ export interface CollapsibleGroupPresentationValue {* children so nested collapsibles never inherit row chrome.*/export const CollapsibleGroupPresentationContext =- createLayerScopedContext<CollapsibleGroupPresentationValue | null>(null);+ createLayerScopedContext<CollapsibleGroupPresentationValue | null>(+ 'CollapsibleGroupPresentationContext',+ 1,+ null,+ );CollapsibleGroupPresentationContext.displayName ='CollapsibleGroupPresentationContext';diff --git a/packages/core/src/CommandPalette/CommandPaletteContext.ts b/packages/core/src/CommandPalette/CommandPaletteContext.tsindex cf2bb8d65d..7c2c498a2c 100644--- a/packages/core/src/CommandPalette/CommandPaletteContext.ts+++ b/packages/core/src/CommandPalette/CommandPaletteContext.ts@@ -3,13 +3,14 @@'use client';/*** @file CommandPaletteContext.ts- * @input Uses React createContext+ * @input Uses createSharedContext* @output Exports CommandPaletteContext and useCommandPaletteContext hook* @position Internal context; consumed by composable sub-components*/-import {createContext, use} from 'react';+import {use} from 'react';import type {SearchableItem} from '../Typeahead';+import {createSharedContext} from '../utils/sharedContext';export interface CommandPaletteContextValue {/** Current search query. */@@ -45,7 +46,11 @@ export interface CommandPaletteContextValue {}export const CommandPaletteContext =- createContext<CommandPaletteContextValue | null>(null);+ createSharedContext<CommandPaletteContextValue | null>(+ 'CommandPaletteContext',+ 1,+ null,+ );CommandPaletteContext.displayName = 'CommandPaletteContext';/**diff --git a/packages/core/src/CommandPalette/busyStartSettle.ts b/packages/core/src/CommandPalette/busyStartSettle.tsindex b88464b518..ac7ec9dcf5 100644--- a/packages/core/src/CommandPalette/busyStartSettle.ts+++ b/packages/core/src/CommandPalette/busyStartSettle.ts@@ -16,11 +16,15 @@* module boundary.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';/** Registers the input's settle function, or `null` when the input goes away. */export type RegisterBusyStartSettle = (settle: (() => void) | null) => void;export const BusyStartSettleContext =- createContext<RegisterBusyStartSettle | null>(null);+ createSharedContext<RegisterBusyStartSettle | null>(+ 'BusyStartSettleContext',+ 1,+ null,+ );BusyStartSettleContext.displayName = 'BusyStartSettleContext';diff --git a/packages/core/src/Dialog/DialogContext.ts b/packages/core/src/Dialog/DialogContext.tsindex 600160df8d..57d9d02dc2 100644--- a/packages/core/src/Dialog/DialogContext.ts+++ b/packages/core/src/Dialog/DialogContext.ts@@ -10,7 +10,8 @@* and by Lab's DialogHeroHeader through the internal/dialog-context entry*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export interface DialogContextValue {/** Whether the dialog is rendered inline for docs/showcases. */@@ -30,7 +31,11 @@ export interface DialogContextValue {syncDefaultName?: () => void;}-export const DialogContext = createContext<DialogContextValue | null>(null);+export const DialogContext = createSharedContext<DialogContextValue | null>(+ 'DialogContext',+ 1,+ null,+);DialogContext.displayName = 'DialogContext';export function useDialogContext(): DialogContextValue | null {diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsxindex ca3bd3bba3..b27bd4e4e0 100644--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx@@ -14,8 +14,9 @@* items don't need to register themselves.*/-import {createContext, use} from 'react';+import {use} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';+import {createSharedContext} from '../utils/sharedContext';/** Menu size, derived from the trigger button size. */export type DropdownMenuSize = 'sm' | 'md' | 'lg';@@ -100,7 +101,11 @@ export interface DropdownMenuSurfaceValue {* off the public menu context, and layer-scoped, so each flyout re-provides it.*/export const DropdownMenuSurfaceContext =- createLayerScopedContext<DropdownMenuSurfaceValue | null>(null);+ createLayerScopedContext<DropdownMenuSurfaceValue | null>(+ 'DropdownMenuSurfaceContext',+ 1,+ null,+ );DropdownMenuSurfaceContext.displayName = 'DropdownMenuSurfaceContext';/**@@ -115,7 +120,7 @@ DropdownMenuSurfaceContext.displayName = 'DropdownMenuSurfaceContext';*/export const DropdownMenuRootOpenContext = createLayerScopedContext<boolean | null->(null);+>('DropdownMenuRootOpenContext', 1, null);DropdownMenuRootOpenContext.displayName = 'DropdownMenuRootOpenContext';/**@@ -128,7 +133,11 @@ export function useDropdownMenuRootOpen(): boolean {}export const DropdownMenuContext =- createLayerScopedContext<DropdownMenuContextValue | null>(null);+ createLayerScopedContext<DropdownMenuContextValue | null>(+ 'DropdownMenuContext',+ 1,+ null,+ );DropdownMenuContext.displayName = 'DropdownMenuContext';/**@@ -153,7 +162,11 @@ export interface DropdownMenuRadioGroupContextValue {}export const DropdownMenuRadioGroupContext =- createContext<DropdownMenuRadioGroupContextValue | null>(null);+ createSharedContext<DropdownMenuRadioGroupContextValue | null>(+ 'DropdownMenuRadioGroupContext',+ 1,+ null,+ );DropdownMenuRadioGroupContext.displayName = 'DropdownMenuRadioGroupContext';/**diff --git a/packages/core/src/FormLayout/FormLayoutContext.ts b/packages/core/src/FormLayout/FormLayoutContext.tsindex f72331ebec..39e1ce91c8 100644--- a/packages/core/src/FormLayout/FormLayoutContext.ts+++ b/packages/core/src/FormLayout/FormLayoutContext.ts@@ -14,7 +14,7 @@* - /packages/core/src/FormLayout/index.ts (exports if types change)*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';/*** Direction of form field arrangement.@@ -44,8 +44,8 @@ export type FormOptionality = 'optional' | 'required';* for spatial arrangement, and `defaultOptionality` so a field can suppress the* indicator that merely restates the form-wide default.*/-export const FormLayoutContext = createContext<{+export const FormLayoutContext = createLayerScopedContext<{direction: FormLayoutDirection;defaultOptionality?: FormOptionality;-}>({direction: 'vertical'});+}>('FormLayoutContext', 1, {direction: 'vertical'});FormLayoutContext.displayName = 'FormLayoutContext';diff --git a/packages/core/src/Icon/IconDefaultSizeContext.ts b/packages/core/src/Icon/IconDefaultSizeContext.tsindex 0278b03068..43119a3a17 100644--- a/packages/core/src/Icon/IconDefaultSizeContext.ts+++ b/packages/core/src/Icon/IconDefaultSizeContext.ts@@ -10,10 +10,14 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import type {IconSize} from './IconSize.stylex';-const IconDefaultSizeContext = createContext<IconSize | null>(null);+const IconDefaultSizeContext = createLayerScopedContext<IconSize | null>(+ 'IconDefaultSizeContext',+ 1,+ null,+);IconDefaultSizeContext.displayName = 'IconDefaultSizeContext';export const IconDefaultSizeProvider = IconDefaultSizeContext.Provider;diff --git a/packages/core/src/InputGroup/InputGroupContext.ts b/packages/core/src/InputGroup/InputGroupContext.tsindex f7f741d600..cd35343812 100644--- a/packages/core/src/InputGroup/InputGroupContext.ts+++ b/packages/core/src/InputGroup/InputGroupContext.ts@@ -10,7 +10,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export interface InputGroupContextValue {isInGroup: true;@@ -20,9 +20,12 @@ export interface InputGroupContextValue {describedByIDs?: string;}-export const InputGroupContext = createContext<InputGroupContextValue | null>(- null,-);+export const InputGroupContext =+ createLayerScopedContext<InputGroupContextValue | null>(+ 'InputGroupContext',+ 1,+ null,+ );InputGroupContext.displayName = 'InputGroupContext';/**diff --git a/packages/core/src/InputGroup/InputGroupInternalContext.ts b/packages/core/src/InputGroup/InputGroupInternalContext.tsindex 5045ad7751..6610edc3ff 100644--- a/packages/core/src/InputGroup/InputGroupInternalContext.ts+++ b/packages/core/src/InputGroup/InputGroupInternalContext.ts@@ -9,7 +9,11 @@* @position Internal group state; not re-exported by index.ts*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';-export const InputGroupInternalContext = createContext({isDisabled: false});+export const InputGroupInternalContext = createLayerScopedContext(+ 'InputGroupInternalContext',+ 1,+ {isDisabled: false},+);InputGroupInternalContext.displayName = 'InputGroupInternalContext';diff --git a/packages/core/src/InteractiveRoleContext/InteractiveRoleContext.ts b/packages/core/src/InteractiveRoleContext/InteractiveRoleContext.tsindex f3d3320c1e..bdd56881c4 100644--- a/packages/core/src/InteractiveRoleContext/InteractiveRoleContext.ts+++ b/packages/core/src/InteractiveRoleContext/InteractiveRoleContext.ts@@ -4,7 +4,7 @@/*** @file InteractiveRoleContext.ts- * @input React createContext, use+ * @input createSharedContext, use* @output Exports InteractiveRoleContext, useInteractiveRoleContext* @position Context primitive; consumed by useInteractiveRole hook*@@ -23,8 +23,9 @@* - /packages/core/src/InteractiveRoleContext/index.ts*/-import {createContext, use} from 'react';+import {use} from 'react';import type {InteractiveRole} from '../hooks/useInteractiveRole';+import {createSharedContext} from '../utils/sharedContext';/*** Context that provides a role override to child components.@@ -37,7 +38,11 @@ import type {InteractiveRole} from '../hooks/useInteractiveRole';* `null` means no parent is overriding — resolve based on own props.*/export const InteractiveRoleContext =- createContext<InteractiveRole | null>(null);+ createSharedContext<InteractiveRole | null>(+ 'InteractiveRoleContext',+ 1,+ null,+ );InteractiveRoleContext.displayName = 'InteractiveRoleContext';/**diff --git a/packages/core/src/Item/ItemDescriptionContext.tsx b/packages/core/src/Item/ItemDescriptionContext.tsxindex 141cd4f620..1cdd8fae08 100644--- a/packages/core/src/Item/ItemDescriptionContext.tsx+++ b/packages/core/src/Item/ItemDescriptionContext.tsx@@ -4,7 +4,7 @@/*** @file ItemDescriptionContext.tsx- * @input Uses React createContext+ * @input Uses createSharedContext* @output Exports ItemDescriptionContext* @position Internal seam between Item and a control it renders in a slot*@@ -23,7 +23,11 @@* `aria-describedby`.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const ItemDescriptionContext = createContext<string | null>(null);+export const ItemDescriptionContext = createSharedContext<string | null>(+ 'ItemDescriptionContext',+ 1,+ null,+);ItemDescriptionContext.displayName = 'ItemDescriptionContext';diff --git a/packages/core/src/Item/ItemListRowContext.tsx b/packages/core/src/Item/ItemListRowContext.tsxindex 6bbf3bafc6..3aa1ce7e2a 100644--- a/packages/core/src/Item/ItemListRowContext.tsx+++ b/packages/core/src/Item/ItemListRowContext.tsx@@ -4,7 +4,7 @@/*** @file ItemListRowContext.tsx- * @input Uses React createContext+ * @input Uses createSharedContext* @output Exports ItemListRowContext* @position Internal seam between ListItem and the Item it renders. Under a* coarse primary pointer a List row's whole touch target follows its link,@@ -12,7 +12,11 @@* content, and a standalone Item has none.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const ItemListRowContext = createContext(false);+export const ItemListRowContext = createSharedContext(+ 'ItemListRowContext',+ 1,+ false,+);ItemListRowContext.displayName = 'ItemListRowContext';diff --git a/packages/core/src/Item/ItemMarkerColumnsContext.tsx b/packages/core/src/Item/ItemMarkerColumnsContext.tsxindex b9ac4ee8d4..9beff00c1e 100644--- a/packages/core/src/Item/ItemMarkerColumnsContext.tsx+++ b/packages/core/src/Item/ItemMarkerColumnsContext.tsx@@ -14,7 +14,12 @@* marker and does not inherit the formatting request.*/-import {createContext, type ReactNode} from 'react';+import type {ReactNode} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const ItemMarkerColumnsContext = createContext<ReactNode>(null);+export const ItemMarkerColumnsContext = createSharedContext<ReactNode>(+ 'ItemMarkerColumnsContext',+ 1,+ null,+);ItemMarkerColumnsContext.displayName = 'ItemMarkerColumnsContext';diff --git a/packages/core/src/Layer/LayerContext.ts b/packages/core/src/Layer/LayerContext.tsindex eee3efa5db..36e4831715 100644--- a/packages/core/src/Layer/LayerContext.ts+++ b/packages/core/src/Layer/LayerContext.ts@@ -13,7 +13,8 @@* - /packages/core/src/Layer/LayerProvider.tsx*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** The inset an app declares for a persistent bar floating over a viewport@@ -68,7 +69,11 @@ export interface LayerContextValue {* React context for the layer provider.* Default value is null — hooks detect this and use the fallback.*/-export const LayerContext = createContext<LayerContextValue | null>(null);+export const LayerContext = createSharedContext<LayerContextValue | null>(+ 'LayerContext',+ 1,+ null,+);LayerContext.displayName = 'LayerContext';/**diff --git a/packages/core/src/Layer/LayerDepthContext.tsx b/packages/core/src/Layer/LayerDepthContext.tsxindex 24f8491f49..5954c83249 100644--- a/packages/core/src/Layer/LayerDepthContext.tsx+++ b/packages/core/src/Layer/LayerDepthContext.tsx@@ -28,13 +28,14 @@* each layer provides depth for its OWN content, so nesting composes on its own.*/-import {createContext, use, type ReactNode} from 'react';+import {use, type ReactNode} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** How many layers deep the current subtree is. 0 at the app root; each layer* increments it for its own content.*/-export const LayerDepthContext = createContext(0);+export const LayerDepthContext = createSharedContext('LayerDepthContext', 1, 0);LayerDepthContext.displayName = 'LayerDepthContext';/**diff --git a/packages/core/src/Layer/layerScopedContext.test.tsx b/packages/core/src/Layer/layerScopedContext.test.tsxindex 9afe2963d3..c45752e533 100644--- a/packages/core/src/Layer/layerScopedContext.test.tsx+++ b/packages/core/src/Layer/layerScopedContext.test.tsx@@ -52,7 +52,7 @@ import {} from '../Stepper/StepperContext';const noop = () => {};-const Scoped = createLayerScopedContext('default');+const Scoped = createLayerScopedContext('TestScopedContext', 1, 'default');const ServiceContext = createContext('service');ServiceContext.displayName = 'ServiceContext';@@ -89,7 +89,11 @@ describe('layer-scoped context', () => {selected: new Set<string>(),onChange: vi.fn(),};- const Membership = createLayerScopedContext(fallback);+ const Membership = createLayerScopedContext(+ 'TestMembershipContext',+ 1,+ fallback,+ );const outer = {isDisabled: true,selected: new Set(['outer']),@@ -111,7 +115,11 @@ describe('layer-scoped context', () => {});it('keeps the public depth provider limited to depth', () => {- const Membership = createLayerScopedContext('default');+ const Membership = createLayerScopedContext(+ 'TestDepthMembershipContext',+ 1,+ 'default',+ );function Probe() {expect(use(Membership)).toBe('outer');expect(use(LayerDepthContext)).toBe(3);@@ -178,7 +186,7 @@ describe('layer-scoped context', () => {const input = screen.getByRole('textbox');fireEvent.change(input, {target: {value: 'keep me'}});input.focus();- const Late = createLayerScopedContext('late default');+ const Late = createLayerScopedContext('TestLateContext', 1, 'late default');rerender(<LayerContentBoundary><Content />diff --git a/packages/core/src/Layer/layerScopedContext.tsx b/packages/core/src/Layer/layerScopedContext.tsxindex 0b1f6c616f..3e209225d8 100644--- a/packages/core/src/Layer/layerScopedContext.tsx+++ b/packages/core/src/Layer/layerScopedContext.tsx@@ -10,15 +10,42 @@*/import {createContext, useState, type Context, type ReactNode} from 'react';+import {createSharedContext} from '../utils/sharedContext';+import {realmValue, sharedKey} from '../utils/sharedRealm';type Reset = (children: ReactNode) => ReactNode;-const resets: Reset[] = [];+/**+ * The reset of each layer-scoped context from every copy of Core on this+ * React. A layer boundary from any of those copies resets them all, and never+ * renders another React's contexts.+ */+const resetsByReact = realmValue(+ sharedKey('layer-scoped-context-resets', 2),+ () => new WeakMap<typeof createContext, Map<Context<unknown>, Reset>>(),+ value => value instanceof WeakMap,+);+let resets = resetsByReact.get(createContext);+if (resets == null) {+ resets = new Map();+ resetsByReact.set(createContext, resets);+}+const reactResets = resets;-/** Create a surface-scoped context whose whole default applies in a new layer. */-export function createLayerScopedContext<T>(defaultValue: T): Context<T> {- const Context = createContext(defaultValue);- Context.displayName = 'LayerScopedContext';- resets.push(children => <Context value={defaultValue}>{children}</Context>);+/**+ * Create a surface-scoped context whose whole default applies in a new layer.+ * The name and version register it like `createSharedContext`.+ */+export function createLayerScopedContext<T>(+ name: string,+ version: number,+ defaultValue: T,+): Context<T> {+ const Context = createSharedContext(name, version, defaultValue);+ if (!reactResets.has(Context as Context<unknown>)) {+ reactResets.set(Context as Context<unknown>, children => (+ <Context value={defaultValue}>{children}</Context>+ ));+ }return Context;}@@ -29,7 +56,7 @@ export function LayerContentBoundary({}): ReactNode {// Keep the provider chain stable for this mount: lazy imports must not// remount existing content and discard its state or focus.- const [resetChain] = useState(() => resets.slice());+ const [resetChain] = useState(() => [...reactResets.values()]);return resetChain.reduceRight((content, reset): ReactNode => reset(content),children,diff --git a/packages/core/src/Layer/sharedContexts.test.tsx b/packages/core/src/Layer/sharedContexts.test.tsxnew file mode 100644index 0000000000..d8cd76027e--- /dev/null+++ b/packages/core/src/Layer/sharedContexts.test.tsx@@ -0,0 +1,266 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * A swizzled copy loads its own instance of Core's modules beside the+ * package's. These tests load a second instance of a module, as a copy does,+ * and check that the copy and the package still share one context.+ */++import * as fs from 'node:fs';+import {createRequire} from 'node:module';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {render, screen} from '@testing-library/react';+import {use} from 'react';+import {describe, expect, it, vi} from 'vitest';++/** A new instance of a module, as a swizzled copy of it loads. */+async function freshInstance<T>(load: () => Promise<T>): Promise<T> {+ vi.resetModules();+ return load();+}++describe('contexts shared by a swizzled copy and the package', () => {+ it('two instances of a context module give one context', async () => {+ const pkg = await freshInstance(+ async () => import('../InputGroup/InputGroupInternalContext'),+ );+ const copy = await freshInstance(+ async () => import('../InputGroup/InputGroupInternalContext'),+ );+ // Two module instances, as a copy and the package are.+ expect(copy).not.toBe(pkg);+ expect(copy.InputGroupInternalContext).toBe(pkg.InputGroupInternalContext);+ });++ it('a provider from the package reaches a consumer from a copy', async () => {+ const pkg = await freshInstance(async () => import('../Layer/toastHost'));+ const copy = await freshInstance(async () => import('../Layer/toastHost'));+ const value = {} as NonNullable<React.ContextType<typeof pkg.ToastContext>>;+ function CopiedConsumer() {+ return (+ <span data-testid="probe">+ {String(use(copy.ToastContext) === value)}+ </span>+ );+ }+ render(+ <pkg.ToastContext value={value}>+ <CopiedConsumer />+ </pkg.ToastContext>,+ );+ expect(screen.getByTestId('probe').textContent).toBe('true');+ });++ it("the package's English context resolves a copy's English", async () => {+ const pkg = await freshInstance(+ async () => import('../i18n/InternationalizationContext'),+ );+ const copy = await freshInstance(+ async () => import('../i18n/englishFallback'),+ );+ // A copied component registers the English it names when it loads.+ copy.registerEnglishFallback({'@astryx.test.copyOnly': 'Copied English'});+ function CopiedConsumer() {+ const {translate} = use(pkg.InternationalizationContext);+ return (+ <span data-testid="probe">+ {translate('@astryx.test.copyOnly', undefined)}+ </span>+ );+ }+ render(<CopiedConsumer />);+ expect(screen.getByTestId('probe').textContent).toBe('Copied English');+ });++ it("the package's layer boundary resets a copy's layer-scoped context", async () => {+ const pkg = await freshInstance(async () => import('./layerScopedContext'));+ const copy = await freshInstance(+ async () => import('../InputGroup/InputGroupInternalContext'),+ );+ function CopiedConsumer() {+ const {isDisabled} = use(copy.InputGroupInternalContext);+ return <span data-testid="probe">{String(isDisabled)}</span>;+ }+ render(+ <copy.InputGroupInternalContext value={{isDisabled: true}}>+ <pkg.LayerContentBoundary>+ <CopiedConsumer />+ </pkg.LayerContentBoundary>+ </copy.InputGroupInternalContext>,+ );+ // Group state stops at the layer boundary, as it does with the package alone.+ expect(screen.getByTestId('probe').textContent).toBe('false');+ });+});++describe('two Reacts in one process', () => {+ /**+ * A second instance of React, as a server that loads two React copies has.+ * Node keeps one instance per resolved file, so drop React's files from+ * the require cache, load it again, then put the first instance back.+ */+ function secondReact(): typeof import('react') {+ const require = createRequire(import.meta.url);+ const isReactFile = (file: string) =>+ /[\\/]node_modules[\\/]react[\\/]/.test(file);+ const saved = Object.keys(require.cache)+ .filter(isReactFile)+ .map(file => [file, require.cache[file]] as const);+ for (const [file] of saved) {+ Reflect.deleteProperty(require.cache, file);+ }+ try {+ return require('react') as typeof import('react');+ } finally {+ for (const [file, module] of saved) {+ require.cache[file] = module;+ }+ }+ }++ /** The shared-context module as it loads on `react`. */+ async function sharedContextOn(react: typeof import('react')) {+ vi.resetModules();+ vi.doMock('react', () => ({...react, default: react}));+ try {+ return await import('../utils/sharedContext');+ } finally {+ vi.doUnmock('react');+ }+ }++ it('gives each React its own context under a key, and one per React', async () => {+ const otherReact = secondReact();+ expect(otherReact.createContext).not.toBe(+ (await import('react')).createContext,+ );+ const onThisReact = await freshInstance(+ async () => import('../utils/sharedContext'),+ );+ const copyOnThisReact = await freshInstance(+ async () => import('../utils/sharedContext'),+ );+ const onOtherReact = await sharedContextOn(otherReact);+ const name = 'TwoReactsProbe';+ const context = onThisReact.createSharedContext(name, 1, 'default');+ // Two copies of Core on one React share the context.+ expect(copyOnThisReact.createSharedContext(name, 1, 'default')).toBe(+ context,+ );+ // A copy on another React gets its own, so a request it renders never+ // reads a value a request on this React provided.+ const other = onOtherReact.createSharedContext(name, 1, 'default');+ expect(other).not.toBe(context);+ expect(onOtherReact.createSharedContext(name, 1, 'default')).toBe(other);+ });+});++describe('every Core context is registered under a versioned key', () => {+ const SRC = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+ const sources = fs+ .readdirSync(SRC, {recursive: true, withFileTypes: true})+ .filter(+ entry =>+ entry.isFile() &&+ /\.tsx?$/.test(entry.name) &&+ !/\.(test|spec|stories|d)\.tsx?$/.test(entry.name) &&+ !entry.parentPath.includes('__tests__'),+ )+ .map(entry => path.join(entry.parentPath, entry.name));+ const FACTORIES = new Set([+ path.join(SRC, 'utils/sharedContext.ts'),+ path.join(SRC, 'Layer/layerScopedContext.tsx'),+ ]);++ it('no module creates a context of its own', () => {+ const direct = sources+ .filter(file => !FACTORIES.has(file))+ .filter(file =>+ /\bcreateContext\s*[<(]/.test(fs.readFileSync(file, 'utf-8')),+ )+ .map(file => path.relative(SRC, file));+ expect(direct).toEqual([]);+ });++ it('each key names one context', () => {+ const owners = new Map<string, string[]>();+ for (const file of sources) {+ if (FACTORIES.has(file)) {+ continue;+ }+ const text = fs+ .readFileSync(file, 'utf-8')+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/^\s*\/\/.*$/gm, '');+ const calls =+ text.match(/\bcreate(?:Shared|LayerScoped)Context\b/g) ?? [];+ const keyed = [+ ...text.matchAll(+ /\bcreate(?:Shared|LayerScoped)Context\b(?:<[\s\S]*?>)?\(\s*'([^']+)',\s*\d+\s*,/g,+ ),+ ];+ // Every call names its key and version; imports name the factory too.+ const imports = (+ text.match(+ /import[^;]*\bcreate(?:Shared|LayerScoped)Context\b[^;]*;/g,+ ) ?? []+ ).length;+ expect(keyed.length, path.relative(SRC, file)).toBe(+ calls.length - imports,+ );+ for (const m of keyed) {+ owners.set(m[1], [+ ...(owners.get(m[1]) ?? []),+ path.relative(SRC, file),+ ]);+ }+ }+ expect(owners.size).toBeGreaterThan(0);+ const shared = [...owners].filter(([, files]) => files.length > 1);+ expect(shared).toEqual([]);+ });+});++describe('shared state in server-safe modules', () => {+ const SRC = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+ /** Every module a file reaches through relative imports, itself included. */+ function reachedFrom(entry: string): string[] {+ const seen = new Set<string>();+ const queue = [entry];+ while (queue.length > 0) {+ const file = queue.shift() as string;+ if (seen.has(file)) {+ continue;+ }+ seen.add(file);+ const text = fs.readFileSync(file, 'utf-8');+ for (const m of text.matchAll(+ /^import[^'"]*['"](\.{1,2}\/[^'"]+)['"]/gm,+ )) {+ if (/^import\s+type\b/.test(m[0])) {+ continue;+ }+ const base = path.resolve(path.dirname(file), m[1]);+ const target = ['.ts', '.tsx', '/index.ts']+ .map(ext => base + ext)+ .find(f => fs.existsSync(f));+ if (target) {+ queue.push(target);+ }+ }+ }+ return [...seen];+ }++ it('the English fallback reaches no client module, so it still loads on the server', () => {+ const client = reachedFrom(path.join(SRC, 'i18n/englishFallback.ts'))+ .filter(file =>+ /^(?:\/\/[^\n]*\n|\s)*['"]use client['"]/.test(+ fs.readFileSync(file, 'utf-8'),+ ),+ )+ .map(file => path.relative(SRC, file));+ expect(client).toEqual([]);+ });+});diff --git a/packages/core/src/Layer/toastHost.tsx b/packages/core/src/Layer/toastHost.tsxindex 010aabb006..c0e913a6e9 100644--- a/packages/core/src/Layer/toastHost.tsx+++ b/packages/core/src/Layer/toastHost.tsx@@ -16,7 +16,6 @@*/import {- createContext,use,useEffect,useState,@@ -26,6 +25,7 @@ import {} from 'react';import type {ToastDismissReason, ToastEntry} from '../Toast/types';import type {LayerInset, LayerToastConfig} from './LayerContext';+import {createSharedContext} from '../utils/sharedContext';/** Internal context value for toast state management. */export interface ToastContextValue {@@ -42,7 +42,11 @@ export interface ToastContextValue {* provide it without importing Toast. With no provider it is null, and* `useToast` mounts a viewport of its own.*/-export const ToastContext = createContext<ToastContextValue | null>(null);+export const ToastContext = createSharedContext<ToastContextValue | null>(+ 'ToastContext',+ 1,+ null,+);ToastContext.displayName = 'ToastContext';/**diff --git a/packages/core/src/Layout/LayoutAreaContext.ts b/packages/core/src/Layout/LayoutAreaContext.tsindex 680d213ee5..2c684f1998 100644--- a/packages/core/src/Layout/LayoutAreaContext.ts+++ b/packages/core/src/Layout/LayoutAreaContext.ts@@ -4,7 +4,7 @@/*** @file LayoutAreaContext.ts- * @input Uses React createContext+ * @input Uses createSharedContext* @output Exports LayoutAreaContext and LayoutArea type* @position Context for layout slot detection*@@ -12,19 +12,14 @@* - /packages/core/src/Layout/Layout.doc.mjs*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** Layout area type representing which slot a component is rendered in.* Used by content area components to detect their position and adjust styling.*/export type LayoutArea =- | 'header'- | 'footer'- | 'content'- | 'start'- | 'end'- | null;+ 'header' | 'footer' | 'content' | 'start' | 'end' | null;/*** Context for detecting which layout area a component is rendered in.@@ -33,5 +28,9 @@ export type LayoutArea =* - Apply correct semantic elements* - Adjust internal spacing*/-export const LayoutAreaContext = createContext<LayoutArea>(null);+export const LayoutAreaContext = createSharedContext<LayoutArea>(+ 'LayoutAreaContext',+ 1,+ null,+);LayoutAreaContext.displayName = 'LayoutAreaContext';diff --git a/packages/core/src/Layout/LayoutDividerContext.ts b/packages/core/src/Layout/LayoutDividerContext.tsindex bd24f16082..6c399660e9 100644--- a/packages/core/src/Layout/LayoutDividerContext.ts+++ b/packages/core/src/Layout/LayoutDividerContext.ts@@ -16,12 +16,16 @@* - /packages/core/src/Layout/LayoutFooter.tsx*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export interface LayoutDividerContextValue {defaultHasDividers: boolean;}export const LayoutDividerContext =- createContext<LayoutDividerContextValue | null>(null);+ createLayerScopedContext<LayoutDividerContextValue | null>(+ 'LayoutDividerContext',+ 1,+ null,+ );LayoutDividerContext.displayName = 'LayoutDividerContext';diff --git a/packages/core/src/Layout/LayoutSlotsContext.ts b/packages/core/src/Layout/LayoutSlotsContext.tsindex d6553a987d..afc26123f4 100644--- a/packages/core/src/Layout/LayoutSlotsContext.ts+++ b/packages/core/src/Layout/LayoutSlotsContext.ts@@ -13,7 +13,7 @@* - /packages/core/src/Layout/Layout/index.ts*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';/*** Information about which layout slots are filled.@@ -47,6 +47,9 @@ export const DEFAULT_LAYOUT_SLOTS: LayoutSlots = {* Content area components use this to determine if they are at an edge* (for applying outer padding).*/-export const LayoutSlotsContext =- createContext<LayoutSlots>(DEFAULT_LAYOUT_SLOTS);+export const LayoutSlotsContext = createLayerScopedContext<LayoutSlots>(+ 'LayoutSlotsContext',+ 1,+ DEFAULT_LAYOUT_SLOTS,+);LayoutSlotsContext.displayName = 'LayoutSlotsContext';diff --git a/packages/core/src/Link/LinkContext.ts b/packages/core/src/Link/LinkContext.tsindex 666da992c8..d02ccc6bfc 100644--- a/packages/core/src/Link/LinkContext.ts+++ b/packages/core/src/Link/LinkContext.ts@@ -4,7 +4,7 @@/*** @file LinkContext.ts- * @input React createContext, LinkComponentType+ * @input createSharedContext, LinkComponentType* @output Exports LinkContext and LinkContextValue* @position Context definition for polymorphic link support*@@ -19,8 +19,8 @@* - /packages/core/src/Link/Link.doc.mjs*/-import {createContext} from 'react';import type {LinkComponentType} from './types';+import {createSharedContext} from '../utils/sharedContext';/*** Context value for the link provider.@@ -33,5 +33,9 @@ export interface LinkContextValue {* Context for providing a custom link component to all Astryx components.* Defaults to null (components fall back to native `<a>`).*/-export const LinkContext = createContext<LinkContextValue | null>(null);+export const LinkContext = createSharedContext<LinkContextValue | null>(+ 'LinkContext',+ 1,+ null,+);LinkContext.displayName = 'LinkContext';diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex 8f32232e4c..0efecc2904 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -14,7 +14,7 @@*/import {use, useMemo, type ReactNode} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import type {AnimatedLayout} from '../hooks/useAnimatedLayout';export type ListDensity = 'compact' | 'balanced' | 'spacious';@@ -70,7 +70,11 @@ export interface ListContextValue {animatedLayout?: AnimatedLayout;}-export const ListContext = createContext<ListContextValue | null>(null);+export const ListContext = createLayerScopedContext<ListContextValue | null>(+ 'ListContext',+ 1,+ null,+);ListContext.displayName = 'ListContext';/**diff --git a/packages/core/src/MetadataList/MetadataListContext.tsx b/packages/core/src/MetadataList/MetadataListContext.tsxindex e477fff4b3..db073f19fa 100644--- a/packages/core/src/MetadataList/MetadataListContext.tsx+++ b/packages/core/src/MetadataList/MetadataListContext.tsx@@ -9,7 +9,7 @@* @position Internal context; consumed by MetadataList.tsx and MetadataListItem.tsx*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export interface MetadataListLabelConfig {position?: 'start' | 'top';@@ -22,5 +22,9 @@ export interface MetadataListContextValue {}export const MetadataListContext =- createContext<MetadataListContextValue | null>(null);+ createLayerScopedContext<MetadataListContextValue | null>(+ 'MetadataListContext',+ 1,+ null,+ );MetadataListContext.displayName = 'MetadataListContext';diff --git a/packages/core/src/NavMenu/NavMenuContext.tsx b/packages/core/src/NavMenu/NavMenuContext.tsxindex 0c716eb378..6950fe9978 100644--- a/packages/core/src/NavMenu/NavMenuContext.tsx+++ b/packages/core/src/NavMenu/NavMenuContext.tsx@@ -12,8 +12,9 @@* - /packages/core/src/NavMenu/index.ts*/-import {createContext, use} from 'react';+import {use} from 'react';import {createLayerScopedContext} from '../Layer/layerScopedContext';+import {createSharedContext} from '../utils/sharedContext';export type NavHeadingMenuSize = 'sm' | 'md' | 'lg';@@ -27,7 +28,11 @@ export interface NavHeadingCloseContextValue {}export const NavHeadingCloseContext =- createContext<NavHeadingCloseContextValue | null>(null);+ createSharedContext<NavHeadingCloseContextValue | null>(+ 'NavHeadingCloseContext',+ 1,+ null,+ );NavHeadingCloseContext.displayName = 'NavHeadingCloseContext';export function useNavHeadingCloseContext(): NavHeadingCloseContextValue | null {@@ -40,9 +45,9 @@ export function useNavHeadingCloseContext(): NavHeadingCloseContextValue | null* expanded SideNavHeading, FR7). NavHeadingMenu calls it for a mouse released* outside, never on an item's selection.*/-export const NavHeadingDismissContext = createContext<{+export const NavHeadingDismissContext = createSharedContext<{dismiss: () => void;-} | null>(null);+} | null>('NavHeadingDismissContext', 1, null);NavHeadingDismissContext.displayName = 'NavHeadingDismissContext';/**@@ -55,7 +60,11 @@ export interface NavHeadingMenuContextValue {}export const NavHeadingMenuContext =- createLayerScopedContext<NavHeadingMenuContextValue | null>(null);+ createLayerScopedContext<NavHeadingMenuContextValue | null>(+ 'NavHeadingMenuContext',+ 1,+ null,+ );NavHeadingMenuContext.displayName = 'NavHeadingMenuContext';export function useNavHeadingMenuContext(): NavHeadingMenuContextValue | null {diff --git a/packages/core/src/RadioList/RadioList.tsx b/packages/core/src/RadioList/RadioList.tsxindex 70bbaeb9b8..929627caee 100644--- a/packages/core/src/RadioList/RadioList.tsx+++ b/packages/core/src/RadioList/RadioList.tsx@@ -17,7 +17,7 @@*/import {RadioListReasonContext} from './RadioListReasonContext';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import React, {useCallback,useId,@@ -63,9 +63,12 @@ export interface RadioListContextValue {status?: InputStatus;}-export const RadioListContext = createContext<RadioListContextValue | null>(- null,-);+export const RadioListContext =+ createLayerScopedContext<RadioListContextValue | null>(+ 'RadioListContext',+ 1,+ null,+ );RadioListContext.displayName = 'RadioListContext';const styles = stylex.create({diff --git a/packages/core/src/RadioList/RadioListReasonContext.ts b/packages/core/src/RadioList/RadioListReasonContext.tsindex c4a8d4dd74..12cb6b40fc 100644--- a/packages/core/src/RadioList/RadioListReasonContext.ts+++ b/packages/core/src/RadioList/RadioListReasonContext.ts@@ -21,5 +21,5 @@ import {createLayerScopedContext} from '../Layer/layerScopedContext';// group is not a radio of it.export const RadioListReasonContext = createLayerScopedContext<string | undefined->(undefined);+>('RadioListReasonContext', 1, undefined);RadioListReasonContext.displayName = 'RadioListReasonContext';diff --git a/packages/core/src/SegmentedControl/SegmentedControlContext.ts b/packages/core/src/SegmentedControl/SegmentedControlContext.tsindex a7f94d7bae..83c7f45a13 100644--- a/packages/core/src/SegmentedControl/SegmentedControlContext.ts+++ b/packages/core/src/SegmentedControl/SegmentedControlContext.ts@@ -12,7 +12,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export type SegmentedControlSize = 'sm' | 'md' | 'lg';export type SegmentedControlLayout = 'hug' | 'fill';@@ -38,7 +38,11 @@ export interface SegmentedControlContextValue {}export const SegmentedControlContext =- createContext<SegmentedControlContextValue | null>(null);+ createLayerScopedContext<SegmentedControlContextValue | null>(+ 'SegmentedControlContext',+ 1,+ null,+ );SegmentedControlContext.displayName = 'SegmentedControlContext';export function useSegmentedControlContext(): SegmentedControlContextValue {diff --git a/packages/core/src/SelectableCard/selectableCardInput.ts b/packages/core/src/SelectableCard/selectableCardInput.tsindex 090e8377bc..89e1855830 100644--- a/packages/core/src/SelectableCard/selectableCardInput.ts+++ b/packages/core/src/SelectableCard/selectableCardInput.ts@@ -12,7 +12,7 @@* SelectableCard's public props do not change.*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';/** The native input a group gives one card. */export interface SelectableCardInput {@@ -26,5 +26,9 @@ export interface SelectableCardInput {/** Without a provider, a card renders its own checkbox. */export const SelectableCardInputContext =- createContext<SelectableCardInput | null>(null);+ createSharedContext<SelectableCardInput | null>(+ 'SelectableCardInputContext',+ 1,+ null,+ );SelectableCardInputContext.displayName = 'SelectableCardInputContext';diff --git a/packages/core/src/Selector/SelectorRowLayoutContext.ts b/packages/core/src/Selector/SelectorRowLayoutContext.tsindex 86b3d057f4..3ba96b8265 100644--- a/packages/core/src/Selector/SelectorRowLayoutContext.ts+++ b/packages/core/src/Selector/SelectorRowLayoutContext.ts@@ -16,12 +16,16 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export type SelectorRowLayout = 'stacked' | 'inline';export const SelectorRowLayoutContext =- createContext<SelectorRowLayout>('stacked');+ createLayerScopedContext<SelectorRowLayout>(+ 'SelectorRowLayoutContext',+ 1,+ 'stacked',+ );SelectorRowLayoutContext.displayName = 'SelectorRowLayoutContext';/**diff --git a/packages/core/src/SideNav/SideNavCollapseContext.ts b/packages/core/src/SideNav/SideNavCollapseContext.tsindex e223ec8f4f..78674e9884 100644--- a/packages/core/src/SideNav/SideNavCollapseContext.ts+++ b/packages/core/src/SideNav/SideNavCollapseContext.ts@@ -4,7 +4,7 @@/*** @file SideNavCollapseContext.ts- * @input React createContext, use+ * @input createSharedContext, use* @output Exports SideNavCollapseContext and useSideNavCollapse hook* @position Internal context for sidenav collapse state*@@ -14,7 +14,8 @@* takes the controlled `collapsible` config as a prop instead.*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export interface SideNavCollapseState {/** Whether the sidenav is currently collapsed */@@ -52,11 +53,15 @@ export interface SideNavImperativeCollapseHandle {getCollapseState: () => SideNavCollapseState | null;}-export const SideNavCollapseContext = createContext<SideNavCollapseState>({- isCollapsed: false,- toggle: () => {},- isCollapsible: false,-});+export const SideNavCollapseContext = createSharedContext<SideNavCollapseState>(+ 'SideNavCollapseContext',+ 1,+ {+ isCollapsed: false,+ toggle: () => {},+ isCollapsible: false,+ },+);SideNavCollapseContext.displayName = 'SideNavCollapseContext';/**diff --git a/packages/core/src/SideNav/SideNavFocusTargetsContext.ts b/packages/core/src/SideNav/SideNavFocusTargetsContext.tsindex 090e71590a..cabebc6630 100644--- a/packages/core/src/SideNav/SideNavFocusTargetsContext.ts+++ b/packages/core/src/SideNav/SideNavFocusTargetsContext.ts@@ -12,7 +12,7 @@* rendered inside the SideNav, registers itself (`component:SideNav` AR3).*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';export interface SideNavFocusTargets {/**@@ -25,5 +25,9 @@ export interface SideNavFocusTargets {}export const SideNavFocusTargetsContext =- createContext<SideNavFocusTargets | null>(null);+ createSharedContext<SideNavFocusTargets | null>(+ 'SideNavFocusTargetsContext',+ 1,+ null,+ );SideNavFocusTargetsContext.displayName = 'SideNavFocusTargetsContext';diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsxindex 00b36b020c..28966f616b 100644--- a/packages/core/src/SideNav/SideNavItem.tsx+++ b/packages/core/src/SideNav/SideNavItem.tsx@@ -35,7 +35,6 @@*/import {- createContext,use,useCallback,useId,@@ -87,6 +86,7 @@ import {} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/SideNav/SideNavItem.generated';import {isRenderable} from '../utils/isRenderable';+import {createSharedContext} from '../utils/sharedContext';registerEnglishFallback(english);// =============================================================================@@ -299,7 +299,11 @@ const indentStyles = stylex.create({* 1 inside one parent, and so on. A collapsed rail's flyout resets it to 0,* since the flyout lists a parent's children as its own top level.*/-const SideNavItemDepthContext = createContext(0);+const SideNavItemDepthContext = createSharedContext(+ 'SideNavItemDepthContext',+ 1,+ 0,+);SideNavItemDepthContext.displayName = 'SideNavItemDepthContext';/**diff --git a/packages/core/src/SideNav/SideNavRenderContext.ts b/packages/core/src/SideNav/SideNavRenderContext.tsindex 31be15751e..982f7b759b 100644--- a/packages/core/src/SideNav/SideNavRenderContext.ts+++ b/packages/core/src/SideNav/SideNavRenderContext.ts@@ -4,7 +4,7 @@/*** @file SideNavRenderContext.ts- * @input React createContext, use+ * @input createSharedContext, use* @output Exports SideNavRenderContext and useSideNavRenderMode hook* @position Internal context for controlling SideNav rendering mode*@@ -15,16 +15,17 @@* - 'drawer': children only, skip heading + footerIcons (mobile drawer)*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export type SideNavRenderMode =- | 'default'- | 'topbar'- | 'drawer'- | 'drawer-content';+ 'default' | 'topbar' | 'drawer' | 'drawer-content';-export const SideNavRenderContext =- createContext<SideNavRenderMode>('default');+export const SideNavRenderContext = createSharedContext<SideNavRenderMode>(+ 'SideNavRenderContext',+ 1,+ 'default',+);SideNavRenderContext.displayName = 'SideNavRenderContext';/**diff --git a/packages/core/src/SideNav/railMotion.ts b/packages/core/src/SideNav/railMotion.tsindex 76fe547004..5d6e87e800 100644--- a/packages/core/src/SideNav/railMotion.ts+++ b/packages/core/src/SideNav/railMotion.ts@@ -43,7 +43,6 @@* SideNavRailMotion.test.tsx.*/-import {createContext} from 'react';import {createAnimatedLayout,holdLayoutEdge,@@ -52,6 +51,7 @@ import {type LayoutEdgeHold,type LayoutSwap,} from '../motion/animatedLayout';+import {createSharedContext} from '../utils/sharedContext';/** What AppShell lends its SideNav; outside AppShell, nothing. */export interface SideNavShell {@@ -69,7 +69,11 @@ export interface SideNavShell {landContent(): void;}-export const SideNavShellContext = createContext<SideNavShell | null>(null);+export const SideNavShellContext = createSharedContext<SideNavShell | null>(+ 'SideNavShellContext',+ 1,+ null,+);SideNavShellContext.displayName = 'SideNavShellContext';/** A SideNav outside AppShell holds its own handle over its parent. */diff --git a/packages/core/src/SizeContext/SizeContext.ts b/packages/core/src/SizeContext/SizeContext.tsindex b0b6a42241..3c1225ea7d 100644--- a/packages/core/src/SizeContext/SizeContext.ts+++ b/packages/core/src/SizeContext/SizeContext.ts@@ -14,7 +14,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';/*** Standard element sizes used across interactive components.@@ -26,7 +26,11 @@ export type ElementSize = 'sm' | 'md' | 'lg';** `null` means no container is providing a size — components use their own default.*/-export const SizeContext = createContext<ElementSize | null>(null);+export const SizeContext = createLayerScopedContext<ElementSize | null>(+ 'SizeContext',+ 1,+ null,+);SizeContext.displayName = 'SizeContext';/**diff --git a/packages/core/src/Spinner/SpinnerOwnerContext.ts b/packages/core/src/Spinner/SpinnerOwnerContext.tsindex cee12d56bc..729850e876 100644--- a/packages/core/src/Spinner/SpinnerOwnerContext.ts+++ b/packages/core/src/Spinner/SpinnerOwnerContext.ts@@ -16,7 +16,11 @@* - /packages/core/src/Spinner/Spinner.tsx*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const SpinnerOwnerContext = createContext(false);+export const SpinnerOwnerContext = createSharedContext(+ 'SpinnerOwnerContext',+ 1,+ false,+);SpinnerOwnerContext.displayName = 'SpinnerOwnerContext';diff --git a/packages/core/src/Stepper/StepperContext.ts b/packages/core/src/Stepper/StepperContext.tsindex c677212587..91260dc5ae 100644--- a/packages/core/src/Stepper/StepperContext.ts+++ b/packages/core/src/Stepper/StepperContext.ts@@ -26,7 +26,7 @@*/import {use, type Context} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export type StepperOrientation = 'horizontal' | 'vertical';export type StepperDensity = 'compact' | 'balanced' | 'spacious';@@ -89,11 +89,20 @@ export interface StepperInternalContextValue extends StepperContextValue {summarySlot: HTMLElement | null;}-export const StepperContext = createContext<StepperContextValue | null>(null);+export const StepperContext =+ createLayerScopedContext<StepperContextValue | null>(+ 'StepperContext',+ 1,+ null,+ );StepperContext.displayName = 'StepperContext';export const StepperInternalContext =- createContext<StepperInternalContextValue | null>(null);+ createLayerScopedContext<StepperInternalContextValue | null>(+ 'StepperInternalContext',+ 1,+ null,+ );StepperInternalContext.displayName = 'StepperInternalContext';function useContextValue<T>(context: Context<T | null>, hookName: string): T {diff --git a/packages/core/src/TabList/TabListContext.ts b/packages/core/src/TabList/TabListContext.tsindex 2424c6ba06..3a2dc38af5 100644--- a/packages/core/src/TabList/TabListContext.ts+++ b/packages/core/src/TabList/TabListContext.ts@@ -12,7 +12,7 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';/*** Size variants for tab list items.@@ -48,7 +48,12 @@ export interface TabListContextValue {pattern: TabListPattern;}-export const TabListContext = createContext<TabListContextValue | null>(null);+export const TabListContext =+ createLayerScopedContext<TabListContextValue | null>(+ 'TabListContext',+ 1,+ null,+ );TabListContext.displayName = 'TabListContext';/**diff --git a/packages/core/src/Table/Table.tsx b/packages/core/src/Table/Table.tsxindex a6f5ad67bc..ff8ace56d7 100644--- a/packages/core/src/Table/Table.tsx+++ b/packages/core/src/Table/Table.tsx@@ -17,7 +17,7 @@* - /packages/cli/assets/templates/blocks/components/Table/ (showcase blocks)*/-import {createContext, use, useMemo, type ReactElement, type Ref} from 'react';+import {use, useMemo, type ReactElement, type Ref} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars} from '../theme/tokens.stylex';import {BaseTable} from './BaseTable';@@ -38,6 +38,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/Table/Table.generated';+import {createSharedContext} from '../utils/sharedContext';registerEnglishFallback(english);@@ -146,10 +147,10 @@ const scrollWrapperStyles = stylex.create({* Internal to Table: the scroll wrapper is not given it as a prop, so it adds* nothing to the public table types.*/-const TableNameContext = createContext<{+const TableNameContext = createSharedContext<{label?: string;labelledBy?: string;-} | null>(null);+} | null>('TableNameContext', 1, null);TableNameContext.displayName = 'TableNameContext';function TableScrollWrapper({diff --git a/packages/core/src/Table/TableContext.ts b/packages/core/src/Table/TableContext.tsindex c2a03c5424..651e4f1d32 100644--- a/packages/core/src/Table/TableContext.ts+++ b/packages/core/src/Table/TableContext.ts@@ -15,7 +15,7 @@* - /packages/core/src/Table/index.ts (exports if types change)*/-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import type {TableVerticalAlign} from './types';export interface TableContextValue {@@ -27,5 +27,9 @@ export interface TableContextValue {textOverflow: 'wrap' | 'truncate';}-export const TableContext = createContext<TableContextValue | null>(null);+export const TableContext = createLayerScopedContext<TableContextValue | null>(+ 'TableContext',+ 1,+ null,+);TableContext.displayName = 'TableContext';diff --git a/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx b/packages/core/src/Table/plugins/filtering/useTableFiltering.tsxindex fc0cb8b75e..82d389e261 100644--- a/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx+++ b/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx@@ -14,7 +14,6 @@*/import {- createContext,use,useRef,useMemo,@@ -69,6 +68,7 @@ import {useComponentTranslator,} from '../../../i18n/useComponentTranslator';import english from '../../../i18n/generated-english/Table/plugins/filtering/useTableFiltering.generated';+import {createSharedContext} from '../../../utils/sharedContext';registerEnglishFallback(english);@@ -338,7 +338,11 @@ interface FilterStore {getConfig: () => UseTableFilteringConfig;}-const FilterStoreContext = createContext<FilterStore | null>(null);+const FilterStoreContext = createSharedContext<FilterStore | null>(+ 'FilterStoreContext',+ 1,+ null,+);FilterStoreContext.displayName = 'FilterStoreContext';function useFilterStore(): FilterStore {@@ -353,7 +357,11 @@ function useFilterStore(): FilterStore {/** Variant is stable per plugin instance — kept in a separate context so* slot components can read it without going through the mutable store. */-const FilterVariantContext = createContext<TableFilterVariant>('popover');+const FilterVariantContext = createSharedContext<TableFilterVariant>(+ 'FilterVariantContext',+ 1,+ 'popover',+);FilterVariantContext.displayName = 'FilterVariantContext';// =============================================================================diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.tsxindex b92dcf8fc5..8f5bf31999 100644--- a/packages/core/src/Table/plugins/selection/useTableSelection.tsx+++ b/packages/core/src/Table/plugins/selection/useTableSelection.tsx@@ -38,7 +38,6 @@*/import {- createContext,use,useCallback,useEffect,@@ -58,6 +57,7 @@ import {useComponentTranslator,} from '../../../i18n/useComponentTranslator';import english from '../../../i18n/generated-english/Table/plugins/selection/useTableSelection.generated';+import {createSharedContext} from '../../../utils/sharedContext';registerEnglishFallback(english);@@ -190,7 +190,11 @@ function applyRowSelectionStyle(// =============================================================================// eslint-disable-next-line @typescript-eslint/no-explicit-any-const SelectionStoreContext = createContext<SelectionStore<any> | null>(null);+const SelectionStoreContext = createSharedContext<SelectionStore<any> | null>(+ 'SelectionStoreContext',+ 1,+ null,+);SelectionStoreContext.displayName = 'SelectionStoreContext';// =============================================================================diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsxindex 1e69402ffd..91c1e8b056 100644--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx@@ -30,7 +30,6 @@*/import {- createContext,use,useCallback,useEffect,@@ -58,6 +57,7 @@ import {useComponentTranslator,} from '../../../i18n/useComponentTranslator';import english from '../../../i18n/generated-english/Table/plugins/tree/useTableTreeData.generated';+import {createSharedContext} from '../../../utils/sharedContext';registerEnglishFallback(english);@@ -172,7 +172,11 @@ function createTreeStore<T extends Record<string, unknown>>(}// eslint-disable-next-line @typescript-eslint/no-explicit-any-const TreeStoreContext = createContext<TreeStore<any> | null>(null);+const TreeStoreContext = createSharedContext<TreeStore<any> | null>(+ 'TreeStoreContext',+ 1,+ null,+);TreeStoreContext.displayName = 'TreeStoreContext';/** Indent token -> index, for the primitive row snapshot. */diff --git a/packages/core/src/Text/textClampContext.ts b/packages/core/src/Text/textClampContext.tsindex 9b4522a324..8358bc197f 100644--- a/packages/core/src/Text/textClampContext.ts+++ b/packages/core/src/Text/textClampContext.ts@@ -14,4 +14,8 @@import {createLayerScopedContext} from '../Layer/layerScopedContext';-export const TextClampContext = createLayerScopedContext(false);+export const TextClampContext = createLayerScopedContext(+ 'TextClampContext',+ 1,+ false,+);diff --git a/packages/core/src/ToggleButton/ToggleButtonGroup.tsx b/packages/core/src/ToggleButton/ToggleButtonGroup.tsxindex bcd9f264c2..a0518bd8e7 100644--- a/packages/core/src/ToggleButton/ToggleButtonGroup.tsx+++ b/packages/core/src/ToggleButton/ToggleButtonGroup.tsx@@ -19,7 +19,7 @@*/import {useCallback, use, useMemo, type ReactNode} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';import * as stylex from '@stylexjs/stylex';import {spacingVars} from '../theme/tokens.stylex';import type {ButtonSize} from '../Button';@@ -44,7 +44,11 @@ interface ToggleButtonGroupContextValue {}const ToggleButtonGroupContext =- createContext<ToggleButtonGroupContextValue | null>(null);+ createLayerScopedContext<ToggleButtonGroupContextValue | null>(+ 'ToggleButtonGroupContext',+ 1,+ null,+ );ToggleButtonGroupContext.displayName = 'ToggleButtonGroupContext';/**diff --git a/packages/core/src/Token/TokenNamingContext.ts b/packages/core/src/Token/TokenNamingContext.tsindex 07b68e6e42..47da75f77e 100644--- a/packages/core/src/Token/TokenNamingContext.ts+++ b/packages/core/src/Token/TokenNamingContext.ts@@ -9,7 +9,7 @@* @position Internal to Core; not exported from the Token entry point*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** Names for a Token whose visible text runs past its label. PowerSearch@@ -24,5 +24,9 @@ export interface TokenNaming {removeName?: string;}-export const TokenNamingContext = createContext<TokenNaming | null>(null);+export const TokenNamingContext = createSharedContext<TokenNaming | null>(+ 'TokenNamingContext',+ 1,+ null,+);TokenNamingContext.displayName = 'TokenNamingContext';diff --git a/packages/core/src/Tokenizer/TokenizerClearAllMessageContext.ts b/packages/core/src/Tokenizer/TokenizerClearAllMessageContext.tsindex 19eaed8dd0..d5f6e44bab 100644--- a/packages/core/src/Tokenizer/TokenizerClearAllMessageContext.ts+++ b/packages/core/src/Tokenizer/TokenizerClearAllMessageContext.ts@@ -13,9 +13,9 @@* words (component:Tokenizer AR7).*/-import {createContext} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const TokenizerClearAllMessageContext = createContext<string | null>(- null,-);+export const TokenizerClearAllMessageContext = createSharedContext<+ string | null+>('TokenizerClearAllMessageContext', 1, null);TokenizerClearAllMessageContext.displayName = 'TokenizerClearAllMessageContext';diff --git a/packages/core/src/Tokenizer/TokenizerItemRemovableContext.ts b/packages/core/src/Tokenizer/TokenizerItemRemovableContext.tsindex 2e3ee9e3e1..2b35d6ed77 100644--- a/packages/core/src/Tokenizer/TokenizerItemRemovableContext.ts+++ b/packages/core/src/Tokenizer/TokenizerItemRemovableContext.ts@@ -15,10 +15,10 @@* while a removable token remains. Without it, every token is removable.*/-import {createContext} from 'react';import type {SearchableItem} from '../Typeahead/types';+import {createSharedContext} from '../utils/sharedContext';-export const TokenizerItemRemovableContext = createContext<+export const TokenizerItemRemovableContext = createSharedContext<((item: SearchableItem) => boolean) | null->(null);+>('TokenizerItemRemovableContext', 1, null);TokenizerItemRemovableContext.displayName = 'TokenizerItemRemovableContext';diff --git a/packages/core/src/Tooltip/tooltipPresentInterest.ts b/packages/core/src/Tooltip/tooltipPresentInterest.tsindex 3afa9eb996..e694461323 100644--- a/packages/core/src/Tooltip/tooltipPresentInterest.ts+++ b/packages/core/src/Tooltip/tooltipPresentInterest.ts@@ -4,7 +4,7 @@/*** @file tooltipPresentInterest.ts- * @input React createContext+ * @input createSharedContext* @output Exports `TooltipPresentInterestContext` and its value types: the* interaction on a tooltip's anchor that mounted the tooltip* @position Internal to Core, not exported from the Tooltip entry. A@@ -13,7 +13,8 @@* its trigger attaches, as its own listeners would have.*/-import {createContext, type RefObject} from 'react';+import type {RefObject} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** The interaction on the anchor that mounted the tooltip: a hover from a@@ -34,5 +35,9 @@ export interface TooltipPresentInterestState {}export const TooltipPresentInterestContext =- createContext<RefObject<TooltipPresentInterestState> | null>(null);+ createSharedContext<RefObject<TooltipPresentInterestState> | null>(+ 'TooltipPresentInterestContext',+ 1,+ null,+ );TooltipPresentInterestContext.displayName = 'TooltipPresentInterestContext';diff --git a/packages/core/src/TopNav/TopNavContext.ts b/packages/core/src/TopNav/TopNavContext.tsindex 7ebe3099c6..56d1979e3e 100644--- a/packages/core/src/TopNav/TopNavContext.ts+++ b/packages/core/src/TopNav/TopNavContext.ts@@ -10,11 +10,15 @@*/import {use} from 'react';-import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext';+import {createLayerScopedContext} from '../Layer/layerScopedContext';export type TopNavSlot = 'start' | 'center' | 'end';-export const TopNavSlotContext = createContext<TopNavSlot>('start');+export const TopNavSlotContext = createLayerScopedContext<TopNavSlot>(+ 'TopNavSlotContext',+ 1,+ 'start',+);TopNavSlotContext.displayName = 'TopNavSlotContext';export function useTopNavSlot(): TopNavSlot {diff --git a/packages/core/src/TopNav/TopNavMobileContentContext.ts b/packages/core/src/TopNav/TopNavMobileContentContext.tsindex 9aa352d419..137b92bac0 100644--- a/packages/core/src/TopNav/TopNavMobileContentContext.ts+++ b/packages/core/src/TopNav/TopNavMobileContentContext.ts@@ -4,7 +4,7 @@/*** @file TopNavMobileContentContext.ts- * @input React createContext, use+ * @input createSharedContext, use* @output Exports TopNavMobileContentContext and useTopNavMobileContent* @position Internal context for passing additional drawer content to TopNav*@@ -13,9 +13,14 @@* mobile drawer, producing a single combined drawer.*/-import {createContext, use, type ReactNode} from 'react';+import {use, type ReactNode} from 'react';+import {createSharedContext} from '../utils/sharedContext';-export const TopNavMobileContentContext = createContext<ReactNode>(null);+export const TopNavMobileContentContext = createSharedContext<ReactNode>(+ 'TopNavMobileContentContext',+ 1,+ null,+);TopNavMobileContentContext.displayName = 'TopNavMobileContentContext';/**diff --git a/packages/core/src/TopNav/TopNavRenderContext.ts b/packages/core/src/TopNav/TopNavRenderContext.tsindex 765daee8be..810bff33ec 100644--- a/packages/core/src/TopNav/TopNavRenderContext.ts+++ b/packages/core/src/TopNav/TopNavRenderContext.ts@@ -4,7 +4,7 @@/*** @file TopNavRenderContext.ts- * @input React createContext, use+ * @input createSharedContext, use* @output Exports TopNavRenderContext and useTopNavRenderMode hook* @position Internal context for controlling TopNav rendering mode*@@ -15,12 +15,16 @@* - 'drawer': nav items as vertical list elements (mobile drawer)*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export type TopNavRenderMode = 'default' | 'mobile-bar' | 'drawer';-export const TopNavRenderContext =- createContext<TopNavRenderMode>('default');+export const TopNavRenderContext = createSharedContext<TopNavRenderMode>(+ 'TopNavRenderContext',+ 1,+ 'default',+);TopNavRenderContext.displayName = 'TopNavRenderContext';/**diff --git a/packages/core/src/Typeahead/busyIndicatorLane.tsx b/packages/core/src/Typeahead/busyIndicatorLane.tsxindex 231b7514d4..54fae1b8c7 100644--- a/packages/core/src/Typeahead/busyIndicatorLane.tsx+++ b/packages/core/src/Typeahead/busyIndicatorLane.tsx@@ -9,7 +9,8 @@* @position Package-internal; not exported from the package entry point*/-import {createContext, use, useSyncExternalStore} from 'react';+import {use, useSyncExternalStore} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** How the base hands its busy state to a wrapper that owns the inline-end lane.@@ -92,7 +93,11 @@ export function useIsBusy(lane: BusyIndicatorLane): boolean {return useSyncExternalStore(lane.subscribe, lane.getIsBusy, lane.getIsBusy);}-const BusyIndicatorLaneContext = createContext<BusyIndicatorLane | null>(null);+const BusyIndicatorLaneContext = createSharedContext<BusyIndicatorLane | null>(+ 'BusyIndicatorLaneContext',+ 1,+ null,+);BusyIndicatorLaneContext.displayName = 'BusyIndicatorLaneContext';export const BusyIndicatorLaneProvider = BusyIndicatorLaneContext.Provider;diff --git a/packages/core/src/Typeahead/committedChoicesKey.tsx b/packages/core/src/Typeahead/committedChoicesKey.tsxindex ffc3b11bd2..32486e4d09 100644--- a/packages/core/src/Typeahead/committedChoicesKey.tsx+++ b/packages/core/src/Typeahead/committedChoicesKey.tsx@@ -15,7 +15,8 @@* render does not change the key and reloads nothing.*/-import {createContext, use} from 'react';+import {use} from 'react';+import {createSharedContext} from '../utils/sharedContext';export type CommittedChoices = {/** Changes exactly when the committed values change. */@@ -26,9 +27,9 @@ export type CommittedChoices = {isAtLimit: boolean;};-export const CommittedChoicesKeyContext = createContext<+export const CommittedChoicesKeyContext = createSharedContext<CommittedChoices | undefined->(undefined);+>('CommittedChoicesKeyContext', 1, undefined);CommittedChoicesKeyContext.displayName = 'CommittedChoicesKeyContext';/** The caller's committed values, if a caller provides them. */diff --git a/packages/core/src/Typeahead/trailingKeyDown.tsx b/packages/core/src/Typeahead/trailingKeyDown.tsxindex 485f485e53..396e5c734e 100644--- a/packages/core/src/Typeahead/trailingKeyDown.tsx+++ b/packages/core/src/Typeahead/trailingKeyDown.tsx@@ -13,12 +13,17 @@* navigation, selection, or token editing (family:input-fields FR10).*/-import {createContext, use, type KeyboardEvent} from 'react';+import {use, type KeyboardEvent} from 'react';+import {createSharedContext} from '../utils/sharedContext';export type TrailingKeyDown =((event: KeyboardEvent<HTMLInputElement>) => void) | undefined;-export const TrailingKeyDownContext = createContext<TrailingKeyDown>(undefined);+export const TrailingKeyDownContext = createSharedContext<TrailingKeyDown>(+ 'TrailingKeyDownContext',+ 1,+ undefined,+);TrailingKeyDownContext.displayName = 'TrailingKeyDownContext';/** The consumer key handler BaseTypeahead runs after its own, if any. */diff --git a/packages/core/src/hooks/pressGroupContext.ts b/packages/core/src/hooks/pressGroupContext.tsindex b58d58c342..7da9fab15d 100644--- a/packages/core/src/hooks/pressGroupContext.ts+++ b/packages/core/src/hooks/pressGroupContext.ts@@ -26,5 +26,9 @@ export {pressGroupItemProps} from '../privateAttributes/pressGroupItem.stylex';* `:active` paint, so one press never lights two.*/export const PressGroupContext =- createLayerScopedContext<ReadonlyArray<string> | null>(null);+ createLayerScopedContext<ReadonlyArray<string> | null>(+ 'PressGroupContext',+ 1,+ null,+ );PressGroupContext.displayName = 'PressGroupContext';diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.tsindex f528e8e441..b67c7fdbf6 100644--- a/packages/core/src/hooks/useAnnounce.ts+++ b/packages/core/src/hooks/useAnnounce.ts@@ -15,7 +15,8 @@* - /packages/core/src/hooks/index.ts*/-import {createContext, use, useCallback, useRef, type RefObject} from 'react';+import {use, useCallback, useRef, type RefObject} from 'react';+import {createSharedContext} from '../utils/sharedContext';/*** Announcement urgency:@@ -358,9 +359,12 @@ export interface ModalAnnounceScope {parent: ModalAnnounceScope | null;}-export const ModalAnnounceContext = createContext<ModalAnnounceScope | null>(- null,-);+export const ModalAnnounceContext =+ createSharedContext<ModalAnnounceScope | null>(+ 'ModalAnnounceContext',+ 1,+ null,+ );ModalAnnounceContext.displayName = 'ModalAnnounceContext';/** The modal route `modalAnnounce.ts` installs when a provider loads it. */diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.tsindex 11a0650c2b..07f4997595 100644--- a/packages/core/src/i18n/InternationalizationContext.ts+++ b/packages/core/src/i18n/InternationalizationContext.ts@@ -4,7 +4,7 @@/*** @file InternationalizationContext.ts- * @input React createContext, i18n types+ * @input createSharedContext, i18n types* @output Exports InternationalizationContext and InternationalizationContextValue* @position Context definition for client-side locale + messages*@@ -22,10 +22,10 @@* - /packages/core/src/i18n/index.ts*/-import {createContext} from 'react';import {getResolve} from './resolve';import type {Locale, MessagesByLocale, Overrides} from './types';import type {CalendarSystem} from '../utils/calendarSystem';+import {createSharedContext} from '../utils/sharedContext';export interface InternationalizationContextValue {locale: Locale;@@ -45,10 +45,14 @@ export interface InternationalizationContextValue {* A consumer that doesn't render a provider still gets English defaults.*/export const InternationalizationContext =- createContext<InternationalizationContextValue>({- locale: 'en',- direction: 'ltr',- messages: {},- translate: getResolve('en', {}),- });+ createSharedContext<InternationalizationContextValue>(+ 'InternationalizationContext',+ 1,+ {+ locale: 'en',+ direction: 'ltr',+ messages: {},+ translate: getResolve('en', {}),+ },+ );InternationalizationContext.displayName = 'InternationalizationContext';diff --git a/packages/core/src/i18n/englishFallback.ts b/packages/core/src/i18n/englishFallback.tsindex 45620866bb..d80d02c7ba 100644--- a/packages/core/src/i18n/englishFallback.ts+++ b/packages/core/src/i18n/englishFallback.ts@@ -28,8 +28,14 @@*/import type {RuntimeCatalog} from './types';+import {realmValue, sharedKey} from '../utils/sharedRealm';-const registered: Record<string, string> = {};+// Every copy of Core registers into one map, so a context that one copy+// created resolves the English of another copy's components.+const registered = realmValue(+ sharedKey('i18n/english-fallback', 1),+ (): Record<string, string> => ({}),+);/** The English registered so far, keyed by catalog key. */export const englishFallback: RuntimeCatalog = registered;diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsxindex acd90c1fc5..96ddbe0620 100644--- a/packages/core/src/theme/Theme.tsx+++ b/packages/core/src/theme/Theme.tsx@@ -50,6 +50,7 @@ import {reducedMotionMarkProps,setRootReducedMotionMark,} from '../privateAttributes/reducedMotion.stylex';+import {createSharedContext} from '../utils/sharedContext';/*** Theme provider props@@ -101,7 +102,11 @@ const wrapperStyles = stylex.create({* @internal Not exported from the theme barrel; useToast imports it from* './theme/Theme' directly.*/-export const ThemeNestingContext = React.createContext(false);+export const ThemeNestingContext = createSharedContext(+ 'ThemeNestingContext',+ 1,+ false,+);ThemeNestingContext.displayName = 'ThemeNestingContext';// =============================================================================diff --git a/packages/core/src/theme/syntax/SyntaxTheme.tsx b/packages/core/src/theme/syntax/SyntaxTheme.tsxindex a7dd6751a8..a7faf365d3 100644--- a/packages/core/src/theme/syntax/SyntaxTheme.tsx+++ b/packages/core/src/theme/syntax/SyntaxTheme.tsx@@ -11,7 +11,7 @@* @see https://github.com/meta/astryx/issues/1148*/-import React, {createContext, use, useMemo} from 'react';+import React, {use, useMemo} from 'react';import {syntaxThemeStyle,resolveSyntaxTokenForMode,@@ -22,6 +22,7 @@ import {import {useMediaQuery} from '../../hooks/useMediaQuery';import {useTheme} from '../useTheme';import {formatColor, parseColor} from '../../utils/color';+import {createSharedContext} from '../../utils/sharedContext';// =============================================================================// Context@@ -32,7 +33,11 @@ interface SyntaxThemeContextValue {theme: SyntaxThemeDefinition;}-const SyntaxThemeContext = createContext<SyntaxThemeContextValue | null>(null);+const SyntaxThemeContext = createSharedContext<SyntaxThemeContextValue | null>(+ 'SyntaxThemeContext',+ 1,+ null,+);SyntaxThemeContext.displayName = 'SyntaxThemeContext';// =============================================================================diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.tsindex 3c3b58e8a3..4be88c513c 100644--- a/packages/core/src/theme/useTheme.ts+++ b/packages/core/src/theme/useTheme.ts@@ -23,19 +23,14 @@* - /packages/core/src/theme/index.ts*/-import {- createContext,- use,- useCallback,- useMemo,- useSyncExternalStore,-} from 'react';+import {use, useCallback, useMemo, useSyncExternalStore} from 'react';import type {ThemeMode} from './types';import type {DefinedTheme} from './defineTheme';import {resolveThemeTokens} from './tokens';import {getRegisteredTheme} from './themeRegistry';import {dataAttr} from '../naming';import {useMediaQuery} from '../hooks/useMediaQuery';+import {createSharedContext} from '../utils/sharedContext';// =============================================================================// Context@@ -57,7 +52,11 @@ export interface ThemeContextValue {* null when no provider is present.* @internal*/-export const ThemeContext = createContext<ThemeContextValue | null>(null);+export const ThemeContext = createSharedContext<ThemeContextValue | null>(+ 'ThemeContext',+ 1,+ null,+);ThemeContext.displayName = 'ThemeContext';// =============================================================================diff --git a/packages/core/src/utils/sharedContext.ts b/packages/core/src/utils/sharedContext.tsnew file mode 100644index 0000000000..05a786cd1a--- /dev/null+++ b/packages/core/src/utils/sharedContext.ts@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file sharedContext.ts+ * @input A registered name and its protocol version+ * @output A React context per key and React, shared by every copy of Core+ * that runs on that React+ * @position Shared runtime state: a swizzled copy and the package use the same+ * contexts and stores when their protocol versions match+ */++import {createContext, type Context} from 'react';+import {realmValue, sharedKey} from './sharedRealm';++/**+ * A React context registered under a versioned key, so a provider in one copy+ * of Core reaches consumers in another. Each React gets its own context under+ * the key: a server can load two Reacts, and a streaming render leaves context+ * values that only its own React restores, so requests on two Reacts must not+ * share a context.+ */+export function createSharedContext<T>(+ name: string,+ version: number,+ defaultValue: T,+): Context<T> {+ const byReact = realmValue(+ sharedKey(`context/${name}`, version),+ () => new WeakMap<typeof createContext, Context<unknown>>(),+ value => value instanceof WeakMap,+ );+ const existing = byReact.get(createContext);+ if (existing != null) {+ return existing as Context<T>;+ }+ const SharedContext = createContext(defaultValue);+ SharedContext.displayName = name;+ byReact.set(createContext, SharedContext as Context<unknown>);+ return SharedContext;+}diff --git a/packages/core/src/utils/sharedRealm.ts b/packages/core/src/utils/sharedRealm.tsnew file mode 100644index 0000000000..48fec3ea52--- /dev/null+++ b/packages/core/src/utils/sharedRealm.ts@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file sharedRealm.ts+ * @input A registered name and its protocol version+ * @output One value per key in the JavaScript realm, shared by every copy of+ * Core+ * @position Shared runtime state for stores and contexts; no React and no+ * client directive, so server-safe modules can use it+ */++/**+ * The registered key of a shared value. The version names the value's shape.+ * Change it when a copy built against the old shape cannot read the value.+ * Each copy then keeps its own value.+ */+export function sharedKey(name: string, version: number): symbol {+ return Symbol.for(`@astryxdesign/core/${name}/v${version}`);+}++/**+ * The value under `key` in this JavaScript realm, created on first use. Every+ * copy of Core that asks for the same key gets the same value.+ *+ * The key names the protocol version, so a value found under it has this+ * protocol's shape. `accepts` guards against a key collision: a value it+ * rejects is left in place, and this copy keeps a value of its own.+ */+export function realmValue<T>(+ key: symbol,+ create: () => T,+ accepts: (value: unknown) => boolean = () => true,+): T {+ const realm = globalThis as typeof globalThis & {[key: symbol]: unknown};+ if (Object.hasOwn(realm, key)) {+ const existing = realm[key];+ return accepts(existing) ? (existing as T) : create();+ }+ const value = create();+ realm[key] = value;+ return value;+}