Skip to content

feat: better alerts around theme awareness #279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025
Merged

Conversation

elibosley
Copy link
Member

@elibosley elibosley commented May 21, 2025

Before Submitting This PR, Please Ensure You Have Completed The Following:

  1. Are internal links to wiki documents using relative file links?
  2. Are all new documentation files lowercase, with dash separated names (ex. unraid-os.mdx)?
  3. Are all assets (images, etc), located in an assets/ subfolder next to the .md/mdx files?
  4. Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  5. Is the build succeeding?

Summary by CodeRabbit

  • New Features

    • Added a theme synchronization status indicator to the iframe test page, displaying whether theme sync is ready or waiting.
    • The "Apply Theme" button is now enabled or disabled based on theme sync readiness, providing clearer user feedback.
    • Introduced a new hook to detect iframe context, improving theme and navigation behavior when embedded.
  • Bug Fixes

    • Prevented redundant theme update messages from being sent, ensuring updates only occur when necessary.
  • Style

    • Improved UI feedback with styled status elements next to theme controls.

Copy link
Contributor

coderabbitai bot commented May 21, 2025

📝 Walkthrough

Walkthrough

This update enhances theme synchronization between a parent page and an iframe. It introduces a status indicator for theme sync readiness, conditional message sending based on sync status, timeout handling, and refines the messaging logic in both the parent test page and the ThemeSync React component to prevent redundant theme updates and ensure reliable communication.

Changes

File(s) Change Summary
iframe-test.html Added a theme sync status indicator UI, logic to track readiness, conditional theme message sending, timeout for fallback readiness, and handling of "theme-ready" messages from the iframe.
src/theme/Layout/ThemeSync.tsx Replaced manual iframe detection with useIframe hook; added lastSentTheme state to avoid redundant "theme-changed" messages; delayed sending "theme-ready" message on mount; removed immediate "theme-ready" sending from message listener.
src/hooks/useIframe.ts Added new useIframe hook to detect iframe presence by comparing window.self and window.top.
src/theme/Layout/IframeNavigation.tsx Replaced manual iframe detection state and effect with useIframe hook for synchronous iframe status detection; removed unused state and effect.
src/theme/Layout/index.tsx Replaced manual iframe detection state and effect with direct use of useIframe hook; removed import of isInIframe utility.
src/theme/Layout/utils.ts Removed the isInIframe utility function as iframe detection is now handled by the useIframe hook.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Parent as Parent Page (iframe-test.html)
    participant Iframe as Iframe (ThemeSync.tsx)

    Parent->>Iframe: Loads iframe
    Note right of Parent: Sets status to "waiting", disables Apply Theme
    Iframe-->>Parent: (after 20ms) Sends "theme-ready" message
    Parent->>Parent: Clears timeout, sets status to "ready", enables Apply Theme
    Parent->>Iframe: Sends "theme-changed" if Apply Theme is clicked and ready
    Iframe->>Iframe: Updates theme, tracks last sent theme
    Iframe-->>Parent: Sends "theme-changed" only if theme differs from last sent

Possibly related PRs

Suggested reviewers

  • zackspear
  • ljm42

Poem

🐇
In frames of theme, we sync and wait,
With status lights to indicate—
A message sent, a theme applied,
No extra pings, all bugs defied.
Now parent, child, in harmony,
Dance in sync, as code should be!
🌈


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 62be81a and a2b8df5.

📒 Files selected for processing (5)
  • src/hooks/useIframe.ts (1 hunks)
  • src/theme/Layout/IframeNavigation.tsx (1 hunks)
  • src/theme/Layout/ThemeSync.tsx (2 hunks)
  • src/theme/Layout/index.tsx (1 hunks)
  • src/theme/Layout/utils.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/theme/Layout/utils.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/theme/Layout/ThemeSync.tsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/theme/Layout/IframeNavigation.tsx (1)
src/hooks/useIframe.ts (1)
  • useIframe (14-22)
src/theme/Layout/index.tsx (1)
src/hooks/useIframe.ts (1)
  • useIframe (14-22)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: AWS Amplify Console Web Preview
🔇 Additional comments (3)
src/hooks/useIframe.ts (1)

1-22: Well-structured hook implementation for iframe detection.

This is a clean and well-documented implementation of a React hook for detecting iframe context. The code follows React best practices by:

  • Using useState and useEffect appropriately
  • Handling SSR with the typeof window !== 'undefined' check
  • Including descriptive JSDoc comments
src/theme/Layout/IframeNavigation.tsx (1)

3-3: Good refactoring to use the centralized hook.

The change nicely replaces local state management with the new useIframe hook, simplifying the component while maintaining the same behavior.

Also applies to: 10-10

src/theme/Layout/index.tsx (1)

5-5: Consistent refactoring using the shared hook.

This change follows the same pattern as in other components, replacing local iframe detection with the centralized useIframe hook.

Also applies to: 8-8


🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • 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.

@coderabbitai coderabbitai bot requested review from ljm42 and zackspear May 21, 2025 18:58
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 (2)
src/theme/Layout/ThemeSync.tsx (1)

17-28: Improved theme readiness notification with delayed initialization

This new effect properly ensures the Docusaurus theme system is fully initialized before sending the ready notification to the parent window. The timeout approach is a good way to handle this asynchronous initialization.

Consider making the 20ms delay configurable via a constant for easier adjustments if needed in the future.

+// Delay before sending theme-ready message to ensure initialization
+const THEME_READY_DELAY_MS = 20;

// Ensure theme system is ready and notify parent
useEffect(() => {
  if (isInIframeState) {
    // Wait a short time to ensure Docusaurus theme system is fully initialized
    const readyTimer = setTimeout(() => {
      // Send ready message to parent
      window.parent.postMessage({ type: 'theme-ready' }, '*');
-    }, 20);
+    }, THEME_READY_DELAY_MS);
    
    return () => clearTimeout(readyTimer);
  }
}, [isInIframeState]);
iframe-test.html (1)

186-202: Good timeout implementation for sync readiness

The timeout implementation provides a robust fallback mechanism in case the iframe never sends a 'theme-ready' message, preventing the UI from being stuck in a waiting state indefinitely.

Consider storing the timeout ID in a separate variable rather than as a property of the iframe element for better code organization.

// Auto-apply theme when iframe loads
iframe.addEventListener('load', function() {
    console.log('Iframe loaded, waiting for theme-ready message...');
    // Reset the theme sync status when iframe loads
    updateThemeStatus(false);
    
+   // Track timeout ID for theme sync
+   let syncTimeoutId;
    
    // Set a timeout for theme sync readiness
-   const syncTimeout = setTimeout(() => {
+   syncTimeoutId = setTimeout(() => {
        if (!isThemeSyncReady) {
            console.warn('Theme sync ready message not received within timeout period');
            // Enable theme controls anyway after timeout
            updateThemeStatus(true);
        }
    }, 5000);
    
-   // Store the timeout in a property so we can clear it if needed
-   iframe.syncTimeoutId = syncTimeout;
+   // Store the timeout ID in a variable accessible to the message event handler
+   window.currentSyncTimeoutId = syncTimeoutId;
});

// Then update the message handler:
if (event.data && event.data.type === 'theme-ready') {
    console.log('Docusaurus is ready for theme sync');
    
    // Clear any existing timeout
-   if (iframe.syncTimeoutId) {
-       clearTimeout(iframe.syncTimeoutId);
+   if (window.currentSyncTimeoutId) {
+       clearTimeout(window.currentSyncTimeoutId);
+       window.currentSyncTimeoutId = null;
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 263bc46 and 62be81a.

📒 Files selected for processing (2)
  • iframe-test.html (5 hunks)
  • src/theme/Layout/ThemeSync.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/theme/Layout/ThemeSync.tsx (1)
src/theme/Layout/utils.ts (1)
  • isInIframe (4-6)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: AWS Amplify Console Web Preview
🔇 Additional comments (6)
src/theme/Layout/ThemeSync.tsx (2)

10-10: Great addition of state tracking for theme messages!

Adding lastSentTheme state is an excellent optimization that prevents redundant theme messages from being sent to the parent window.


58-70: Improved theme change notification with conditional sending

The conditional check colorMode !== lastSentTheme is an excellent optimization that prevents sending duplicate theme messages when the theme hasn't actually changed. This reduces unnecessary communication between frames and follows React best practices with proper dependency tracking.

iframe-test.html (4)

65-79: Great addition of visual theme sync status indicator

The addition of theme status styles and UI element provides clear visual feedback to users about the synchronization state. The color-coding (yellow for waiting, green for ready) makes the status immediately recognizable.

Also applies to: 121-121


144-165: Well-structured theme sync state management

The implementation of theme sync readiness tracking and the updateThemeStatus function creates a clean and maintainable approach to managing the sync state. The function properly handles all aspects of status updates: variable state, UI text, CSS classes, and button state.


167-177: Improved defensive coding for theme message sending

The conditional check before sending theme messages prevents potential race conditions by ensuring messages are only sent when the iframe is ready to receive them. The console logging provides helpful debugging information as well.


209-220: Complete message handling for theme synchronization

The implementation properly handles the 'theme-ready' message from the iframe by clearing any existing timeout, updating the UI status, and immediately synchronizing the iframe's theme. This creates a robust communication protocol between the parent page and iframe.

Copy link

This pull request is automatically being deployed by Amplify Hosting (learn more).

Access this pull request here: https://pr-279.d1o5s833kbd339.amplifyapp.com

@elibosley elibosley merged commit 9c9c257 into main May 21, 2025
3 checks passed
@elibosley elibosley deleted the feat/better-theme-alerts branch May 21, 2025 19:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant