Skip to content
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

Fix theme "flickering" from light to dark on load of the page #3520

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

joel-jeremy
Copy link
Contributor

@joel-jeremy joel-jeremy commented Sep 27, 2024

Fixes the theme color change (from light theme to configured theme) that happens when initially loading the page.

Switching to useLayoutEffect so that the proper theme colors are set before the page is painted on screen

@actual-github-bot actual-github-bot bot changed the title Fix themes being applied late [WIP] Fix themes being applied late Sep 27, 2024
Copy link
Contributor

coderabbitai bot commented Sep 27, 2024

Walkthrough

The pull request introduces modifications to two components in the desktop client application, specifically the App component and the ThemeStyle function. In both cases, the useEffect hook has been replaced with the useLayoutEffect hook, altering the timing of side effects in relation to DOM updates. This ensures that certain functions are executed synchronously before the browser renders the updated content, affecting how state related to scrollbars and theme preferences is managed.

Changes

File Path Change Summary
packages/desktop-client/src/components/App.tsx
packages/desktop-client/src/style/theme.tsx
Replaced useEffect with useLayoutEffect to modify the timing of side effects related to DOM updates. Introduced useCallback in ThemeStyle for memoizing the media query listener. No changes to exported or public entity declarations.

Possibly related PRs

Suggested labels

sparkles: Merged

Suggested reviewers

  • matt-fidd
  • MatissJanis

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 38a6c02 and 794ec36.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3520.md is excluded by !**/*.md
📒 Files selected for processing (2)
  • packages/desktop-client/src/components/App.tsx (2 hunks)
  • packages/desktop-client/src/style/theme.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/desktop-client/src/components/App.tsx
  • packages/desktop-client/src/style/theme.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

Copy link

netlify bot commented Sep 27, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 794ec36
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/66fc3277c08c5e0008ccd187
😎 Deploy Preview https://deploy-preview-3520.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Sep 27, 2024

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
9 5.29 MB → 5.29 MB (+169 B) +0.00%
Changeset
File Δ Size
src/style/theme.tsx 📈 +163 B (+6.96%) 2.29 kB → 2.45 kB
src/components/App.tsx 📈 +6 B (+0.11%) 5.19 kB → 5.19 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/index.js 3.31 MB → 3.31 MB (+169 B) +0.00%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/resize-observer.js 18.37 kB 0%
static/js/AppliedFilters.js 20.96 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/narrow.js 81.98 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/wide.js 225.27 kB 0%
static/js/ReportRouter.js 1.5 MB 0%

Copy link
Contributor

github-actions bot commented Sep 27, 2024

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.19 MB 0%

Changeset

No files were changed

View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
kcab.worker.js 1.19 MB 0%

@joel-jeremy joel-jeremy changed the title [WIP] Fix themes being applied late Fixes the color change that happens when initially loading the page Sep 27, 2024
@joel-jeremy joel-jeremy changed the title Fixes the color change that happens when initially loading the page Fixes the theme color change that happens when initially loading the page Sep 27, 2024
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: 2

🧹 Outside diff range and nitpick comments (1)
packages/desktop-client/src/components/App.tsx (1)

Line range hint 131-155: Consider separating layout effects from other side effects.

The change from useEffect to useLayoutEffect is generally appropriate for the checkScrollbars function, as it may affect the layout and should run before the browser paints to prevent potential flickering.

However, the onVisibilityChange function, which triggers a sync operation, might not need to be in useLayoutEffect as it doesn't directly affect the layout. Consider separating these concerns:

  1. Keep checkScrollbars and its related event listener in useLayoutEffect.
  2. Move onVisibilityChange and its event listener to a separate useEffect.

This separation would optimize performance by ensuring that only layout-related effects run synchronously, while other side effects run in the usual asynchronous manner.

Here's a suggested refactor:

useLayoutEffect(() => {
  function checkScrollbars() {
    if (hiddenScrollbars !== hasHiddenScrollbars()) {
      setHiddenScrollbars(hasHiddenScrollbars());
    }
  }

  window.addEventListener('focus', checkScrollbars);
  return () => {
    window.removeEventListener('focus', checkScrollbars);
  };
}, [hiddenScrollbars]);

useEffect(() => {
  let isSyncing = false;

  async function onVisibilityChange() {
    if (!isSyncing) {
      console.debug('triggering sync because of visibility change');
      isSyncing = true;
      await dispatch(sync());
      isSyncing = false;
    }
  }

  window.addEventListener('visibilitychange', onVisibilityChange);
  return () => {
    window.removeEventListener('visibilitychange', onVisibilityChange);
  };
}, [dispatch]);

This refactoring separates the layout-affecting code from the sync operation, potentially improving performance and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6725d56 and a7a6f18.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3520.md is excluded by !**/*.md
📒 Files selected for processing (2)
  • packages/desktop-client/src/components/App.tsx (2 hunks)
  • packages/desktop-client/src/style/theme.tsx (2 hunks)
🔇 Additional comments (2)
packages/desktop-client/src/components/App.tsx (2)

2-2: LGTM: Import statement updated correctly.

The addition of useLayoutEffect to the import statement is consistent with the changes in the component. This ensures that the necessary hook is available for use.


Line range hint 1-200: Summary: Addressing late theme application with room for optimization

The changes in this file directly address the PR objective of fixing themes being applied late. By moving the checkScrollbars function to useLayoutEffect, you ensure that scrollbar-related updates happen synchronously before the browser paints, which can help prevent flickering and ensure the theme is applied earlier in the rendering process.

However, as mentioned in the previous comment, there's room for optimization by separating the layout effects from other side effects. This separation would further refine the solution, ensuring that only absolutely necessary operations run synchronously while maintaining the benefits of the current implementation.

Overall, the changes are a step in the right direction for addressing the late theme application issue. With the suggested optimizations, the implementation could be even more efficient and maintainable.

@@ -52,7 +52,7 @@ export function ThemeStyle() {
| undefined
>(undefined);

useEffect(() => {
useLayoutEffect(() => {
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 27, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider the performance implications of using useLayoutEffect

The change from useEffect to useLayoutEffect can help prevent a flash of unstyled content (FOUC) by ensuring the theme is applied before the browser paints. This aligns with the PR objective of fixing themes being applied late.

However, useLayoutEffect runs synchronously and can potentially block visual updates, especially given the complex logic within the effect (event listeners, media queries). This might impact the component's initial render performance.

Consider the following improvements:

  1. Split the effect into two parts:
    a. Use useLayoutEffect for the initial theme application.
    b. Use useEffect for setting up event listeners and handling subsequent theme changes.

  2. Memoize the event listener function to prevent unnecessary re-creation.

Here's a potential refactor:

const darkThemeMediaQueryListener = useCallback((event: MediaQueryListEvent) => {
  if (event.matches) {
    setThemeColors(themes[darkThemePreference].colors);
  } else {
    setThemeColors(themes['light'].colors);
  }
}, [darkThemePreference]);

useLayoutEffect(() => {
  if (theme === 'auto') {
    const darkThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    if (darkThemeMediaQuery.matches) {
      setThemeColors(themes[darkThemePreference].colors);
    } else {
      setThemeColors(themes['light'].colors);
    }
  } else {
    setThemeColors(themes[theme].colors);
  }
}, [theme, darkThemePreference]);

useEffect(() => {
  if (theme === 'auto') {
    const darkThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    darkThemeMediaQuery.addEventListener('change', darkThemeMediaQueryListener);
    return () => {
      darkThemeMediaQuery.removeEventListener('change', darkThemeMediaQueryListener);
    };
  }
}, [theme, darkThemeMediaQueryListener]);

This approach maintains the benefits of early theme application while potentially improving performance.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nice suggestion. I have implemented this.

Copy link
Contributor

Choose a reason for hiding this comment

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

@joel-jeremy, glad to hear that you've implemented the suggestion!

(^‿^)/


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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

🧹 Outside diff range and nitpick comments (2)
packages/desktop-client/src/style/theme.tsx (2)

66-79: Excellent: Implemented useLayoutEffect for immediate theme application

The use of useLayoutEffect ensures that theme colors are set synchronously before the browser paints, effectively addressing the flash of unstyled content (FOUC) issue. The logic correctly handles both 'auto' and specific theme selections.

Consider memoizing the darkThemeMediaQuery to avoid recreating it on every render:

const darkThemeMediaQuery = useMemo(
  () => window.matchMedia('(prefers-color-scheme: dark)'),
  []
);

useLayoutEffect(() => {
  if (theme === 'auto') {
    if (darkThemeMediaQuery.matches) {
      setThemeColors(themes[darkThemePreference].colors);
    } else {
      setThemeColors(themes['light'].colors);
    }
  } else {
    setThemeColors(themes[theme].colors);
  }
}, [theme, darkThemePreference, darkThemeMediaQuery]);

This optimization can further improve performance by avoiding unnecessary media query object creation.


81-97: Well done: Improved event listener management

The useEffect hook has been correctly implemented to manage the event listener for theme changes. It properly uses the memoized darkThemeMediaQueryListener and includes a cleanup function to remove the listener when necessary.

Consider moving the darkThemeMediaQuery creation outside the effect to avoid recreating it on every render:

const darkThemeMediaQuery = useMemo(
  () => window.matchMedia('(prefers-color-scheme: dark)'),
  []
);

useEffect(() => {
  if (theme === 'auto') {
    darkThemeMediaQuery.addEventListener('change', darkThemeMediaQueryListener);
    return () => {
      darkThemeMediaQuery.removeEventListener('change', darkThemeMediaQueryListener);
    };
  }
}, [theme, darkThemeMediaQueryListener, darkThemeMediaQuery]);

This change would be consistent with the optimization suggested for the useLayoutEffect hook and further improve performance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a7a6f18 and 38a6c02.

📒 Files selected for processing (1)
  • packages/desktop-client/src/style/theme.tsx (2 hunks)
🔇 Additional comments (3)
packages/desktop-client/src/style/theme.tsx (3)

2-2: LGTM: Import statement updated correctly

The addition of useLayoutEffect to the import statement is consistent with its usage in the component and aligns with the PR objective of fixing themes being applied late.


55-64: Great job: Implemented performance optimization

The darkThemeMediaQueryListener function is well-implemented using useCallback. This memoization addresses the performance concern raised in the previous review by preventing unnecessary re-creation of the function. The logic for handling theme changes based on the media query is correct and concise.


Line range hint 1-107: Overall: Excellent improvements to theme handling

The changes in this file successfully address the PR objective of fixing themes being applied late. The implementation of useLayoutEffect for immediate theme application and the optimized event listener management with useEffect are well-done. The code is well-structured and follows React best practices.

A few minor optimization suggestions have been provided to further improve performance. Additionally, consider addressing the @ts-strict-ignore comment to enhance type safety.

Great job on these improvements!

packages/desktop-client/src/style/theme.tsx Show resolved Hide resolved
@joel-jeremy joel-jeremy changed the title Fixes the theme color change that happens when initially loading the page Fix theme "fickering" from light to dark on load of the page Sep 29, 2024
@joel-jeremy joel-jeremy changed the title Fix theme "fickering" from light to dark on load of the page Fix theme "flickering" from light to dark on load of the page Sep 29, 2024
Copy link
Contributor

@MikesGlitch MikesGlitch left a comment

Choose a reason for hiding this comment

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

Is this the flicker (wave background goes from dark to light)? It's still happening for me:

test4

@joel-jeremy joel-jeremy force-pushed the fix-themes-applied-late branch from 38a6c02 to 794ec36 Compare October 1, 2024 17:33
@joel-jeremy
Copy link
Contributor Author

Is this the flicker (wave background goes from dark to light)? It's still happening for me:

test4 test4

Yes this is what I'm trying to fix. Looks like it's still there. Need to look further why that is still happening.

@MikesGlitch MikesGlitch self-assigned this Oct 12, 2024
@matt-fidd matt-fidd removed their request for review November 12, 2024 01:21
Copy link
Contributor

This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

@github-actions github-actions bot added the Stale label Dec 12, 2024
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.

2 participants