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

refactor: [anchor] rename topOffset and reverse judge condition #2394

Merged
merged 1 commit into from
Oct 25, 2024

Conversation

gimmyhehe
Copy link
Member

@gimmyhehe gimmyhehe commented Oct 25, 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)

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:

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

  • New Features

    • Enhanced anchor link handling and scroll behavior for improved user experience.
  • Bug Fixes

    • Improved logic for determining visibility of anchor links in the viewport.
  • Documentation

    • Updated naming conventions for properties related to anchor offsets for clarity.
  • Chores

    • Consistent property names across various components to streamline functionality.

@gimmyhehe gimmyhehe added bug Something isn't working refactoring Refactoring labels Oct 25, 2024
Copy link

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes in this pull request primarily involve renaming state and property variables related to anchor link management within the renderless and Vue components. The offsetTop variable is consistently renamed to childOffsetTop across various files, affecting internal state handling and calculations for scroll behavior. The updates enhance the clarity of the anchor management system without altering the overall structure or functionality of the components.

Changes

File Path Change Summary
packages/renderless/src/anchor/index.ts Renamed offsetTop to childOffsetTop in setChildOffsetTop and onItersectionObserver functions; updated logic for intersection checks and link clicks.
packages/renderless/src/anchor/vue.ts Renamed offsetTop to childOffsetTop in the state object of the renderless function.
packages/renderless/types/anchor.type.ts Renamed offsetTop to childOffsetTop in the IAnchorState interface.
packages/vue/src/anchor/src/index.ts Renamed topOffset to offsetTop in the anchorProps object.
packages/vue/src/anchor/src/pc.vue Updated props declaration to rename topOffset to offsetTop.

Possibly related PRs

Suggested reviewers

  • zzcr
  • chenxi-20

Poem

🐇 In the garden where anchors sway,
Child offsets lead the way.
Scroll and click, links align,
A smoother path, oh how divine!
With every hop, our joy will grow,
In the world of code, let’s make it flow! 🌼


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.

@github-actions github-actions bot removed the bug Something isn't working label Oct 25, 2024
Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

Copy link

@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)
packages/vue/src/anchor/src/index.ts (1)

36-39: Add JSDoc for the offsetTop property

Consider adding JSDoc documentation to describe the purpose and usage of this property.

+  /**
+   * The top offset value for the anchor positioning
+   * @default 0
+   */
   offsetTop: {
     type: Number,
     default: 0
   }
packages/vue/src/anchor/src/pc.vue (1)

11-11: Consider removing the deprecated onChange event.

The comment indicates that the onChange event was deprecated in v3.12.0 and scheduled for removal in v3.17.0. If we're past v3.17.0, this comment and the deprecated event should be removed.

-  emits: ['linkClick', 'onChange', 'change'], // deprecated v3.12.0废弃,v3.17.0移除onChange 事件
+  emits: ['linkClick', 'change'],
packages/renderless/src/anchor/index.ts (1)

242-242: LGTM! Consider enhancing the inline comment.

The property rename from topOffset to offsetTop is consistent with other changes. However, the comment could be more descriptive.

Consider updating the comment to better explain the fix:

-        props.offsetTop // 修复横向锚点无法滚动到顶部
+        props.offsetTop // Subtracts the offset to ensure proper scroll position for both vertical and horizontal anchors
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d3c8944 and 636884e.

📒 Files selected for processing (5)
  • packages/renderless/src/anchor/index.ts (4 hunks)
  • packages/renderless/src/anchor/vue.ts (1 hunks)
  • packages/renderless/types/anchor.type.ts (1 hunks)
  • packages/vue/src/anchor/src/index.ts (1 hunks)
  • packages/vue/src/anchor/src/pc.vue (1 hunks)
🔇 Additional comments (8)
packages/vue/src/anchor/src/index.ts (1)

36-39: Verify impact of property rename from topOffset to offsetTop

While the rename improves naming consistency, changing prop names is typically considered a breaking change. This contradicts the PR's "no breaking changes" statement.

Let's check for existing usages:

Consider:

  1. Adding a deprecation warning for the old prop name
  2. Supporting both prop names temporarily
  3. Documenting this change in the migration guide
packages/renderless/types/anchor.type.ts (2)

28-28: Consider updating documentation.

Since this is a public interface change, ensure that any associated documentation or API references are updated to reflect the new property name.

Let's check for documentation files that might need updates:

#!/bin/bash
# Description: Look for documentation files that might reference the old property name

echo "Checking documentation files for references to offsetTop..."
fd -e md -e mdx | xargs rg "offsetTop"

28-28: Verify the rename impact across the codebase.

The rename from offsetTop to childOffsetTop in the IAnchorState interface appears to be for better clarity, reflecting its actual usage context. However, since this is an exported interface, we should verify that all consumers have been updated.

Let's verify the rename has been consistently applied:

✅ Verification successful

Property rename is correctly implemented and consistent

The rename from offsetTop to childOffsetTop has been properly implemented across the anchor component's codebase:

  1. The property is defined in the state interface (IAnchorState)
  2. It's used consistently in the implementation files:
    • packages/renderless/src/anchor/index.ts - Used in setChildOffsetTop function
    • packages/renderless/src/anchor/vue.ts - Defined in the state object
  3. The property is internal to the component's state and not exposed in the public API (props)
  4. All references to this state property have been updated

The rename is a safe, non-breaking change as it only affects the internal state management of the anchor component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old property name
# and verify all usages have been updated to the new name.

echo "Checking for any remaining references to state.offsetTop..."
rg -l "state\.offsetTop"

echo "Verifying all references now use state.childOffsetTop..."
rg -l "state\.childOffsetTop"

# Also check for type references
echo "Checking for any TypeScript interface property definitions still using offsetTop..."
ast-grep --pattern 'interface $_ {
  $$$
  offsetTop: $_
  $$$
}'

Length of output: 262


Script:

#!/bin/bash
# Let's try a more focused search approach

# Search for any remaining references to offsetTop
echo "=== Searching for 'offsetTop' references ==="
rg "offsetTop" -l

# Search for new childOffsetTop references
echo -e "\n=== Searching for 'childOffsetTop' references ==="
rg "childOffsetTop" -l

# Search specifically in TypeScript files
echo -e "\n=== Searching in TypeScript files for interface definitions ==="
fd -e ts -e tsx --exec grep -l "offsetTop\|childOffsetTop" {}

Length of output: 2705


Script:

#!/bin/bash
# Let's examine the actual usage context in anchor-related files

echo "=== Checking anchor implementation files ==="
echo -e "\nContent of packages/renderless/src/anchor/index.ts:"
cat packages/renderless/src/anchor/index.ts

echo -e "\nContent of packages/renderless/src/anchor/vue.ts:"
cat packages/renderless/src/anchor/vue.ts

echo -e "\nContent of packages/vue/src/anchor/src/index.ts:"
cat packages/vue/src/anchor/src/index.ts

echo -e "\nContent of packages/vue/src/anchor/src/pc.vue:"
cat packages/vue/src/anchor/src/pc.vue

Length of output: 14353

packages/vue/src/anchor/src/pc.vue (2)

Line range hint 7-54: Implementation looks good!

The component implementation is well-structured with:

  • Clear separation of concerns using the renderless pattern
  • Type-safe implementation with proper TypeScript types
  • Clean and recursive rendering logic for nested links
  • Proper handling of different anchor types

10-10: Verify the property rename direction across the codebase.

There appears to be an inconsistency in the property naming across different parts of the codebase. Let's verify the correct direction of the rename and ensure consistency.

✅ Verification successful

Let me try a different approach with ripgrep since the --type flag didn't work as expected.


Based on the git history and code search results, I can now provide a definitive response about the property rename:

Property rename is correctly implemented from topOffset to offsetTop

The git history shows a clear commit (636884e) that explicitly renames the prop from topOffset to offsetTop. The code search also confirms that offsetTop is now consistently used across the codebase, particularly in the anchor-related functionality. This rename aligns with the PR objectives and maintains consistency with the component's implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the usage of both property names across the codebase
# to determine the correct direction of the rename and ensure consistency

echo "Checking for 'offsetTop' usage:"
rg --type vue --type typescript 'offsetTop' -B 2 -A 2

echo -e "\nChecking for 'topOffset' usage:"
rg --type vue --type typescript 'topOffset' -B 2 -A 2

# Check specifically in anchor-related files
echo -e "\nChecking anchor-specific files:"
fd -e ts -e vue anchor

Length of output: 890


Script:

#!/bin/bash
# Search for both property names in all files, focusing on the actual implementation
echo "Searching for offsetTop usage:"
rg 'offsetTop' -B 2 -A 2

echo -e "\nSearching for topOffset usage:"
rg 'topOffset' -B 2 -A 2

# Also check the git history for this specific file to see the rename direction
echo -e "\nChecking git history for the specific file:"
git log -p packages/vue/src/anchor/src/pc.vue

Length of output: 43616

packages/renderless/src/anchor/vue.ts (1)

57-57: Improved naming clarity with childOffsetTop.

The rename from offsetTop to childOffsetTop provides better clarity about the property's purpose in relation to child elements.

Let's verify consistent renaming across the codebase:

packages/renderless/src/anchor/index.ts (2)

130-130: LGTM! Improved variable naming.

The rename from offsetTop to childOffsetTop better describes the variable's purpose, making the code more self-documenting.


170-177: LGTM! Enhanced intersection detection logic.

The modified condition provides more precise intersection detection by:

  1. Properly accounting for container position
  2. Including both child and parent offsets
  3. Handling boundary cases with the <= operator

Let's verify the intersection logic works correctly with various offset combinations:

Also applies to: 199-203

✅ Verification successful

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

Verified: The enhanced intersection detection logic is correct and well-implemented

The changes improve the accuracy of intersection detection by:

  1. Properly calculating the scroll start position using scrollStartTop = top + childOffsetTop + offsetTop
  2. Using the container's bounding rect to get the correct top position
  3. Maintaining state through observerLinks for proper tracking
  4. Correctly handling hash changes and scroll states

The implementation ensures proper anchor positioning and scrolling behavior while respecting the configured offset values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tests that verify intersection observer behavior
rg -l "IntersectionObserver.*offsetTop" --type ts

Length of output: 51


Script:

#!/bin/bash
# Let's try a broader search for intersection observer tests
rg -l "IntersectionObserver" --type test
rg -l "IntersectionObserver" "**/*test*" --type ts

# Also search for anchor-related tests that might verify this behavior
rg -l "anchor.*test" --type test
rg -l "anchor.*spec" --type test

# Look for actual usage of these offset calculations
rg "scrollStartTop.*childOffsetTop.*offsetTop" --type ts -C 3

Length of output: 965


Script:

#!/bin/bash
# Let's try different search patterns to find tests
fd -e test.ts -e spec.ts

# Search for the actual usage of IntersectionObserver in the codebase
rg "IntersectionObserver" -C 5 --type ts

# Look for anchor-related test files with any extension
fd "anchor" -e test.ts -e spec.ts -e test.js -e spec.js

# Search for offset-related logic in anchor component
rg "offsetTop|childOffsetTop" --type ts -C 3 packages/renderless/src/anchor/

Length of output: 68964


Script:

#!/bin/bash
# Let's examine the intersection observer logic more closely
rg "observerLinks|currentLink" -C 5 packages/renderless/src/anchor/

# Look for any tests related to anchor scrolling behavior
rg -l "anchor.*scroll" examples/sites/demos/pc/app/anchor/

# Check the anchor component's props and state definitions
ast-grep --pattern 'interface $_ {
  $$$
  offsetTop?: $_
  $$$
}'

Length of output: 8015

Copy link

@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 (2)
packages/vue/src/anchor/src/pc.vue (1)

10-10: Document the breaking change in prop name.

The rename from topOffset to offsetTop is a breaking change that should be documented in the changelog or migration guide.

Consider adding a comment above the props declaration to indicate the change:

+ // @breaking-change topOffset prop has been renamed to offsetTop for better DOM terminology alignment
 props: [...props, 'isAffix', 'links', 'containerId', 'markClass', 'type', 'offsetTop'],
packages/renderless/src/anchor/index.ts (1)

242-242: Consider moving the fix documentation to JSDoc

While the change correctly uses the renamed prop, the inline comment about fixing horizontal anchor scrolling would be more valuable as a JSDoc comment above the function.

Consider this documentation improvement:

+/**
+ * Handles anchor link clicks and scrolling
+ * @param {Event} e - Click event
+ * @param {IAnchorLinkItem} item - Anchor item
+ * @note The offsetTop adjustment ensures correct scrolling for both vertical and horizontal anchors
+ */
 export const linkClick = ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d3c8944 and 636884e.

📒 Files selected for processing (5)
  • packages/renderless/src/anchor/index.ts (4 hunks)
  • packages/renderless/src/anchor/vue.ts (1 hunks)
  • packages/renderless/types/anchor.type.ts (1 hunks)
  • packages/vue/src/anchor/src/index.ts (1 hunks)
  • packages/vue/src/anchor/src/pc.vue (1 hunks)
🔇 Additional comments (10)
packages/vue/src/anchor/src/index.ts (1)

36-39: Consider handling this breaking change more gracefully.

While renaming topOffset to offsetTop improves naming consistency, this change could break existing implementations that use the topOffset prop.

Consider:

  1. Supporting both prop names temporarily with topOffset marked as deprecated
  2. Adding proper documentation for this breaking change

Here's a script to check for existing usage:

packages/renderless/types/anchor.type.ts (2)

28-28: LGTM! The new property name is more descriptive.

The rename from offsetTop to childOffsetTop better describes the purpose of this property, making the code more self-documenting.


28-28: Verify consistent property renaming across implementations.

Let's ensure all usages of this state property have been updated to use the new name.

✅ Verification successful

Property childOffsetTop is used consistently in anchor component

Based on the search results, the property childOffsetTop is correctly and consistently used across the anchor component implementation:

  • Type definition in packages/renderless/types/anchor.type.ts
  • Initial state in packages/renderless/src/anchor/vue.ts
  • Usage in scroll calculations in packages/renderless/src/anchor/index.ts

The occurrences of offsetTop found in the codebase are unrelated to this property as they belong to different components or represent DOM element properties.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all references to the old property name have been updated

# Test 1: Search for any remaining references to 'offsetTop'
# Expect: No references in anchor-related files except in comments
echo "Checking for remaining 'offsetTop' references..."
rg -g '!*.md' -g '!*.json' 'offsetTop' packages/

# Test 2: Verify the new property name is used consistently
# Expect: References to 'childOffsetTop' in anchor component files
echo "Checking usage of new 'childOffsetTop' property..."
rg 'childOffsetTop' packages/

Length of output: 9699

packages/vue/src/anchor/src/pc.vue (1)

10-10: Prop rename improves naming consistency but requires attention.

The rename from topOffset to offsetTop better aligns with DOM terminology and improves code clarity.

Let's verify the impact of this change:

✅ Verification successful

Prop rename is safe and properly implemented

The verification shows that:

  1. No occurrences of topOffset exist in the codebase, indicating the rename was complete
  2. The new offsetTop prop is properly used in the anchor component's implementation (packages/vue/src/anchor/src/index.ts and packages/vue/src/anchor/index.ts)
  3. The change is consistent with the component's internal logic where offsetTop is used for scroll calculations and observer margins
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of topOffset in the codebase
rg "topOffset" --type vue --type ts --type js

Length of output: 73


Script:

#!/bin/bash
# Search for any remaining usage of topOffset in all files
rg "topOffset"

# Also search for offsetTop to understand the full scope of changes
rg "offsetTop"

# List all vue files in the anchor directory to understand the component structure
fd -e vue -p "anchor"

Length of output: 10268

packages/renderless/src/anchor/vue.ts (2)

Line range hint 1-96: Excellent code organization and practices!

The overall structure of this renderless component demonstrates several good practices:

  • Strong typing with TypeScript
  • Clear separation of concerns with composable functions
  • Proper reactive handling with watch effects
  • Clean API composition pattern

57-57: LGTM! Verify related component usage.

The rename from offsetTop to childOffsetTop in the state object is consistent with the broader refactoring effort described in the PR. The new name better reflects its purpose in managing child component offsets.

Let's verify the consistency of this rename across the codebase:

packages/renderless/src/anchor/index.ts (4)

130-130: LGTM: Consistent variable renaming

The rename from topOffset to childOffsetTop in the state improves clarity by better describing its purpose - storing the offset of the first child anchor link.


170-173: LGTM: Consistent prop usage

The changes correctly use the renamed props and state variables while maintaining the same rootMargin calculation logic.


176-177: LGTM: Improved intersection check readability

The changes improve the code in two ways:

  1. Consistent use of renamed variables in scrollStartTop calculation
  2. More intuitive intersection condition that's easier to understand

Also applies to: 199-203


Line range hint 1-246: Verify consistent variable renaming across the codebase

Let's ensure all instances of the old variable names have been updated consistently.

✅ Verification successful

No variable renaming inconsistencies found

Based on the search results:

  • No instances of the old variable name topOffset were found in the codebase
  • The new variables offsetTop and childOffsetTop are used consistently in the anchor component and other components where they represent legitimate, separate concepts
  • The changes in the anchor component are self-contained and properly implemented
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of the old variable names
echo "Checking for any remaining instances of 'topOffset'..."
rg "topOffset" --type ts --type vue

echo "Verifying consistent usage of new 'offsetTop' and 'childOffsetTop'..."
rg "offsetTop|childOffsetTop" --type ts --type vue

Length of output: 430


Script:

#!/bin/bash
# Search for any remaining instances of the old variable names
echo "Checking for any remaining instances of 'topOffset'..."
rg "topOffset"

echo "Verifying consistent usage of new 'offsetTop' and 'childOffsetTop'..."
rg "offsetTop|childOffsetTop"

Length of output: 9588

@gimmyhehe gimmyhehe changed the title refactor: rename topOffset and reverse judge condition refactor: [anchor] rename topOffset and reverse judge condition Oct 25, 2024
@zzcr zzcr merged commit 481b4bc into dev Oct 25, 2024
17 of 23 checks passed
@kagol kagol deleted the cgm/refactor-acnhor-offset-top branch November 4, 2024 06:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Refactoring
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants