feat(eslint-rules): add consistent-base-hook rule for v9 base hooks#36236
Draft
Hotell wants to merge 15 commits into
Draft
feat(eslint-rules): add consistent-base-hook rule for v9 base hooks#36236Hotell wants to merge 15 commits into
Hotell wants to merge 15 commits into
Conversation
📊 Bundle size report
Unchanged fixtures
|
|
Pull request demo site: URL |
| @@ -35,6 +35,7 @@ const __internal = { | |||
| /** @type {import('eslint').Linter.RulesRecord} */ | |||
There was a problem hiding this comment.
🕵🏾♀️ visual changes to review in the Visual Change Report
vr-tests-react-components/Charts-DonutChart 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/Charts-DonutChart.Dynamic.default.chromium.png | 5581 | Changed |
vr-tests-react-components/Menu Converged - submenuIndicator slotted content 2 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/Menu Converged - submenuIndicator slotted content.default.submenus open.chromium.png | 413 | Changed |
| vr-tests-react-components/Menu Converged - submenuIndicator slotted content.default - RTL.submenus open.chromium.png | 599 | Changed |
vr-tests-react-components/Positioning 2 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/Positioning.Positioning end.updated 2 times.chromium.png | 505 | Changed |
| vr-tests-react-components/Positioning.Positioning end.chromium.png | 839 | Changed |
vr-tests-react-components/ProgressBar converged 3 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/ProgressBar converged.Indeterminate + thickness - Dark Mode.default.chromium.png | 89 | Changed |
| vr-tests-react-components/ProgressBar converged.Indeterminate + thickness - High Contrast.default.chromium.png | 95 | Changed |
| vr-tests-react-components/ProgressBar converged.Indeterminate + thickness.default.chromium.png | 41 | Changed |
vr-tests-react-components/Skeleton converged 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/Skeleton converged.Opaque Skeleton with rectangle - Dark Mode.default.chromium.png | 9 | Changed |
vr-tests-react-components/TagPicker 3 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-react-components/TagPicker.disabled - Dark Mode.disabled input hover.chromium.png | 658 | Changed |
| vr-tests-react-components/TagPicker.disabled - High Contrast.disabled input hover.chromium.png | 1319 | Changed |
| vr-tests-react-components/TagPicker.disabled.chromium.png | 677 | Changed |
vr-tests-web-components/Badge 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-web-components/Badge. - Dark Mode.normal.chromium.png | 443 | Changed |
vr-tests-web-components/MenuList 3 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-web-components/MenuList. - RTL.1st selected.chromium_2.png | 39384 | Changed |
| vr-tests-web-components/MenuList. - RTL.normal.chromium_1.png | 39083 | Changed |
| vr-tests-web-components/MenuList. - RTL.2nd selected.chromium_3.png | 38816 | Changed |
vr-tests-web-components/RadioGroup 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests-web-components/RadioGroup. - Dark Mode.normal.chromium_1.png | 89 | Changed |
vr-tests/Callout 8 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/Callout.Right center.default.chromium.png | 2117 | Changed |
| vr-tests/Callout.Gap space 25.default.chromium.png | 2195 | Changed |
| vr-tests/Callout.Left bottom edge.default.chromium.png | 3182 | Changed |
| vr-tests/Callout.Right top edge.default.chromium.png | 1126 | Changed |
| vr-tests/Callout.No beak.default.chromium.png | 2192 | Changed |
| vr-tests/Callout.Root.default.chromium.png | 2195 | Changed |
| vr-tests/Callout.Top center.default.chromium.png | 2127 | Changed |
| vr-tests/Callout.Top auto edge.default.chromium.png | 2212 | Changed |
vr-tests/Keytip 2 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/Keytip.Disabled.default.chromium.png | 26 | Changed |
| vr-tests/Keytip.Root.default.chromium.png | 51 | Changed |
vr-tests/Pivot - Overflow 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/Pivot - Overflow.Tabs - RTL.chromium.png | 4471 | Changed |
vr-tests/react-charting-GaugeChart 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/react-charting-GaugeChart.Basic.default.chromium.png | 2 | Changed |
vr-tests/react-charting-LineChart 2 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/react-charting-LineChart.Multiple - Dark Mode.default.chromium.png | 181 | Changed |
| vr-tests/react-charting-LineChart.Multiple - RTL.default.chromium.png | 200 | Changed |
vr-tests/react-charting-VerticalBarChart 1 screenshots
| Image Name | Diff(in Pixels) | Image Type |
|---|---|---|
| vr-tests/react-charting-VerticalBarChart.Basic - Secondary Y Axis.default.chromium.png | 3 | Changed |
There were 3 duplicate changes discarded. Check the build logs for more information.
b31ff9c to
a849b63
Compare
Contributor
There was a problem hiding this comment.
Pull request overview
Adds a new workspace ESLint rule to enforce the v9 “base hook” contract (use<Name>Base_unstable) and wires it into the repo’s React lint override, including typed (TS Program-backed) transitive runtime-dependency detection.
Changes:
- Added
consistent-base-hookESLint rule with typed (transitive import graph) and untyped fallbacks, plus a fixture-based typed test suite. - Registered and enabled the rule in the workspace rules index and the
packages/eslint-plugininternal React override. - Added targeted suppressions for known legacy violations and adjusted lint tsconfig to exclude rule fixtures.
Reviewed changes
Copilot reviewed 19 out of 19 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tools/eslint-rules/tsconfig.lint.json | Excludes __fixtures__ from the eslint-rules TS lint project. |
| tools/eslint-rules/rules/consistent-callback-type.ts | Makes TSESTree a type-only import (no runtime change). |
| tools/eslint-rules/rules/consistent-base-hook.ts | Implements the new rule (param contract + forbidden runtime dependency detection, including typed transitive analysis + caching). |
| tools/eslint-rules/rules/consistent-base-hook.spec.ts | Adds RuleTester coverage for both untyped and typed (fixture-backed) paths. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/tsconfig.json | Fixture TS project for typed RuleTester cases (path-mapped stub packages). |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/watched-pkg/light.ts | Stub “watched” package module that stays clear of forbidden runtime. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/watched-pkg/index.ts | Stub watched package barrel (includes type-only re-exports). |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/watched-pkg/heavy.ts | Stub watched module that imports the forbidden runtime to trigger reach detection. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/light-helper/index.ts | Stub helper package used by the “light” watched module. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/heavy-runtime/index.ts | Stub forbidden runtime package for typed tests. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/cyclic-pkg/index.ts | Stub package with cyclic re-exports to validate cycle safety. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/cyclic-pkg/b.ts | Part of cyclic stub graph used by cycle-safety test. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/stubs/cyclic-pkg/a.ts | Part of cyclic stub graph used by cycle-safety test. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/src/test.ts | Placeholder file so typed RuleTester filenames exist in the fixture Program. |
| tools/eslint-rules/rules/fixtures/consistent-base-hook/src/dummy.ts | Additional placeholder fixture source file. |
| tools/eslint-rules/index.ts | Registers the new workspace rule export. |
| packages/react-components/react-tooltip/library/src/components/Tooltip/useTooltipBase.tsx | Adjusts the useTooltipBase_unstable “use no memo” directive statement. |
| packages/react-components/react-tags/library/src/components/TagGroup/useTagGroup.ts | Adds scoped suppressions for legacy tabster usage inside a base hook. |
| packages/eslint-plugin/src/internal.js | Enables @nx/workspace-consistent-base-hook under the internal React override. |
Enforces the v9 base hook API contract for any function matching
`use<Name>Base_unstable`:
- 1 or 2 positional parameters; first must be named `props`,
optional second must be named `ref` and typed as `React.Ref<...>`.
- No references to bindings imported from configured forbidden
packages (defaults to `@fluentui/react-tabster`, `tabster`,
`keyborg`). Forbidden-package detection is scope-based, so
local shadowing is handled correctly.
Options:
{ forbiddenPackages?: Array<string | { name: string; allow?: string[] }> }
…legacy base hooks Pre-existing base hooks that don't yet conform to the new contract (missing/non-React.Ref-typed `ref` param, or references to tabster/keyborg bindings) are suppressed with line-scoped `eslint-disable-next-line` comments so the rule can ship as `error` for new code. Refactors to remove the suppressions will follow. Affected packages: - react-checkbox, react-menu, react-radio, react-rating, react-slider, react-switch, react-tags, react-tooltip
…e-hook `useFocusWithin` from `@fluentui/react-tabster` is a pure ref-attaching utility with no global side effects; it's safe to use inside base hooks. Added to the default allowlist so callers don't need to opt-out per-site.
…essions `useFocusWithin` is now part of the rule's default allowlist, so the line-scoped suppressions in react-checkbox, react-radio, react-rating, react-slider, and react-switch are no longer needed.
…se-hook Same rationale as `useFocusWithin`: `useFocusVisible` from `@fluentui/react-tabster` is safe to use inside base hooks.
…yborg from forbidden list
- Remove `keyborg` from the default forbidden packages list. Base hooks
may freely depend on `keyborg` since it carries no tabster runtime.
- Expand the default allowlist for `@fluentui/react-tabster` with APIs
that internally depend only on `keyborg` (no `tabster` runtime):
- useKeyboardNavAttribute
- useIsNavigatingWithKeyboard
- useSetKeyboardNavigation
- useOnKeyboardNavigationChange
- applyFocusVisiblePolyfill
- KEYBORG_FOCUSIN / KeyborgFocusInEvent (re-exports from `keyborg`)
…ions `useIsNavigatingWithKeyboard`, `KEYBORG_FOCUSIN`, and `KeyborgFocusInEvent` are now part of the rule's default allowlist.
… in consistent-base-hook
Replace the hand-curated allow/forbidden package lists with per-symbol transitive value-import analysis powered by typescript-eslint ParserServices and the TypeScript Program. The rule now traces each base-hook import back to its defining source file and walks non-type-only re-exports/imports to detect whether the symbol's module graph reaches any configured forbidden runtime package.
Options shape: { watchedPackages?: string[]; forbiddenRuntimes?: string[] }. Defaults: watchedPackages=['@fluentui/react-tabster'], forbiddenRuntimes=['tabster']. New message ids: forbiddenRuntimeDirect, forbiddenRuntimeReach. Type-only imports are skipped. When typed services are unavailable, only direct forbidden-runtime imports are reported.
By default (allowTypeImports: false) type-only imports from forbiddenRuntimes packages are disallowed inside base hooks, to keep the base hook's public API fully decoupled from those packages. Setting allowTypeImports: true restores the previous behavior of skipping type-only imports. Type-only imports from watched packages are unaffected (types cannot transitively pull runtime).
…nore fixtures from type check
…; fix tooltip directive - isReactRefTypeAnnotation now resolves the Ref/React identifier via scope analysis and requires it to be imported from 'react'. Adds tests for local aliases, non-react imports, and shadowed React.- useTooltipBase_unstable: use bare 'use no memo' directive prologue instead of parenthesized expression so React Compiler detects it.
…onsistent-base-hook
Extend the rule's transitive analysis so type references in a base hook
signature are also checked against forbidden runtimes when they originate
from a watched package whose defining module reaches a forbidden runtime
(via either value or type imports).
- Track type-only imports from watched packages (previously skipped).
- Per-Program cache now stores { value, all } reach sets, filled in a
single DFS pass so the new analysis adds no extra resolution work.
- visitScope picks the reach set based on reference.isTypeReference:
value refs use value reach (runtime coupling), type refs use all
reach (API-surface coupling).
- allowTypeImports is now symmetric: when true, type-only imports are
exempt from BOTH direct forbidden checks AND transitive watched
reach checks.
- New tests cover symmetric exemption, type-only watched -> clean
module (allowed), and indirect type leakage via HeavyWrapper whose
defining file value-re-exports the heavy module.
1429791 to
1084d65
Compare
…k signature detection Wrapping state hooks (`use<X>_unstable`) that pair with a base hook (`use<X>Base_unstable`) must also follow the `(props, ref)` signature contract. Pair detection checks the same file first, then sibling files (`.ts`/`.tsx`) in the same directory. Suppress the violation on `useTagGroupBase_unstable`, which takes a third `options` argument used internally by `useTagGroup_unstable`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Summary
Adds a new workspace ESLint rule —
@nx/workspace-consistent-base-hook— that enforces the v9 "base hook" API contract for any function whose name matchesuse<Name>Base_unstable, and extends the signature contract to the paired wrapping state hookuse<Name>_unstablevia pair detection.The rule encodes architectural rules we currently rely on tribal knowledge / PR review to enforce, namely:
use<Name>_unstablehook) can compose them mechanically.tabsterby default). That responsibility belongs to the wrapping hook.Detection of (3) is fully automatic and covers two threat models:
Detection works without a hand-curated allow/deny list: each imported symbol is resolved to its defining source file via typescript-eslint
ParserServices+ the TSProgram, then the module's import graph is walked and the appropriate reach set (value-only vs value+type) is consulted. Results are memoized perts.Program× file with cycle protection.Rule contract
For any function matching
/^use[A-Z]\w*Base_unstable$/OR any wrapping state hookuse<Name>_unstablewhose paired base hook (use<Name>Base_unstable) exists in the same file or as a sibling file (.ts/.tsx) in the same directory:Identifiernamedprops.Identifiernamedref, typed asReact.Ref<...>(orRef<...>imported fromreact).For base hooks only (additional body/signature check):
forbiddenRuntimespackage or transitively pulls one through awatchedPackagespackage.Detection is scope-based (via
sourceCode.getDeclaredVariables), so a locally-declared identifier that happens to share a name with a forbidden import is not flagged.Pair detection (state hook coverage)
Across all 85
useXBase_unstabledeclarations inpackages/react-components/**:react-tooltip(useTooltipBase.tsx↔useTooltip.tsx),react-field(useFieldBase.tsx↔useField.tsx),react-menu/MenuItem(useMenuItemBase.tsx↔useMenuItem.tsx).The pair lookup checks same-file first (zero IO), then falls back to
fs.statSynconuseX.ts/useX.tsxinpath.dirname(filename)with per-rule-instance caching. Wrapping hooks that exist without a base hook (e.g.,useTabListContextValues_unstable,useFooStyles_unstable) are not flagged — pair detection is strictly anchored onBASE_HOOK_NAME_PATTERN, eliminating false positives on other_unstablehooks.Options
Defaults:
{ watchedPackages: ['@fluentui/react-tabster'], forbiddenRuntimes: ['tabster'], allowTypeImports: false }.Message ids
invalidParamCountinvalidParamNameprops, or param 2 is not Identifierref(fires for base hooks and paired state hooks)invalidRefTyperefis present but missing a type annotation or not typed asReact.Ref<...>(fires for base hooks and paired state hooks)forbiddenRuntimeDirectforbiddenRuntimespackage (including type-only imports whenallowTypeImports: false)forbiddenRuntimeReachwatchedPackagespackage whose defining module transitively imports aforbiddenRuntimespackage; the failing path is reported viaviaFile. Fires for value references (value-import graph) and for type references (value + type-import graph)typedServicesUnavailableProgram:exit: a watched-package reference was encountered but transitive analysis was skipped because TypeScript type information was unavailableAll reports point at the function identifier (or the failing reference), so a single
eslint-disable-next-lineabove the export line suppresses cleanly.Untyped fallback
If typed services are unavailable, the rule degrades gracefully — it still catches direct imports from
forbiddenRuntimesvia plain scope analysis, skips the transitive walk for watched-package references, and emits a singletypedServicesUnavailablediagnostic per file so the misconfiguration is visible rather than silent.Wiring
Enabled as
errorinpackages/eslint-plugin/src/internal.jsunder the React override, scoped to v9 source files (excludes*.test.*,*.spec.*,*.cy.*,*.stories.*). The hostingflat/reactpreset enablesparserOptions.projectService: true, so the typed Program-backed analysis runs in production.Test coverage
tools/eslint-rules/rules/consistent-base-hook.spec.ts— 75 cases, split into two RuleTester instances:Ref<>import,React.Ref<>namespace, non-base hook unaffected, shadowing handled,keyborgallowed by default, same-file paired correct signature, sibling-file paired correct signature, orphan…ContextValues_unstablenot flagged; invalid 0/3 params, wrong names, ObjectPatternprops, missing/non-React.Refref type,React.ForwardedRef, same-file pair state hook with 3 params, sibling-file pair state hook with wrong param names, and thetypedServicesUnavailableone-shot warning.tools/eslint-rules/rules/__fixtures__/consistent-base-hook/withwatched-pkg,heavy-runtime,light-helper,cyclic-pkg. Covers:runHeavy, aliasedrunHeavy as go);useHeavy) flagged withviaFile;useLight) allowed;HeavyOptions) flagged by default;HeavyType, both top-level and per-specifiertype) flagged withviaFile;HeavyWrapperwhose defining file (watched-pkg/index.ts) value-re-exports./heavy—viaFilecorrectly points atindex.ts;LightOptions) allowed;allowTypeImports: trueexempts both direct forbidden type imports AND transitive watched type imports;Verification
yarn nx run eslint-rules:test --testPathPatterns=consistent-base-hook→ 75/75 pass.yarn nx run-many -t lint --projects=tag:vNext --skip-nx-cache→ 165/165 projects pass, zeroconsistent-base-hookerrors.Performance (per-rule,
TIMING=allESLint CLI)Cold runs (
--skip-nx-cache), measured viaTIMING=all nx run <pkg>:lint. Even with the new value+type transitive analysis the rule stays at low single-digit milliseconds per package because:WeakMap<ts.Program, Map<file, { value, all }>>cache fills both reach sets in a single DFS pass, amortizing across all files in a lint run;allowTypeImports: true, so the analysis pays zero cost when irrelevant;fs.statSyncresults per rule instance, so each component directory pays at most one syscall per linted run.consistent-base-hooktimereact-buttonreact-tabsterreact-checkboxreact-sliderreact-menureact-ratingreact-tagsFor context on
react-menu: top rule cost is@typescript-eslint/no-deprecatedat 2076 ms (54.8%) andreact-hooks/static-componentsat 802 ms (21.2%).consistent-base-hookis roughly ~1000× cheaper thanno-deprecatedand ~400× cheaper thanstatic-components.Pre-existing violators
A handful of legacy base hooks across
react-checkbox,react-menu(useMenuTrigger),react-radio,react-rating,react-slider,react-switch,react-tagsdon't yet conform (mostly: untyped/non-React.Refrefparam, or directtabsterruntime usage viauseFocusFinders/useArrowNavigationGroupetc.). These are suppressed with line-scopedeslint-disable-next-linecomments so the rule can ship aserrorfor new code. Follow-up refactors will remove the suppressions one package at a time.useTooltipBase,useMenuBase, anduseAvatarGroupPopoverBase(1-param hooks) are valid under the relaxed contract and required no suppression.The pair-detection extension surfaced exactly one new violation:
useTagGroupBase_unstableaccepts a 3rdoptionsargument used internally byuseTagGroup_unstable. Suppressed inline with explanation.Commits (kept decoupled)
feat(eslint-rules): add consistent-base-hook rule— initial rule + spec + registrationchore(eslint-plugin): enable consistent-base-hook for v9 sources— plugin wiringfeat(eslint-rules): auto-detect forbidden runtime deps via TS Program in consistent-base-hook— replaces the hand-curated allowlist with per-symbol transitive value-import analysis powered by typescript-eslintParserServices+ TSProgramfeat(eslint-rules): add allowTypeImports option to consistent-base-hook— type-only imports fromforbiddenRuntimespackages are disallowed by default, opt-in to skip themfeat(eslint-rules): detect type-leakage through watched packages in consistent-base-hook— extends transitive analysis to type references in the hook signature; symmetricallowTypeImportssemantics; newtypedServicesUnavailableone-shot diagnostic when typed services are missingfeat(eslint-rules): extend consistent-base-hook with paired state hook signature detection—(props, ref)contract is now enforced on wrappinguse<Name>_unstablehooks when a paired base hook exists in the same file or as a sibling.ts/.tsxfile in the same directoryFollow-ups (not in this PR)
base-hook-signature(signature + pair detection) andbase-hook-no-forbidden-runtime(transitive analysis) — with the transitive-reach / module-resolver / tracked-imports helpers extracted as reusable utilities.use<Name>_unstablehook), then drop the suppressions.