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

[WEB-2532] fix: custom theme mutation logic #5685

Merged
merged 2 commits into from
Oct 8, 2024

Conversation

aaryan610
Copy link
Collaborator

@aaryan610 aaryan610 commented Sep 24, 2024

Problem:

MutationObserver logic to update the custom theme is too expensive and unnecessary.

Solution:

Update the applyTheme function to select the themeElement with the attribute [data-theme] instead of [data-theme="custom"] to make sure themeElement always exists.

Plane issue: WEB-2532

Summary by CodeRabbit

  • New Features

    • Enhanced theme application logic for a more streamlined user experience.
  • Bug Fixes

    • Eliminated unnecessary dependencies on DOM elements, improving performance and reliability of theme settings.

Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

The changes across the components focus on simplifying the theme application logic by removing unnecessary dependencies on the DOM. The ProfileAppearancePage and StoreWrapper components have been updated to streamline theme application processes, while the applyTheme function has been modified to centralize theme manipulation to a specific document element. These modifications enhance the clarity and efficiency of theme management throughout the application.

Changes

File Change Summary
web/app/profile/appearance/page.tsx Removed the custom theme element parameter from applyTheme, simplifying the function call.
web/core/lib/wrappers/store-wrapper.tsx Eliminated the dom state variable and its associated logic for a more straightforward theme application.
web/helpers/theme.helper.ts Updated applyTheme to remove the dom parameter and use a document query to find the theme element.

Possibly related PRs

Suggested labels

🐛bug, ✍️editor

Suggested reviewers

  • gakshita
  • SatishGandham
  • rahulramesha

🐇 In the meadow where themes play,
A rabbit hops, brightening the day.
With simpler paths and colors anew,
The world feels fresh, like morning dew.
Let's cheer for changes, swift and bright,
A joyful leap into the light! 🌈


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a651a60 and 4dacdc4.

Files selected for processing (1)
  • web/helpers/theme.helper.ts (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • web/helpers/theme.helper.ts

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

Outside diff range and nitpick comments (5)
web/app/profile/appearance/page.tsx (1)

Line range hint 1-89: Summary of changes and next steps

The changes made to the ProfileAppearancePage component, specifically in the applyThemeChange function, align with the PR objectives of improving the performance of the theme mutation logic. The removal of the custom theme element parameter from the applyTheme function call simplifies the logic and potentially enhances efficiency.

To ensure the effectiveness of these changes:

  1. Verify that the applyTheme function has been updated in its implementation file to work with the new calling convention.
  2. Consider adding unit tests or updating existing ones to cover the new behavior of the applyThemeChange function.
  3. If possible, perform performance measurements to quantify the improvement gained from this change.

To further improve the theme application process:

  1. Consider memoizing the applyThemeChange function to prevent unnecessary re-renders.
  2. Evaluate if the theme palette parsing logic (theme?.palette !== ",,,,") could be moved to a utility function for better reusability and testability.
web/helpers/theme.helper.ts (4)

64-64: Approve themeElement selection and suggest minor improvement.

The introduction of themeElement centralizes the theme application to a specific element identified by the data-theme attribute. This approach is more robust and aligns with the PR objectives.

Consider adding a comment explaining the purpose of this selection for better code readability:

+ // Select the first element with a data-theme attribute for applying the theme
const themeElement = window.document?.querySelector<HTMLElement>("[data-theme]");

84-88: Approve CSS property setting changes and suggest optimization.

The changes to set CSS properties on themeElement instead of dom are consistent with the new approach and maintain the existing functionality. The use of optional chaining is a good practice for handling potential null values.

Consider optimizing the performance by caching the style property of themeElement:

+ const themeStyle = themeElement?.style;
+ if (!themeStyle) return;

- themeElement?.style.setProperty(`--color-background-${shade}`, bgRgbValues);
- themeElement?.style.setProperty(`--color-text-${shade}`, textRgbValues);
- themeElement?.style.setProperty(`--color-primary-${shade}`, primaryRgbValues);
- themeElement?.style.setProperty(`--color-sidebar-background-${shade}`, sidebarBackgroundRgbValues);
- themeElement?.style.setProperty(`--color-sidebar-text-${shade}`, sidebarTextRgbValues);
+ themeStyle.setProperty(`--color-background-${shade}`, bgRgbValues);
+ themeStyle.setProperty(`--color-text-${shade}`, textRgbValues);
+ themeStyle.setProperty(`--color-primary-${shade}`, primaryRgbValues);
+ themeStyle.setProperty(`--color-sidebar-background-${shade}`, sidebarBackgroundRgbValues);
+ themeStyle.setProperty(`--color-sidebar-text-${shade}`, sidebarTextRgbValues);

// ... (apply similar changes to other setProperty calls)

This optimization reduces the number of property accesses and null checks, potentially improving performance, especially in the loop where these properties are set multiple times.

Also applies to: 93-97, 104-104


Line range hint 107-121: Update unsetCustomCssVariables to match applyTheme changes.

The unsetCustomCssVariables function hasn't been updated to match the changes made in applyTheme. It still uses [data-theme='custom'] to select the DOM element, which is inconsistent with the new approach and could lead to issues where custom CSS variables are not properly unset.

Update the unsetCustomCssVariables function to use the same selector as applyTheme:

export const unsetCustomCssVariables = () => {
+ const themeElement = window.document?.querySelector<HTMLElement>("[data-theme]");
+ if (!themeElement) return;

  for (let i = 10; i <= 900; i >= 100 ? (i += 100) : (i += 10)) {
-   const dom = document.querySelector<HTMLElement>("[data-theme='custom']");

-   dom?.style.removeProperty(`--color-background-${i}`);
-   dom?.style.removeProperty(`--color-text-${i}`);
-   dom?.style.removeProperty(`--color-border-${i}`);
-   dom?.style.removeProperty(`--color-primary-${i}`);
-   dom?.style.removeProperty(`--color-sidebar-background-${i}`);
-   dom?.style.removeProperty(`--color-sidebar-text-${i}`);
-   dom?.style.removeProperty(`--color-sidebar-border-${i}`);
-   dom?.style.removeProperty("--color-scheme");
+   themeElement.style.removeProperty(`--color-background-${i}`);
+   themeElement.style.removeProperty(`--color-text-${i}`);
+   themeElement.style.removeProperty(`--color-border-${i}`);
+   themeElement.style.removeProperty(`--color-primary-${i}`);
+   themeElement.style.removeProperty(`--color-sidebar-background-${i}`);
+   themeElement.style.removeProperty(`--color-sidebar-text-${i}`);
+   themeElement.style.removeProperty(`--color-sidebar-border-${i}`);
  }
+ themeElement.style.removeProperty("--color-scheme");
};

This change ensures consistency with the applyTheme function and properly unsets all custom CSS variables.


Line range hint 1-128: Summary of changes and suggestions

The changes in this file align well with the PR objectives of improving the theme mutation logic. The centralization of theme application to a specific element with the data-theme attribute is a good approach. However, there are a few areas for improvement:

  1. Consider adding comments to explain the purpose of the themeElement selection.
  2. Optimize performance in the applyTheme function by caching the style property of themeElement.
  3. Update the unsetCustomCssVariables function to use the same selector as applyTheme for consistency.

These changes will further enhance the robustness and efficiency of the theme helper functions.

To further improve the theme management system, consider the following architectural suggestions:

  1. Implement a Theme Manager class that encapsulates all theme-related operations, including applying and unsetting themes.
  2. Use a configuration object or enum to define theme-related constants (e.g., shade values, CSS variable names) to improve maintainability.
  3. Implement a caching mechanism for calculated shades to avoid redundant calculations when applying the same theme multiple times.

These architectural improvements would make the theme system more modular, maintainable, and performant.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f38755b and a651a60.

Files selected for processing (3)
  • web/app/profile/appearance/page.tsx (1 hunks)
  • web/core/lib/wrappers/store-wrapper.tsx (1 hunks)
  • web/helpers/theme.helper.ts (2 hunks)
Additional comments not posted (3)
web/core/lib/wrappers/store-wrapper.tsx (1)

45-52: 🛠️ Refactor suggestion

Approved: Theme application logic simplified

The changes successfully simplify the theme application logic, which aligns with the PR objectives to improve performance. The removal of the dom state and its associated logic (as mentioned in the AI summary) contributes to this simplification.

However, there's a potential for further improvement:

Consider removing the currentTheme === "custom" check if the applyTheme function has been updated to work with all themes as mentioned in the PR objectives. This could further simplify the logic:

- if (currentTheme === "custom" && currentThemePalette) {
-   applyTheme(
-     currentThemePalette !== ",,,," ? currentThemePalette : "#0d101b,#c5c5c5,#3f76ff,#0d101b,#c5c5c5",
-     false
-   );
- } else unsetCustomCssVariables();
+ if (currentThemePalette) {
+   applyTheme(
+     currentThemePalette !== ",,,," ? currentThemePalette : "#0d101b,#c5c5c5,#3f76ff,#0d101b,#c5c5c5",
+     false
+   );
+ } else {
+   unsetCustomCssVariables();
+ }

To ensure the changes align with the PR objectives, let's verify the implementation of the applyTheme function:

This will help us confirm if the applyTheme function has been updated to select the theme element using [data-theme] instead of [data-theme="custom"] as mentioned in the PR objectives.

Verification successful

Verified: applyTheme function aligns with PR objectives

The applyTheme function in web/helpers/theme.helper.ts correctly selects the theme element using [data-theme] instead of [data-theme="custom"]. This change simplifies the theme application logic and aligns with the PR objectives to improve performance.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of the applyTheme function

# Test: Search for the applyTheme function definition
rg --type typescript -A 10 'function applyTheme'

Length of output: 85


Script:

#!/bin/bash
# Description: Verify the implementation of the applyTheme function with correct file type

# Test: Search for the applyTheme function definition in TypeScript React files
rg --type typescriptreact -A 10 'function applyTheme'

Length of output: 95


Script:

#!/bin/bash
# Description: Verify the implementation of the applyTheme function by searching within .tsx files

# Test: Search for the applyTheme function definition in .tsx files
rg -g "*.tsx" 'function\s+applyTheme|const\s+applyTheme\s*='

Length of output: 62


Script:

#!/bin/bash
# Description: Search for the applyTheme function in both .ts and .tsx files with flexible patterns

rg -g "*.ts*" 'function\s+applyTheme|const\s+applyTheme\s*='

Length of output: 163


Script:

#!/bin/bash
# Description: Retrieve the implementation of the applyTheme function from theme.helper.ts

# Test: Extract the applyTheme function definition and its contents
rg 'export\s+const\s+applyTheme\s*=' -A 20 web/helpers/theme.helper.ts

Length of output: 1364

web/app/profile/appearance/page.tsx (1)

55-57: Approve changes with verification request

The modifications to the applyTheme function call align with the PR objectives of improving performance. The logic for applying custom themes remains robust, handling empty palettes and maintaining the correct conditions for application.

To ensure the changes are fully effective and error-free:

  1. Please confirm that the applyTheme function has been updated elsewhere to work without the custom theme element parameter.
  2. Consider measuring the performance impact of this change to quantify the improvement.

Run the following script to verify the applyTheme function implementation:

This script will help us confirm that the applyTheme function has been properly updated and that there are no remaining instances of the old implementation using [data-theme="custom"].

web/helpers/theme.helper.ts (1)

62-62: Approve function signature change and verify usage.

The removal of the dom parameter from the applyTheme function signature aligns with the PR objective of improving the theme mutation logic. This change makes the function more focused and less dependent on external DOM elements.

To ensure this change doesn't break existing code, please run the following script to verify the function usage across the codebase:

Verification successful

Function signature change verified successfully.

All existing calls to applyTheme match the updated signature without the dom parameter. No issues found with the current usage across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `applyTheme` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type typescript -A 5 $'applyTheme\('

Length of output: 77


Script:

#!/bin/bash
# Description: Verify all function calls to `applyTheme` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type=ts -A 5 'applyTheme\('

Length of output: 869

web/helpers/theme.helper.ts Outdated Show resolved Hide resolved
@pushya22 pushya22 merged commit 39195d0 into preview Oct 8, 2024
14 of 15 checks passed
@pushya22 pushya22 deleted the fix/custom-theme-mutation branch October 8, 2024 11:17
@sriramveeraghanta sriramveeraghanta modified the milestones: v0.23.0, v0.24.0 Oct 8, 2024
sriramveeraghanta pushed a commit that referenced this pull request Oct 10, 2024
* fix: custom theme mutation logic

* chore: update querySelector element
@sriramveeraghanta sriramveeraghanta modified the milestones: v0.24.0, v0.23.1 Oct 10, 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.

4 participants