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

支持前端使能/禁用代码折叠 #5640

Merged
merged 3 commits into from
Oct 11, 2024

Conversation

code-october
Copy link
Contributor

@code-october code-october commented Oct 11, 2024

💻 变更类型 | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

🔀 变更说明 | Description of Change

同 Artifacts 一样,有些人不想默认开启代码折叠功能,支持在客户端设置关闭代码折叠

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Introduced code folding functionality, allowing users to collapse or expand long code blocks based on their preferences.
    • Added a checkbox in the settings for enabling/disabling code folding.
    • Enhanced localization support for code folding with new entries in both English and Chinese.
  • Bug Fixes

    • Improved visibility control for the code folding toggle button based on user settings.
  • Documentation

    • Updated locale files to include descriptions for the new code folding feature.

Copy link

vercel bot commented Oct 11, 2024

@code-october is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

This pull request introduces several enhancements across multiple components to implement code folding functionality. The CustomCode component is updated to conditionally render code blocks based on a new enableCodeFold variable, which is influenced by session configurations. The Settings component now includes a checkbox to enable or disable this feature, while localization files are updated to support new titles and subtitles for code folding. Additionally, the configuration store is modified to include a default setting for code folding.

Changes

File Change Summary
app/components/markdown.tsx - Added enableCodeFold variable to CustomCode for dynamic code folding.
- Updated rendering logic for code block height and toggle button visibility.
app/components/settings.tsx - Added a new checkbox in settings to control enableCodeFold, updating the configuration on toggle.
app/locales/cn.ts - Added CodeFold property in Mask configuration with title and subtitle for code folding.
app/locales/en.ts - Introduced CodeFold property in Mask section with title and subtitle for code folding functionality.
app/store/config.ts - Added enableCodeFold: true to DEFAULT_CONFIG for enabling code folding by default.
app/store/mask.ts - Updated Mask type definition to include optional enableCodeFold property.

Possibly related PRs

  • 代码折叠 #5235: This PR introduces enhancements to the CustomCode component in app/components/markdown.tsx, which is directly related to the changes made in the main PR regarding the CustomCode component and its code folding functionality.
  • Modify View All Languages #5303: This PR modifies the CustomCode component in app/components/markdown.tsx to enhance its internationalization capabilities, which is relevant as it builds upon the same component that has been updated in the main PR.

Suggested reviewers

  • Dogtiti
  • lloydzhou

Poem

In the land of code, where rabbits play,
We fold our snippets, come what may.
With toggles and settings, oh what a sight,
Code folding's here, making things right!
So hop along, let’s celebrate,
A cleaner view, oh isn’t it great? 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8fd843d and 4a1319f.

📒 Files selected for processing (1)
  • app/components/markdown.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/components/markdown.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
Contributor

Your build has completed!

Preview deployment

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 (8)
app/components/markdown.tsx (2)

172-176: LGTM! Consider using object destructuring for cleaner code.

The implementation of enableCodeFold looks good and correctly considers both session-specific and global configurations. This aligns well with the PR objectives.

Consider using object destructuring for a cleaner code:

const { currentSession, useAppConfig } = useChatStore();
const session = currentSession();
const { enableCodeFold: globalEnableCodeFold } = useAppConfig();
const enableCodeFold = session.mask?.enableCodeFold !== false && globalEnableCodeFold;

This approach reduces the number of variables and makes the code more concise.


Line range hint 205-211: LGTM! Consider extracting the button rendering logic.

The "Show More" button rendering now correctly depends on both showToggle and enableCodeFold, which is consistent with the new feature implementation.

Consider extracting the button rendering logic into a separate function for better readability:

const renderShowMoreButton = () => {
  if (showToggle && enableCodeFold && collapsed) {
    return (
      <div className={`show-hide-button ${collapsed ? "collapsed" : "expanded"}`}>
        <button onClick={toggleCollapsed}>{Locale.NewChat.More}</button>
      </div>
    );
  }
  return null;
};

// Then in the return statement:
{renderShowMoreButton()}

This approach improves code organization and makes the component's structure clearer.

app/locales/cn.ts (1)

668-671: LGTM! Consider a minor improvement for consistency.

The addition of the CodeFold property to the Mask.Config object is well-implemented and aligns with the PR objectives. The Chinese translations are clear and accurately describe the feature.

For consistency with other boolean config options in this file, consider changing the Title to "启用代码折叠" instead of "启用CodeFold". This would make it more aligned with the Chinese language style used throughout the file.

 CodeFold: {
-  Title: "启用CodeFold",
+  Title: "启用代码折叠",
   SubTitle: "启用之后可以折叠/展开过长的代码块",
 },
app/components/mask.tsx (3)

Line range hint 1-24: Consider organizing imports and removing unused ones

The import section is quite long and may contain unused imports. Consider organizing them and removing any that are not used in the file.

To help identify unused imports, you can run the following command:

#!/bin/bash
# Description: Identify potentially unused imports

echo "Potentially unused imports:"
rg --type typescript --type javascript -n "^import .* from" app/components/mask.tsx | while read -r line; do
    import=$(echo "$line" | awk -F'import ' '{print $2}' | awk -F' from' '{print $1}')
    if ! rg -q "$import" --type typescript --type javascript app/components/mask.tsx; then
        echo "$line"
    fi
done

Line range hint 1-1000: Consider splitting the file into smaller, more focused components

This file is quite long and contains multiple components (MaskConfig, ContextPromptItem, ContextPrompts, MaskPage). Consider splitting these into separate files for better maintainability and readability.

To help with this refactoring, you could create separate files for each main component and then import them in a main mask.tsx file. For example:

  1. MaskConfig.tsx
  2. ContextPrompts.tsx (including ContextPromptItem)
  3. MaskPage.tsx

This would make the codebase more modular and easier to navigate.


Line range hint 4-4: TODO comment: Add tests

There's a TODO comment to add tests. It's important to ensure proper test coverage for the components in this file.

Would you like me to generate some basic test cases for the components in this file? I can create a new issue to track this task if you prefer.

app/locales/en.ts (1)

678-682: LGTM with a minor suggestion for clarity.

The addition of the CodeFold configuration option is well-structured and aligns with the existing localization patterns. The description is clear and informative.

Consider a slight rewording of the subtitle for better clarity:

 CodeFold: {
   Title: "Enable CodeFold",
   SubTitle:
-    "Automatically collapse/expand overly long code block when enable CodeFold",
+    "Automatically collapse/expand overly long code blocks when CodeFold is enabled",
 },

This minor change improves readability and grammatical correctness.

app/components/settings.tsx (1)

1512-1526: LGTM! Consider adding a data-testid attribute for easier testing.

The implementation of the code folding setting is well-structured and follows the existing patterns in the file. It correctly uses localization for internationalization and properly implements the checkbox state and update logic.

For consistency with best practices and to facilitate easier testing, consider adding a data-testid attribute to the input element.

Here's a suggested minor improvement:

 <input
   aria-label={Locale.Mask.Config.CodeFold.Title}
   type="checkbox"
   checked={config.enableCodeFold}
+  data-testid="enable-code-fold-checkbox"
   onChange={(e) =>
     updateConfig(
       (config) => (config.enableCodeFold = e.currentTarget.checked),
     )
   }
 ></input>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c139038 and 6792d6e.

📒 Files selected for processing (7)
  • app/components/markdown.tsx (2 hunks)
  • app/components/mask.tsx (1 hunks)
  • app/components/settings.tsx (1 hunks)
  • app/locales/cn.ts (1 hunks)
  • app/locales/en.ts (1 hunks)
  • app/store/config.ts (1 hunks)
  • app/store/mask.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (8)
app/store/mask.ts (1)

22-22: LGTM! Verify usage in related components.

The addition of the enableCodeFold property to the Mask type is appropriate and aligns with the PR objective. The optional nature of the property ensures backward compatibility.

To ensure proper implementation, please verify the usage of this new property in related components. Run the following script to check for its usage:

✅ Verification successful

Verified! The enableCodeFold property is correctly implemented and consistently used across all relevant components, ensuring both functionality and backward compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of enableCodeFold in components

# Search for enableCodeFold in all TypeScript and TypeScript React files
rg --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' -t ts -t tsx 'enableCodeFold'

Length of output: 936

app/store/config.ts (1)

55-56: LGTM! Consider enhancing the comment and verifying migration handling.

The addition of the enableCodeFold option aligns well with the PR objectives and provides the desired functionality to enable/disable code folding. Good job on maintaining backward compatibility by setting it to true by default.

A couple of suggestions:

  1. Consider expanding the comment slightly for clarity:
enableCodeFold: true, // Enable/disable code folding in the UI
  1. Verify if the new enableCodeFold option needs any special handling in the merge and migrate functions at the bottom of this file. If not, please confirm that the default handling is sufficient.
app/components/markdown.tsx (2)

199-199: LGTM! The maxHeight style is correctly updated.

The maxHeight style property now correctly considers the enableCodeFold variable, which is consistent with the new feature implementation.


Line range hint 1-338: Overall, the changes look good and align with the PR objectives.

The implementation of the code folding feature is well-done, considering both session-specific and global configurations. This provides the desired flexibility for users to enable or disable code folding as needed. The changes are localized to the CustomCode component, which is appropriate for this feature.

A few minor suggestions have been made to improve code readability and organization, but these are not critical for the functionality. Great job on implementing this new feature!

app/locales/cn.ts (1)

668-671: Summary: Localization strings added for code folding feature

The changes to this file are minimal and focused, adding only the necessary Chinese localization strings for the new code folding feature. These additions are well-integrated into the existing Mask.Config object and maintain consistency with the file's overall structure and style.

The new strings will enable Chinese-speaking users to understand and use the code folding feature effectively.

app/components/mask.tsx (2)

Line range hint 1-1000: Summary: Good implementation with room for improvement

The new code folding feature is well-implemented and integrates smoothly with the existing component structure. However, there are some areas for improvement:

  1. The file is quite long and could benefit from being split into smaller, more focused components.
  2. There may be unused imports that could be removed.
  3. There's a TODO comment for adding tests that should be addressed.

Overall, the changes are approved, but consider the suggested improvements for better maintainability and code organization.


186-202: New feature: Code folding option added

The new code segment introduces a checkbox for enabling/disabling code folding. This feature is well-integrated into the existing MaskConfig component and follows the same pattern as other configuration options.

A few observations:

  1. The feature is conditionally rendered based on globalConfig.enableCodeFold.
  2. The checkbox state is linked to props.mask.enableCodeFold.
  3. The implementation is consistent with other similar features in the component.

To ensure this feature is properly integrated, let's verify its usage:

✅ Verification successful

Action Required: Update Verification Script for Accurate Results

The previous verification script encountered errors due to unrecognized file types. To accurately verify the usage of enableCodeFold, please execute the updated script below:


Action Required: Update Verification Script to Use File Patterns Instead of Type Specifiers

The previous verification script encountered errors due to unrecognized file types. To accurately search for enableCodeFold, please execute the updated script below:


Verification Successful: enableCodeFold is Properly Integrated

The enableCodeFold feature is consistently implemented across the codebase, including in app/components/mask.tsx and related files. No issues were found regarding its integration or usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of enableCodeFold in the codebase

# Check for enableCodeFold in global config
echo "Checking global config for enableCodeFold:"
rg "enableCodeFold" --type typescript --type javascript

# Check for enableCodeFold in mask-related files
echo "\nChecking mask-related files for enableCodeFold:"
rg "enableCodeFold" --type typescript --type javascript -g "*mask*"

Length of output: 397


Script:

#!/bin/bash
# Description: Verify the usage of enableCodeFold in the codebase

# Check for enableCodeFold in global config
echo "Checking global config for enableCodeFold:"
rg "enableCodeFold" -t ts -t tsx -t js -t jsx

# Check for enableCodeFold in mask-related files
echo -e "\nChecking mask-related files for enableCodeFold:"
rg "enableCodeFold" -t ts -t tsx -t js -t jsx -g "*mask*"

Length of output: 365


Script:

#!/bin/bash
# Description: Verify the usage of enableCodeFold in the codebase

# Check for enableCodeFold in global config
echo "Checking global config for enableCodeFold:"
rg "enableCodeFold" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx"

# Check for enableCodeFold in mask-related files
echo -e "\nChecking mask-related files for enableCodeFold:"
rg "enableCodeFold" -g "*mask*" -g "*.ts" -g "*.tsx" -g "*.js" -g "*.jsx"

Length of output: 2061

app/components/settings.tsx (1)

1512-1526: Verify the implementation of code folding in other parts of the application.

The addition of the code folding setting is well-implemented in the settings component. However, to ensure full functionality, we should verify that this setting is respected in the relevant parts of the application where code folding is applied.

Please run the following script to check for the usage of enableCodeFold in other parts of the application:

✅ Verification successful

Please run the following corrected script to check for the usage of enableCodeFold in other parts of the application:


Please run the following corrected script to check for the usage of enableCodeFold in other parts of the application:


The implementation of enableCodeFold is properly integrated across the application.

The enableCodeFold setting is consistently used in relevant components and configurations, ensuring that the code folding functionality is respected throughout the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of enableCodeFold in the codebase

# Search for enableCodeFold usage
echo "Searching for enableCodeFold usage:"
rg --type typescript --type tsx 'enableCodeFold'

# Search for potential code folding implementation
echo "\nSearching for potential code folding implementation:"
rg --type typescript --type tsx 'fold|collapse|expand'

Length of output: 375


Script:

# 
#!/bin/bash
# Description: Check for usage of enableCodeFold in the codebase

# Search for enableCodeFold usage
echo "Searching for enableCodeFold usage:"
rg --type ts --type tsx 'enableCodeFold'

# Search for potential code folding implementation
echo -e "\nSearching for potential code folding implementation:"
rg --type ts --type tsx 'fold|collapse|expand'

Length of output: 347


Script:

# 
#!/bin/bash
# Description: Check for usage of enableCodeFold in the codebase

# Search for enableCodeFold usage
echo "Searching for enableCodeFold usage:"
rg -g "*.ts" -g "*.tsx" 'enableCodeFold'

# Search for potential code folding implementation
echo -e "\nSearching for potential code folding implementation:"
rg -g "*.ts" -g "*.tsx" 'fold|collapse|expand'

Length of output: 2372

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 (3)
app/components/settings.tsx (1)

1512-1527: LGTM! Consider adding an ARIA label to the checkbox.

The implementation of the code folding toggle is well-integrated into the existing settings structure. It correctly uses localization and follows the established patterns for other settings. The data-testid attribute is a good addition for testing purposes.

To improve accessibility, consider adding an aria-label to the checkbox input. You can use the same localization string as the title:

 <input
   aria-label={Locale.Mask.Config.CodeFold.Title}
   type="checkbox"
   checked={config.enableCodeFold}
   data-testid="enable-code-fold-checkbox"
+  aria-label={Locale.Mask.Config.CodeFold.Title}
   onChange={(e) =>
     updateConfig(
       (config) => (config.enableCodeFold = e.currentTarget.checked),
     )
   }
 ></input>
app/components/markdown.tsx (2)

175-176: Use strict inequality operator !== for accurate comparison

Using != false can lead to unexpected results due to type coercion. It's safer to use !== false for strict boolean comparison.

Apply this diff to improve type safety:

- const enableCodeFold =
-   session.mask?.enableCodeFold != false && config.enableCodeFold;
+ const enableCodeFold =
+   session.mask?.enableCodeFold !== false && config.enableCodeFold;

209-209: Consider making the maxHeight value configurable

Hardcoding the value "400px" may reduce flexibility. Consider defining it as a constant or making it configurable to enhance maintainability and adaptability.

Apply this diff to improve the code:

+ const MAX_CODE_FOLD_HEIGHT = "400px";
  ...
  <code
    className={props?.className}
    ref={ref}
    style={{
-     maxHeight: enableCodeFold && collapsed ? "400px" : "none",
+     maxHeight: enableCodeFold && collapsed ? MAX_CODE_FOLD_HEIGHT : "none",
      overflowY: "hidden",
    }}
  >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6792d6e and 8fd843d.

📒 Files selected for processing (4)
  • app/components/markdown.tsx (2 hunks)
  • app/components/settings.tsx (1 hunks)
  • app/locales/cn.ts (1 hunks)
  • app/locales/en.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/locales/cn.ts
  • app/locales/en.ts
🧰 Additional context used

@Dogtiti Dogtiti merged commit d18bd8a into ChatGPTNextWeb:main Oct 11, 2024
1 of 2 checks passed
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.

2 participants