Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 26, 2025

Description

<PricingTable/> is one of the few components that accepts the fallback prop and that its initial data are loaded asynchronously after clerk.js has loaded. We need to wait for that plans to be resolved and only then swap the fallback with the content.

⚠️ One disadvantage of this fix is that if your app is on an new @clerk/clerk-react version with an older clerk-js version (probably pinned) the component that you pass in the fallback prop will be visible indefinitely.

Before

Screen.Recording.2025-08-27.at.12.04.27.AM.mov

After

Screen.Recording.2025-08-27.at.12.03.17.AM.mov

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Pricing Table now reliably waits for pricing data/readiness before hiding its fallback, preventing premature hiding and ensuring correct rendering for both signed-in and signed-out users.
    • Improved component mount readiness handling to reduce intermittent rendering issues.
  • Chores

    • Prepared patch releases for the JavaScript and React packages.

@panteliselef panteliselef self-assigned this Aug 26, 2025
Copy link

changeset-bot bot commented Aug 26, 2025

🦋 Changeset detected

Latest commit: 943da66

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 9 packages
Name Type
@clerk/clerk-js Patch
@clerk/clerk-react Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/elements Patch
@clerk/nextjs Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Aug 26, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 2, 2025 3:49pm

Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds a readiness signal for PricingTable rendering: Flow.Root and InvisibleRootBox accept/propagate an isFlowReady flag and set a data-component-status attribute; the mount waiter now observes that attribute via a selector; includes a changeset for patch releases.

Changes

Cohort / File(s) Summary of Changes
Release metadata
\.changeset/floppy-glasses-share.md
Adds a changeset declaring patch bumps for @clerk/clerk-js and @clerk/clerk-react with release-note: "Wait for pricing table data to be ready before hiding its fallback."
PricingTable readiness prop
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
Passes isFlowReady into Flow.Root: isFlowReady={clerk.isSignedIn ? !!subscription : plans.length > 0} so readiness reflects subscription (signed-in) or available plans (signed-out).
Flow root prop widening
packages/clerk-js/src/ui/customizables/Flow.tsx
Widened Flow Root props to accept optional isFlowReady?: boolean and forwards it via {...props}.
Invisible root element updates
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
_InvisibleRootBox now accepts isFlowReady?: boolean; uses setAttribute('class', ...) and adds data-component-status ('ready' vs 'awaiting-data'); includes isFlowReady in effect deps and refactors span ref callback.
Flow metadata provider change
packages/clerk-js/src/ui/elements/contexts/index.tsx
Provider now passes a shallow-cloned value: { ...props } to FlowMetadataCtx.Provider instead of the raw props object.
Mount/wait utilities refactor
packages/react/src/utils/useWaitForComponentMount.ts
Introduces createAwaitableMutationObserver, refactors waitForElementChildren to use an isReady predicate, configurable observer options, initial readiness check, and timeout support. useWaitForComponentMount gains options?: { selector: string } and returns `'rendering'
PricingTable mount gating in React UI
packages/react/src/components/uiComponents.tsx
PricingTable now calls useWaitForComponentMount(component, { selector: '[data-component-status="ready"]' }) to wait for the readiness attribute before treating the component as mounted; mounting gating still depends on mountingStatus and clerk.loaded.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as App UI
  participant PT as PricingTable
  participant FlowRoot as Flow.Root
  participant IRB as InvisibleRootBox
  participant Hook as useWaitForComponentMount
  participant DOM as DOM

  App->>PT: render PricingTable
  PT->>PT: compute isFlowReady = clerk.isSignedIn ? !!subscription : plans.length > 0
  PT->>FlowRoot: render with isFlowReady
  FlowRoot->>IRB: render InvisibleRootBox (receives isFlowReady)
  IRB->>DOM: setAttribute('class', ...)
  IRB->>DOM: setAttribute('data-component-status', 'ready' or 'awaiting-data')

  App->>Hook: waitForComponentMount(selector='[data-component-status="ready"]')
  Hook->>DOM: observe mutations / initial check
  alt selector matches
    Hook-->>App: 'rendered'
  else timeout/error
    Hook-->>App: 'error'
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I nudge a span with whiskered care,
A status set — "awaiting" to "ready" there.
Observers blink and context holds the root,
Plans arrive, the fallback lifts—then hoot! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1212-fix-cls-when-pricingtable-fallback

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

pkg-pr-new bot commented Aug 26, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6644

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6644

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6644

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6644

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6644

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6644

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6644

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6644

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6644

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6644

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6644

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6644

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6644

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6644

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6644

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6644

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6644

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6644

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6644

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6644

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6644

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6644

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6644

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6644

commit: 943da66

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)

74-92: Prevent setState on unmounted and reset watcher when component changes

If the component using this hook unmounts before the promise resolves, setStatus may still run. Also, when the component param changes, watcherRef should reset to create a new watcher.

   useEffect(() => {
+    let isMounted = true;
+    watcherRef.current = undefined;
     if (!component) {
       throw new Error('Clerk: no component name provided, unable to detect mount.');
     }
 
     if (typeof window !== 'undefined' && !watcherRef.current) {
       const selector = `[data-clerk-component="${component}"]`;
       const needsReadyAttribute = component === 'PricingTable';
       watcherRef.current = waitForElementChildren({
         selector,
         check: needsReadyAttribute ? el => el?.getAttribute('data-ready') === 'true' : undefined,
       })
-        .then(() => {
-          setStatus('rendered');
-        })
-        .catch(() => {
-          setStatus('error');
-        });
+        .then(() => {
+          if (isMounted) setStatus('rendered');
+        })
+        .catch(() => {
+          if (isMounted) setStatus('error');
+        });
     }
-  }, [component]);
+    return () => {
+      isMounted = false;
+      watcherRef.current = undefined;
+    };
+  }, [component]);
🧹 Nitpick comments (5)
.changeset/floppy-glasses-share.md (1)

1-6: Changeset looks correct and scoped to patch releases

Packages and note align with the implementation goal to avoid CLS by waiting for data readiness. Consider making the note slightly more explicit for consumers: “PricingTable now hides fallback only after data-ready is signaled to prevent CLS.”

Apply this minimal tweak:

-Wait for pricing table data to be ready before hiding its fallback.
+PricingTable: wait for data readiness (data-ready="true") before hiding fallback to prevent CLS.
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)

137-141: Memo deps and payload scope

  • setRootElement is stable; including it in deps is unnecessary. Use flow, part, rootElement.
  • Avoid spreading props directly to the context value, as it also carries children. Spread only the fields you intend to expose (flow, part) to prevent accidental context bloat.

Apply:

-  const value = React.useMemo(
-    () => ({ value: { ...props, rootElement, setRootElement } }),
-    [flow, part, rootElement, setRootElement],
-  );
+  const value = React.useMemo(
+    () => ({ value: { flow, part, rootElement, setRootElement } }),
+    [flow, part, rootElement],
+  );

100-104: Duplicate union member 'subscriptionDetails'

Union type lists 'subscriptionDetails' twice. Remove the duplicate to keep the type clean.

-    | 'subscriptionDetails'
-    | 'subscriptionDetails'
+    | 'subscriptionDetails'
packages/react/src/utils/useWaitForComponentMount.ts (1)

41-47: Reduce observer cost: retarget to the actual element and filter observed attributes

Currently observing the entire root subtree for all attributes can be noisy. Once the target element is found, switch the observer to that element and use attributeFilter when check is provided (e.g., data-ready).

-    const observer = new MutationObserver(mutationsList => {
+    const observer = new MutationObserver(mutationsList => {
       for (const mutation of mutationsList) {
-        if (!elementToWatch && selector) {
-          elementToWatch = root?.querySelector(selector);
-        }
+        if (!elementToWatch && selector) {
+          const el = root?.querySelector(selector);
+          if (el) {
+            elementToWatch = el as HTMLElement;
+            // Re-target to the specific element to cut noise.
+            observer.disconnect();
+            observer.observe(elementToWatch, {
+              childList: true,
+              attributes: true,
+              subtree: false,
+              attributeFilter: typeof check === 'function' ? ['data-ready'] : undefined,
+            });
+          }
+        }
 
-        if (mutation.type === 'childList' || mutation.type === 'attributes') {
+        if (mutation.type === 'childList' || mutation.type === 'attributes') {
           if (isReady(elementToWatch)) {
             observer.disconnect();
             resolve();
             return;
           }
         }
       }
     });
 
-    observer.observe(root, { childList: true, attributes: true, subtree: true });
+    observer.observe(root, { childList: true, attributes: true, subtree: true });

Also applies to: 55-55

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (1)

18-27: Optional: remove readiness flag when not ready

Not strictly required, but if UI states can toggle, consider removing the attribute when not ready to keep contract clear.

-    if (isReady) {
-      rootElement?.setAttribute('data-ready', 'true');
-    }
+    if (!rootElement) return;
+    if (isReady) {
+      rootElement.setAttribute('data-ready', 'true');
+    } else {
+      rootElement.removeAttribute('data-ready');
+    }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f871573 and f4d6cc4.

📒 Files selected for processing (5)
  • .changeset/floppy-glasses-share.md (1 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/contexts/index.tsx (1 hunks)
  • packages/react/src/utils/useWaitForComponentMount.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/floppy-glasses-share.md
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (4)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (2)
  • useSubscription (63-78)
  • usePlans (80-90)
packages/shared/src/react/hooks/useSubscription.tsx (1)
  • useSubscription (32-65)
packages/shared/src/react/hooks/usePlans.tsx (1)
  • usePlans (9-22)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
  • useFlowMetadata (162-162)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)

128-134: FlowMetadata context usage verified – all call sites updated

All occurrences of useFlowMetadata in the repo compile and type-check against the extended shape. Call sites either consume the new rootElement/setRootElement properties or continue to use existing fields without error:

• packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (line 10):
Destructures setRootElement from useFlowMetadata()

• packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (line 16):
Destructures rootElement from useFlowMetadata()

• packages/clerk-js/src/ui/elements/Card/CardRoot.tsx (line 14):
Assigns entire flowMetadata object from useFlowMetadata()

• packages/clerk-js/src/ui/elements/Card/CardContent.tsx (line 22):
Assigns entire flowMetadata object from useFlowMetadata()

• packages/clerk-js/src/ui/customizables/Flow.tsx (line 30):
Destructures existing flow property from useFlowMetadata()

No other usages were found, and external packages won’t be impacted by the broader context shape.

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (1)

102-102: Placement of SyncRootElement is good

Rendering the readiness synchronizer immediately under Flow.Root ensures the root element exists early and avoids additional reflows. With the dependency fix above, this should reliably signal readiness.

Comment on lines 12 to 30
function SyncRootElement() {
const clerk = useClerk();
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription();
const { data: plans, isLoading: isPlansLoading } = usePlans();
const { rootElement } = useFlowMetadata();

useEffect(() => {
if (isSubscriptionLoading || isPlansLoading) {
return;
}
const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0;

if (isReady) {
rootElement?.setAttribute('data-ready', 'true');
}
}, [subscription, plans]);

return null;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

data-ready attribute may never be set due to missing rootElement in deps

If rootElement becomes available after the effect runs (likely, given it’s set via InvisibleRootBox), the effect won’t re-run and data-ready will never be set, keeping the fallback visible indefinitely. Also include clerk.isSignedIn and loading flags in deps.

Apply:

 function SyncRootElement() {
   const clerk = useClerk();
   const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription();
   const { data: plans, isLoading: isPlansLoading } = usePlans();
   const { rootElement } = useFlowMetadata();

   useEffect(() => {
-    if (isSubscriptionLoading || isPlansLoading) {
+    if (isSubscriptionLoading || isPlansLoading) {
       return;
     }
-    const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0;
+    const isReady = clerk.isSignedIn ? !!subscription : (plans?.length ?? 0) > 0;
 
     if (isReady) {
       rootElement?.setAttribute('data-ready', 'true');
     }
-  }, [subscription, plans]);
+  }, [rootElement, clerk.isSignedIn, isSubscriptionLoading, isPlansLoading, subscription, plans]);
 
   return null;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function SyncRootElement() {
const clerk = useClerk();
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription();
const { data: plans, isLoading: isPlansLoading } = usePlans();
const { rootElement } = useFlowMetadata();
useEffect(() => {
if (isSubscriptionLoading || isPlansLoading) {
return;
}
const isReady = clerk.isSignedIn ? !!subscription : plans.length > 0;
if (isReady) {
rootElement?.setAttribute('data-ready', 'true');
}
}, [subscription, plans]);
return null;
}
function SyncRootElement() {
const clerk = useClerk();
const { data: subscription, isLoading: isSubscriptionLoading } = useSubscription();
const { data: plans, isLoading: isPlansLoading } = usePlans();
const { rootElement } = useFlowMetadata();
useEffect(() => {
if (isSubscriptionLoading || isPlansLoading) {
return;
}
const isReady = clerk.isSignedIn
? !!subscription
: (plans?.length ?? 0) > 0;
if (isReady) {
rootElement?.setAttribute('data-ready', 'true');
}
}, [
rootElement,
clerk.isSignedIn,
isSubscriptionLoading,
isPlansLoading,
subscription,
plans,
]);
return null;
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx around
lines 12-30, the useEffect currently omits rootElement, clerk.isSignedIn,
isSubscriptionLoading and isPlansLoading from its dependency array so it may not
re-run when the rootElement becomes available or auth/loading state changes;
update the effect dependencies to include rootElement, clerk.isSignedIn,
isSubscriptionLoading and isPlansLoading (and keep subscription and plans),
ensure you guard rootElement with a null check before calling setAttribute, and
only set data-ready when isReady is true so the effect will re-run and correctly
set the attribute when rootElement appears or state changes.

@panteliselef panteliselef force-pushed the elef/bill-1212-fix-cls-when-pricingtable-fallback branch from b2ca731 to 31115ef Compare August 26, 2025 20:05
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/react/src/components/uiComponents.tsx (1)

580-585: PricingTable now waits for readiness via attribute selector — good, but ensure the observer watches attribute mutations

Passing { selector: '[data-ready="true"]' } is the right approach to avoid CLS by keeping the fallback visible until data is ready. However, the current waiter (waitForElementChildren) only observes childList mutations by default. If readiness is signaled solely by toggling data-ready (without child insertions), the hook may never transition to "rendered," leaving the fallback visible and the host element hidden.

Please update the waiter to observe attribute changes (see suggested diff in useWaitForComponentMount.ts). Without that, this change risks a permanent "rendering" state when only data-ready flips.

🧹 Nitpick comments (4)
packages/react/src/utils/useWaitForComponentMount.ts (4)

31-45: Tighten observer/timeout lifecycle to prevent leaks and double-settle attempts

  • Store the timeout id and clear it when resolving.
  • Disconnect once resolved/rejected.
  • Minor: re-querying elementToWatch only when null is fine; no change needed there.

Apply:

-      const observer = new MutationObserver(mutationsList => {
+      let timer: ReturnType<typeof setTimeout> | undefined;
+      const observer = new MutationObserver(mutationsList => {
         for (const mutation of mutationsList) {
           if (!elementToWatch && selector) {
             elementToWatch = root?.querySelector(selector);
           }
           if (
             (globalOptions.childList && mutation.type === 'childList') ||
             (globalOptions.attributes && mutation.type === 'attributes')
           ) {
             if (isReady(elementToWatch, selector)) {
               observer.disconnect();
-              resolve();
+              if (timer) {
+                clearTimeout(timer);
+              }
+              resolve();
               return;
             }
           }
         }
       });
 
-      observer.observe(root, globalOptions);
+      const { isReady: _isReady, ...observerOptions } = globalOptions;
+      observer.observe(root, observerOptions as MutationObserverInit);
 
       // Set up an optional timeout to reject the promise if the element never gets child nodes
       if (timeout > 0) {
-        setTimeout(() => {
+        timer = setTimeout(() => {
           observer.disconnect();
           reject(new Error(`Timeout waiting for ${selector}`));
         }, timeout);
       }

Also applies to: 52-58


10-17: SSR safety nit: avoid referencing document in default parameters

While this function is invoked client-side due to the useEffect guard, referencing document in a default parameter can still surprise future callers. Prefer computing the default root inside the executor.

Apply:

-  return (options: { selector: string; root?: HTMLElement | null; timeout?: number }) =>
-    new Promise<void>((resolve, reject) => {
-      const { root = document?.body, selector, timeout = 0 } = options;
+  return (options: { selector: string; root?: HTMLElement | null; timeout?: number }) =>
+    new Promise<void>((resolve, reject) => {
+      const { selector, timeout = 0 } = options;
+      const root = options.root ?? (typeof document !== 'undefined' ? document.body : null);

68-75: Update JSDoc to reflect new options and return type

The hook now accepts an options object and returns a status union. Document these to keep the public API clear.

Apply:

 /**
  * Detect when a Clerk component has mounted by watching DOM updates to an element with a `data-clerk-component="${component}"` property.
  */
-export function useWaitForComponentMount(
+/**
+ * @param component The Clerk component name (e.g., "PricingTable").
+ * @param options Optional readiness selector to further gate mount resolution (e.g., '[data-ready="true"]').
+ * @returns 'rendering' | 'rendered' | 'error'
+ */
+export function useWaitForComponentMount(

83-91: Minor: allow a timeout to surface as hook option for better failure modes

Right now, a stalled readiness check leaves the UI in a permanent "rendering" state. Consider exposing a timeoutMs in the hook and mapping timeout to setStatus('error') with a meaningful message. I can draft this if desired.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f4d6cc4 and 31115ef.

📒 Files selected for processing (6)
  • .changeset/floppy-glasses-share.md (1 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/contexts/index.tsx (1 hunks)
  • packages/react/src/components/uiComponents.tsx (1 hunks)
  • packages/react/src/utils/useWaitForComponentMount.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
  • .changeset/floppy-glasses-share.md
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/react/src/components/uiComponents.tsx
  • packages/react/src/utils/useWaitForComponentMount.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/react/src/components/uiComponents.tsx
🧬 Code graph analysis (1)
packages/react/src/components/uiComponents.tsx (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
  • useWaitForComponentMount (71-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
🔇 Additional comments (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)

78-99: Re-initialization semantics when selector changes

You’ve added options?.selector to the deps, but the !watcherRef.current guard prevents re-watching if the selector changes at runtime. If you intend the hook to react to selector changes, reset the ref in a cleanup. If selectors are static (preferred), ignore this.

Apply:

   useEffect(() => {
     if (!component) {
       throw new Error('Clerk: no component name provided, unable to detect mount.');
     }
 
     if (typeof window !== 'undefined' && !watcherRef.current) {
       const defaultSelector = `[data-clerk-component="${component}"]`;
       const selector = options?.selector;
       watcherRef.current = waitForElementChildren({
         selector: selector
           ? // Allows for `[data-clerk-component="xxxx"][data-some-attribute="123"] .my-class`
             defaultSelector + selector
           : defaultSelector,
       })
         .then(() => {
           setStatus('rendered');
         })
         .catch(() => {
           setStatus('error');
         });
     }
-  }, [component, options?.selector]);
+    return () => {
+      watcherRef.current = undefined;
+    };
+  }, [component, options?.selector]);

Would you like this hook to handle dynamic selector changes, or are callers guaranteed to pass a stable selector?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)

11-22: Prevent CLS & ensure attribute cleanup in InvisibleRootBox

• In packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx switch from React.useEffect to React.useLayoutEffect so class and data-attribute mutations occur before paint.
• Add a dedicated cleanup effect to remove the data-component-status attribute on unmount, avoiding stale status on a reused host element.
• Include showSpan in the effect’s dependency list (or refactor to use a ref for a one-time mount check) to satisfy react-hooks/exhaustive-deps.
• Optional nit: namespace the data attribute (e.g. data-cl-component-status) and update the selector in packages/react/src/components/uiComponents.tsx accordingly (selector: '[data-component-status="ready"]').

Suggested diff:

--- a/packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
+++ b/packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
@@ -11,7 +11,7 @@ const _InvisibleRootBox = React.memo((props: RootBoxProps & { isFlowReady
-  React.useEffect(() => {
+  React.useLayoutEffect(() => {
     const parent = parentRef.current;
     if (!parent) {
       return;
@@ -18,7 +18,7 @@ const _InvisibleRootBox = React.memo((props: RootBoxProps & { isFlowReady
     if (showSpan) {
       setShowSpan(false);
     }
-    parent.setAttribute('class', props.className);
-    parent.setAttribute('data-component-status', props.isFlowReady ? 'ready' : 'awaiting-data');
-  }, [props.className, props.isFlowReady]);
+    parent.setAttribute('class', props.className);
+    parent.setAttribute('data-component-status', props.isFlowReady ? 'ready' : 'awaiting-data');
+  }, [props.className, props.isFlowReady, showSpan]);

+  // Cleanup on unmount to avoid leaking stale status
+  React.useEffect(() => {
+    return () => {
+      const parent = parentRef.current;
+      if (parent) {
+        parent.removeAttribute('data-component-status');
+      }
+    };
+  }, []);

If you rename the attribute to data-cl-component-status, update the matching selector in
packages/react/src/components/uiComponents.tsx (line 582) to selector: '[data-cl-component-status="ready"]'.

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)

29-31: Avoid stale parent ref across unmount; clear on component unmount, not on span removal

We need the parent element after the span disappears, so don’t null the ref here. Instead, clear it in an unmount cleanup (see previous comment). Minor readability tweak below makes the intent explicit.

Apply:

-          ref={el => {
-            parentRef.current = el ? el.parentElement : parentRef.current;
-          }}
+          ref={el => {
+            if (el) {
+              parentRef.current = el.parentElement as HTMLElement | null;
+            }
+          }}
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/customizables/Flow.tsx (1)

13-21: Fold isFlowReady into FlowRootProps and document the new prop

Surfacing isFlowReady on Root looks good. To make the API cleaner and avoid the ad-hoc intersection at the callsite, consider adding isFlowReady directly to FlowRootProps. Also, if Flow.Root is part of the public surface, add a short JSDoc entry for the new prop.

Apply:

-type FlowRootProps = React.PropsWithChildren & FlowMetadata & { sx?: ThemableCssProp };
+type FlowRootProps = React.PropsWithChildren & FlowMetadata & { sx?: ThemableCssProp; isFlowReady?: boolean };

-const Root = (props: FlowRootProps & { isFlowReady?: boolean }) => {
+const Root = (props: FlowRootProps) => {

Please confirm that makeCustomizable(InvisibleRootBox) does not forward unknown props to DOM nodes. If it does, ensure isFlowReady is stripped before reaching any DOM element.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 31115ef and 399137d.

📒 Files selected for processing (5)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (1 hunks)
  • packages/clerk-js/src/ui/customizables/Flow.tsx (1 hunks)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/contexts/index.tsx (1 hunks)
  • packages/react/src/components/uiComponents.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/react/src/components/uiComponents.tsx
  • packages/clerk-js/src/ui/elements/contexts/index.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
🧰 Additional context used
📓 Path-based instructions (9)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/customizables/Flow.tsx
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (1)

7-7: Prop surface widened to include isFlowReady — LGTM

Typing aligns with the new readiness signal and matches how Flow.Root forwards the prop.

@panteliselef panteliselef requested a review from a team August 26, 2025 21:10
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/react/src/components/uiComponents.tsx (1)

584-585: Keep fallback visible on error to avoid CLS regressions

If the waiter fails (status === 'error'), we currently hide the fallback. Safer to show fallback until explicitly 'rendered'.

Apply:

-    const shouldShowFallback = mountingStatus === 'rendering' || !clerk.loaded;
+    const shouldShowFallback = mountingStatus !== 'rendered' || !clerk.loaded;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 399137d and 0650b55.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx (2 hunks)
  • packages/react/src/components/uiComponents.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/elements/InvisibleRootBox.tsx
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/react/src/components/uiComponents.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/react/src/components/uiComponents.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/react/src/components/uiComponents.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/react/src/components/uiComponents.tsx
🧬 Code graph analysis (1)
packages/react/src/components/uiComponents.tsx (1)
packages/react/src/utils/useWaitForComponentMount.ts (1)
  • useWaitForComponentMount (71-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (23)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/react/src/components/uiComponents.tsx (1)

580-583: Approve selector: no change needed
The data-component-status attribute is applied on the same element that carries the data-clerk-component attribute, so concatenating defaultSelector + selector (i.e. [data-clerk-component="PricingTable"][data-component-status="ready"]) will correctly match that root node.

Comment on lines +87 to +90
selector: selector
? // Allows for `[data-clerk-component="xxxx"][data-some-attribute="123"] .my-class`
defaultSelector + selector
: defaultSelector,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to join with a ' '? Or intentionally not?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The concatenation happens between [data-clerk-component="xxxx"] and [data-some-attribute="123"] .my-class, and between those there is no space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants