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

feat: ✨ scroll to target element position when hash in url #24

Merged
merged 3 commits into from
Oct 24, 2024

Conversation

zhumeisongsong
Copy link
Owner

@zhumeisongsong zhumeisongsong commented Oct 24, 2024

image

Summary by CodeRabbit

  • New Features

    • Enhanced the strategic design document for Domain-Driven Design (DDD) with improved organization and clarity.
    • Introduced a scrolling feature in the BodyMarkdown component that navigates to specific sections based on URL hash.
  • Bug Fixes

    • Improved readability and coherence in the strategic design content.

Copy link

coderabbitai bot commented Oct 24, 2024

Warning

Rate limit exceeded

@zhumeisongsong has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 25 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 2ebd61d and 4d43aed.

Walkthrough

The changes include significant structural and content modifications to a markdown document focused on Domain-Driven Design (DDD) and the introduction of a new scrolling behavior in the BodyMarkdown component. The DDD document has been reorganized for consistency and clarity, with enhanced descriptions of strategic design components. The BodyMarkdown component now utilizes a useEffect hook to facilitate scrolling to specific sections based on the URL hash when the HTML content updates.

Changes

File Change Summary
_posts/2024-10-19-DDD2.md Structural and content modifications for clarity and organization; refined sections on Product Vision, Scenario Analysis, Domain Modeling, and Microservices Splitting.
src/app/_components/body-markdown.tsx Introduced a new useEffect hook to scroll to elements based on URL hash when html state updates.

Possibly related PRs

Poem

In a world of design, so grand and bright,
Our DDD shines, a guiding light.
With sections refined, and clarity found,
We hop through the code, where insights abound.
Scroll to the vision, let ideas take flight,
In the realm of DDD, all feels just right! 🐇✨


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.

@zhumeisongsong zhumeisongsong changed the title feat: ✨ scroll to target element position feat: ✨ scroll to target element position when hash in url Oct 24, 2024
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: 2

🧹 Outside diff range and nitpick comments (5)
_posts/2024-10-19-DDD2.md (5)

Line range hint 55-97: Enhance mermaid diagram readability.

The product vision map could be improved by:

  1. Using more descriptive node labels
  2. Adding visual hierarchy through subgraphs
  3. Grouping related concepts

Consider this improved structure:

 graph LR
-A(For) --> B(Age of 6-18)
-C(Their) --> D(Learn knowledge of geography)
-E(This) --> F(Web interactive learning service)
+subgraph Target
+  A[Target Users] --> B[Age of 6-18]
+  C[Learning Focus] --> D[Geography Knowledge]
+end
+
+subgraph Product
+  E[Product Type] --> F[Web Interactive Learning]
+  G[Core Feature] --> H[Quiz Game Format]
+end
 
-G(Is) --> H(Quiz game)
-I(It could) --> J(Take quiz game)
-J --> K(Get real-time feedback on each question)
-K --> L(Receive result of answering the quiz)
-L --> M(Get rewards to be more motivated to improve)
+subgraph Features
+  I[Key Capabilities] --> J[Interactive Quizzes]
+  J --> K[Real-time Feedback]
+  K --> L[Quiz Results]
+  L --> M[Reward System]
+end
 
-N(It's not) --> O(Reading-centered learning with fixed content)
-O --> P(Listening-centered learning with fixed content)
+subgraph Differentiation
+  N[Non-Traditional] --> O[Not Reading-centered]
+  O --> P[Not Listening-centered]
+end
 
-Q(It is) --> R(Dynamic questions generated by AI)
+subgraph Innovation
+  Q[Unique Value] --> R[AI-Generated Dynamic Content]
+end

Line range hint 98-114: Add concrete examples of scenario classifications and dependencies.

While the section effectively introduces scenario analysis and includes visual diagrams, it would benefit from:

  1. Explicit examples of scenario classifications (e.g., "Core Learning Flow", "Reward Flow", etc.)
  2. A table or diagram showing dependencies between subdomains

Consider adding a section like:

Example Scenario Classifications:
1. Core Learning Flow
   - Topic Discovery
   - Quiz Participation
   - Result Analysis
2. Reward Flow
   - Point Accumulation
   - Achievement Unlocking
   - Level Progression

Subdomain Dependencies:
- Quiz Service → Knowledge Management (for question generation)
- Quiz Service → User Service (for progress tracking)
- Reward Service → Quiz Service (for achievement triggers)
🧰 Tools
🪛 LanguageTool

[style] ~96-~96: As an alternative to the over-used intensifier ‘very’, consider replacing this phrase.
Context: ... your system goals and requirements are very clear, this step can be ignored. ### Scenari...

(EN_WEAK_ADJECTIVE)


Line range hint 115-262: Enhance domain model completeness and clarity.

The domain modeling section would benefit from two improvements:

  1. Add essential attributes and methods to entity classes
  2. Clarify the nature of bounded context relationships

For the class diagram, consider adding key attributes and methods:

 classDiagram
 class User Entity{
+  -userId: UUID
+  -profile: UserProfile
   RegisterUserCommand
   UpdateUserProfileCommand
+  +register(email: String, password: String)
+  +updateProfile(profile: UserProfile)
   StartNewQuizCommand
   UserRegisteredEvent
   UserLoggedInEvent
   UserCompletedQuizEvent
 }

For the bounded context diagram, consider adding relationship types:

 graph LR
-A(User Management Context) --> B(Quiz Management Context)
+A(User Management Context) -->|"Provides user data"| B(Quiz Management Context)
-B --> A
+B -->|"Updates learning history"| A

Line range hint 263-350: Add service interaction details and deployment considerations.

The microservices splitting section would benefit from:

  1. API contract examples between services
  2. Deployment and scaling considerations for each service

Consider adding:

  1. Example API contract:
### Service Interaction Examples

Quiz Service → AI Question Generation Service:
```yaml
POST /api/v1/questions/generate
Request:
  topic: string
  difficulty: enum
  userContext: {
    learningLevel: number
    previousTopics: string[]
  }
Response:
  questions: Question[]
  metadata: {
    generationTime: timestamp
    difficultyScore: number
  }
  1. Deployment considerations:
  • AI Question Generation Service: CPU-intensive, requires GPU support
  • Quiz Management Service: Needs horizontal scaling for concurrent users
  • Knowledge Management Service: Cache-heavy, requires Redis/Memcached

---

Line range hint `1-350`: **Consider adding a consistent example throughout the document.**

The document effectively explains DDD strategic design, but could be enhanced by following a single example (e.g., "Geography Quiz Feature") through each section:
- Product Vision: How it fits the target audience
- Scenario Analysis: Specific user journey
- Domain Modeling: Relevant entities and aggregates
- Microservices: Implementation considerations

This would help readers better understand how the concepts connect in practice.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**

<details>
<summary>📥 Commits</summary>

Files that changed from the base of the PR and between 7b65890e80bea3129e4301a0f82af28e2c56863d and 5df59eeae30fb519efc48a14b398f0ab76d64a00.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* _posts/2024-10-19-DDD2.md (4 hunks)
* src/app/_components/body-markdown.tsx (1 hunks)

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>src/app/_components/body-markdown.tsx (2)</summary><blockquote>

Line range hint `37-42`: **LGTM! Proper security measures in place.**

The implementation correctly uses DOMPurify for HTML sanitization and safe DOM access methods.

---

`22-34`: **Verify scroll behavior with router navigation.**

Please ensure the scroll behavior works correctly with:
1. Direct URL access with hash
2. Internal navigation using Next.js router
3. Back/forward browser navigation

<details>
<summary>✅ Verification successful</summary>

Let me try different search patterns and file extensions to gather more information about the routing and navigation implementation.

---

Let's examine the implementation details of the files that handle markdown and scrolling to better understand the integration.

---

Let's check for any client-side navigation components and event handlers that might interact with the scroll behavior.

---

Based on the gathered information, I can now provide a final response about the scroll behavior implementation.

**Hash-based navigation is properly integrated with markdown content**

The implementation is well-integrated with the Next.js application for the following reasons:

1. The `body-markdown.tsx` component correctly handles hash-based scrolling using `scrollIntoView` with smooth behavior
2. The content navigation (`content-navigation.tsx`) properly generates hash-based links (`href="#${heading.id}"`) that correspond to the scroll targets
3. The markdown processing (`markdown-to-html.ts` and `extract-headings.ts`) correctly generates the heading IDs that match the hash-based navigation
4. The implementation works with both direct URL access (through `window.location.hash`) and internal navigation (through Next.js `Link` components)

The scroll behavior will work correctly for all three scenarios mentioned in the review:
- Direct URL access with hash (handled by the useEffect)
- Internal navigation (handled by content-navigation links)
- Browser back/forward (handled by the useEffect watching hash changes)



</details>

<details>
<summary>🏁 Scripts executed</summary>

The following scripts were executed for the analysis:

Script:

```shell
#!/bin/bash
# Check for router implementation and navigation handlers
rg -l "useRouter|Link.*href.*#" --type tsx

Length of output: 72


Script:

#!/bin/bash
# Search for router usage and hash-based navigation with broader patterns
rg -l "useRouter|Link.*href.*#|router\.push|scrollIntoView" --type ts --type jsx --type tsx --type js

# Look for files containing markdown rendering and navigation
fd -e ts -e tsx -e jsx -e js | xargs rg -l "markdown|navigation"

# Search for route definitions and navigation components
fd -e ts -e tsx -e jsx -e js | xargs rg -l "router|navigation|scroll"

Length of output: 680


Script:

#!/bin/bash
# Check the implementation of body-markdown and post-body components
rg -A 5 "scrollIntoView|useEffect.*hash" src/app/_components/body-markdown.tsx src/app/_components/post-body.tsx

# Look for hash-based navigation in page components
rg -A 5 "hash|scroll" src/app/posts/[slug]/page.tsx src/app/page.tsx

# Check markdown processing implementation
rg -A 5 "markdown|html" src/lib/markdown-to-html.ts src/lib/extract-headings.ts

Length of output: 2031


Script:

#!/bin/bash
# Look for Next.js Link components and client-side navigation
rg -A 5 "import.*Link|<Link" src/app/_components/ src/app/posts/ src/app/categories/

# Check for any other scroll-related event handlers
rg -A 5 "onScroll|addEventListener.*scroll|window\.scroll" src/app/

# Look for any layout components that might affect scrolling
rg -A 5 "layout.*tsx|Layout" src/app/

Length of output: 5666

src/app/_components/body-markdown.tsx Outdated Show resolved Hide resolved
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5df59ee and 2ebd61d.

📒 Files selected for processing (1)
  • src/app/_components/body-markdown.tsx (1 hunks)
🔇 Additional comments (1)
src/app/_components/body-markdown.tsx (1)

22-35: 🛠️ Refactor suggestion

Verify scroll timing with content processing.

There's a potential race condition where scrolling might be attempted before the markdown processing and ID addition is complete. Consider adding a check to ensure the target element exists after a short delay.

 useEffect(() => {
   const hash = window.location.hash;
   if (!html || !hash) {
     return;
   }
   const elementId = hash.substring(1);
   const element = document.getElementById(elementId);
 
   if (element) {
-    element.scrollIntoView({
-      behavior: "smooth",
-    });
+    // Add a small delay to ensure content is fully processed
+    requestAnimationFrame(() => {
+      const element = document.getElementById(elementId);
+      if (element) {
+        element.scrollIntoView({
+          behavior: "smooth",
+        });
+      }
+    });
   }
 }, [html, window.location.hash]);

src/app/_components/body-markdown.tsx Outdated Show resolved Hide resolved
@zhumeisongsong zhumeisongsong merged commit b62cd07 into main Oct 24, 2024
5 checks passed
@zhumeisongsong zhumeisongsong deleted the feature/scroll-to-id-position branch October 24, 2024 03:17
@zhumeisongsong
Copy link
Owner Author

🎉 This PR is included in version 1.39.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant