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: time asc add i18n failed #976

Merged
merged 2 commits into from
Dec 31, 2024

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Dec 28, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

【问题描述】

i1n 国际化插件,当使用非时间倒序排序时,点击添加词条按钮,无法添加国际化词条。

【问题分析】

  1. 点击添加词条的时候,会往 langList.value 插入一行数据。
  2. watchEffect 函数同时监听了 langList.value。此时会触发该函数,将新增的数据移除。

【解决方案】
watchEffect 改为 watch,只监听 [fullLangList.value, currentSearchType.value]

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Enhanced language selection filtering and sorting in the internationalization (i18n) plugin panel.
  • Bug Fixes
    • Improved validation for language entry keys, preventing duplicate entries during editing.

Copy link
Contributor

coderabbitai bot commented Dec 28, 2024

Walkthrough

The pull request modifies the Main.vue file in the i18n plugin, focusing on improvements to language entry filtering and sorting logic. The primary changes involve replacing the watchEffect function with a more precise watch function that monitors fullLangList, currentSearchType, and searchKey. Additionally, the validateKey function has been updated to include a new validation rule for checking duplicate keys, specifically when not in edit mode.

Changes

File Change Summary
packages/plugins/i18n/src/Main.vue - Replaced watchEffect with watch for more granular reactivity
- Updated validateKey function with new duplicate key validation rule
- Modified validRules to incorporate new validation logic

Suggested labels

refactor-main

Suggested reviewers

  • chilingling

Possibly related PRs

  • fix: preview compatibility i18n is null #912: This PR addresses an issue related to internationalization (i18n) where the preview functionality encounters a null value, which is directly relevant to the changes made in the main PR that involve filtering and sorting language entries in the i18n plugin panel.
  • fix: optimize bind-i18n styles #925: This PR optimizes styles related to the bind-i18n functionality, which is connected to the overall i18n functionality being enhanced in the main PR, particularly in terms of user interface and experience.

Poem

🐰 In the realm of code, a rabbit's delight,
Watching languages dance with newfound might,
Filtering, sorting, with precision so keen,
Validation rules now clearer than they've been!
A refactor's magic, subtle yet bright 🌟


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3bd94dd and 3492721.

📒 Files selected for processing (1)
  • packages/plugins/i18n/src/Main.vue (2 hunks)
🔇 Additional comments (2)
packages/plugins/i18n/src/Main.vue (2)

126-126: LGTM: Import changes are correct

The addition of watch to the imports is appropriate for the new implementation while maintaining watchEffect for language tracking.


247-256: 🛠️ Refactor suggestion

Optimize watch implementation for better performance

While the current implementation fixes the original issue, there are several opportunities for optimization:

  1. Use the watch callback parameters to avoid unnecessary Vue refs access
  2. Add debouncing for search operations
  3. Only sort when the sort type changes
  4. Cache the regex pattern

Consider this optimized implementation:

-    watch(
-      () => [fullLangList.value, currentSearchType.value, searchKey.value],
-      () => {
-        langList.value = fullLangList.value.filter((item) => {
-          const reg = new RegExp(searchKey.value, 'i')
-          return reg.test(item?.zh_CN) || reg.test(item?.en_US) || reg.test(item?.key)
-        })
-        sortTypeChanges(currentSearchType.value)
-      }
-    )
+    const debouncedFilter = utils.debounce((list, searchTerm) => {
+      const reg = new RegExp(searchTerm, 'i')
+      return list.filter((item) => 
+        reg.test(item?.zh_CN) || reg.test(item?.en_US) || reg.test(item?.key)
+      )
+    }, 300)
+
+    watch(
+      () => [fullLangList.value, currentSearchType.value, searchKey.value],
+      ([list, sortType, searchTerm], oldValues) => {
+        // Only refilter if list or search term changed
+        if (!oldValues || list !== oldValues[0] || searchTerm !== oldValues[2]) {
+          langList.value = debouncedFilter(list, searchTerm)
+        }
+        
+        // Only sort if sort type changed
+        if (!oldValues || sortType !== oldValues[1]) {
+          sortTypeChanges(sortType)
+        }
+      },
+      { immediate: true }
+    )

This optimization:

  • Debounces the expensive filter operation
  • Caches the regex pattern
  • Only sorts when necessary
  • Uses the watch callback parameters efficiently

Likely invalid or redundant comment.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@github-actions github-actions bot added the bug Something isn't working label Dec 28, 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: 1

🧹 Nitpick comments (1)
packages/plugins/i18n/src/Main.vue (1)

247-256: Enhance key validation robustness

While the duplicate key validation is correct, there's room for improvement in the validation logic.

Consider these enhancements:

     const validateKey = (rule, value, callback) => {
+      const trimmedValue = value?.trim()
+      
+      if (!trimmedValue) {
+        callback(new Error('Key cannot be empty or contain only whitespace'))
+        return
+      }
+      
       // 新增模式,需要校验 key 不重复
-      if (!isEditMode.value && fullLangList.value.some(({ key }) => value === key)) {
-        callback(new Error('不可与现有 key 重复'))
+      if (!isEditMode.value && fullLangList.value.some(({ key }) => trimmedValue === key)) {
+        callback(new Error(`Key "${trimmedValue}" already exists. Please use a unique key.`))
         return
       }

       callback()
     }

This enhancement:

  1. Adds whitespace validation
  2. Provides more descriptive error messages
  3. Trims the key value before validation
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f05029 and 3bd94dd.

📒 Files selected for processing (1)
  • packages/plugins/i18n/src/Main.vue (2 hunks)
🔇 Additional comments (2)
packages/plugins/i18n/src/Main.vue (2)

126-126: LGTM: Import changes are appropriate

The addition of the watch import is necessary for the new implementation replacing watchEffect.


247-256: Verify fix for ascending time sort i18n failure

The implementation appears to address the core issue with time-based sorting, but let's verify the fix works as expected.

✅ Verification successful

Let me try a different approach to verify the changes.


Based on the code analysis, I can now provide a final response:

Time-based sorting implementation is correctly fixed

The implementation properly handles ascending time sort by:

  1. Using reverse() for ascending time sort in sortTypeChanges function
  2. Maintaining sort state through the watch callback that triggers on both list and sort type changes
  3. Preserving the sort order when filtering through search

The code shows that:

  • Time-based sorting is handled by the natural order of the list (descending) and reverse() for ascending
  • The sort type changes are properly applied after filtering operations
  • The implementation is simple and efficient, avoiding complex comparisons for timestamps
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of time-based sorting in i18n
# Look for any other time-based sorting implementations that might be affected

# Check for similar sorting patterns in the codebase
echo "Checking for similar time-based sorting patterns..."
rg -l "byTimeAsc|sortByTime|timeAsc" --type vue

# Look for any related test files
echo "Checking for related test files..."
fd -e spec.js -e test.js -e spec.ts -e test.ts . | rg -i "i18n|sort|time"

# Check for any related issues or PRs
echo "Checking for related issues..."
gh issue list --search "i18n sort time in:title,body"

Length of output: 472


Script:

#!/bin/bash
# Search for sorting-related code in the i18n plugin
echo "Checking for sorting implementations in i18n plugin..."
rg "sort" packages/plugins/i18n/

# Look for the sortTypeChanges function implementation
echo -e "\nChecking for sortTypeChanges implementation..."
ast-grep --pattern 'const sortTypeChanges = $_'

# Check for time-related sorting tests or specs
echo -e "\nChecking for time-related test files..."
fd -e spec -e test . packages/plugins/i18n/

# Check the complete Main.vue file to understand the context
echo -e "\nChecking Main.vue content..."
cat packages/plugins/i18n/src/Main.vue

Length of output: 18196

packages/plugins/i18n/src/Main.vue Outdated Show resolved Hide resolved
@hexqi hexqi merged commit 702357b into opentiny:release/v2.1.0 Dec 31, 2024
2 checks passed
chilingling added a commit that referenced this pull request Jan 3, 2025
* fix: time asc add i18n failed

* fix: search invalid

---------

Co-authored-by: hexqi <wu_12556@126.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants