Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@swaparup36
Copy link
Contributor

@swaparup36 swaparup36 commented Mar 20, 2025

untitled.mp4

It resolves #3897

I just implemented lazy loading of the statistic chart. That reduced the page's loading time. As the calculation and data gathering for the charts is time-consuming, it takes some time to load after the page is rendered as shown in the video.

I am raising this pr again as the previous one was ugly because of lot of unnecessary commits.

Summary by CodeRabbit

  • New Features
    • Introduced a new endpoint that enables access to repository activity data.
    • Enhanced the repository details page to display dynamic, interactive statistics, featuring real-time charts and loading indicators for an improved user experience.
  • Bug Fixes
    • Resolved issues related to static content rendering by implementing dynamic data handling for statistics.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 20, 2025

Walkthrough

This pull request introduces a new API endpoint for fetching repository activity data and updates the repository detail page to load statistics charts dynamically. A new URL pattern is added alongside an associated view function in the backend. Simultaneously, the repository detail HTML template is modified to remove static conditionals and hardcoded values in favor of dynamic data loading with JavaScript functions. These changes enhance the modularity of data fetching and front-end rendering for repository statistics.

Changes

File(s) Change Summary
blt/urls.py Added a new URL pattern repository/<slug:slug>/activity-data/ mapped to repo_activity_data and updated import statements accordingly.
website/views/project.py Introduced new repo_activity_data API endpoint to fetch repository activity data.
website/templates/projects/repo_detail.html Refactored the "Statistics Charts" section to always render with placeholders and loading spinners. Added JavaScript functions (createCharts, updateTrendIndicator, fetchActivityData) to dynamically fetch and update chart data on page load.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant B as Browser
    participant V as View (repo_activity_data)
    participant D as Data Service (RepoDetailView.fetch_activity_data)

    U->>B: Load repository detail page
    B->>B: Trigger DOMContentLoaded event
    B->>B: Execute fetchActivityData() JS function
    B->>V: AJAX GET request to /repository/{slug}/activity-data/
    V->>D: Retrieve activity data using repo slug
    D-->>V: Return activity data JSON
    V-->>B: Send JSON response
    B->>B: Update charts and statistics with received data
Loading

Assessment against linked issues

Objective Addressed Explanation
add statistic charts to the repo detail page (#3897)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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: 1

🧹 Nitpick comments (3)
website/templates/projects/repo_detail.html (3)

410-508: Enhanced Statistics Charts Section with Lazy Loading
The revised HTML segment for the statistics charts cleanly replaces static values with dynamic placeholders and loading spinners. This ensures that users see immediate visual feedback ("Loading...") while the asynchronous data retrieval is in progress. The use of clearly defined IDs (e.g., issue_change_ratio_numbers, pr_change_numbers, commit_change_numbers) facilitates targeted updates once the data is available.

Consider adding ARIA attributes (e.g., aria-busy="true" during loading and aria-busy="false" after updates) to improve accessibility for screen reader users.


1364-1369: Redundant Open/Closed Issue Ratio Calculation
There is an initial calculation and manual insertion of the open/closed issue ratio (lines 1364–1369) before the dynamic update later in the createCharts function. While initializing the ratio early can be useful, the same value is recalculated when the fetched data arrives. Consider consolidating this logic to a single update point or ensuring that both calculations remain synchronized to avoid any discrepancies between the static initial render and the dynamic update.


1372-1517: Dynamic Chart Generation and Trend Indicator Updates
The new JavaScript code efficiently implements lazy loading for the statistics charts. Key strengths include:

  • Proper Cleanup: The functions check for and destroy existing chart instances before creating new ones, preventing duplicate renders and potential memory leaks.
  • Modularity: Separating the chart creation (createCharts(data)), trend indicator updates (updateTrendIndicator(elementId, change, percentage_change)), and data fetching (fetchActivityData()) into distinct functions improves maintainability and readability.
  • Dynamic UI Updates: The logic updates the displayed values (e.g., for issues, pull requests, and commits) and provides trend indicators with directional arrows based on the data changes.

A couple of suggestions:

  • Improve error handling: While errors are logged to the console and an alert is shown, providing a more user-friendly in-page error notification or status message could enhance the user experience.
  • Consider centralizing the open/closed issue ratio update to avoid redundancy with the initial ratio calculation mentioned earlier.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0260d94 and 408411b.

📒 Files selected for processing (3)
  • blt/urls.py (2 hunks)
  • website/templates/projects/repo_detail.html (2 hunks)
  • website/views/project.py (2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
blt/urls.py (1)
website/views/project.py (1) (1)
  • repo_activity_data (52-61)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
blt/urls.py (1)

1098-1098: Good addition of a new API endpoint for repository activity data.

The URL pattern is well structured and follows the existing URL pattern conventions in the application. This new endpoint will facilitate lazy loading of statistic charts as described in the PR objectives.

website/views/project.py (1)

52-61: Clean implementation of the repository activity data endpoint.

The function correctly retrieves repository data by slug and processes it to extract GitHub owner and repository name. This enables the repository detail page to load statistics dynamically.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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 (2)
website/views/project.py (2)

52-61: Implementation of API endpoint to fetch repository activity data.

Good implementation of an API endpoint for fetching repository activity data. This allows the frontend to load the statistics chart asynchronously, which will improve the initial page load time as mentioned in the PR objectives.

Consider adding error handling for malformed repository URLs that might not follow the expected format github.com/owner/repo:

 def repo_activity_data(request, slug):
     """API endpoint for repository activity data"""
     repo = get_object_or_404(Repo, slug=slug)
-    owner_repo = repo.repo_url.rstrip("/").split("github.com/")[-1]
-    owner, repo_name = owner_repo.split("/")
+    try:
+        owner_repo = repo.repo_url.rstrip("/").split("github.com/")[-1]
+        owner, repo_name = owner_repo.split("/")
+    except (IndexError, ValueError):
+        return JsonResponse({"error": "Invalid repository URL format"}, status=400)

     # Get activity data
     activity_data = RepoDetailView().fetch_activity_data(owner, repo_name)

     return JsonResponse(activity_data)

59-59: Consider refactoring to avoid direct instantiation of a view class.

Creating a new instance of RepoDetailView here is unusual since Django views are typically not designed to be instantiated directly. This approach works because fetch_activity_data doesn't depend on the view's lifecycle, but it creates tight coupling.

Consider extracting the fetch_activity_data logic into a separate utility function or service that can be called from both the view and this API endpoint:

 # Get activity data
-activity_data = RepoDetailView().fetch_activity_data(owner, repo_name)
+from website.utils.github import fetch_repository_activity_data
+activity_data = fetch_repository_activity_data(owner, repo_name)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 408411b and 4df96ff.

📒 Files selected for processing (1)
  • website/views/project.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
website/views/project.py (2)
website/models.py (1) (1)
  • Repo (1453-1530)
website/views/repo.py (1) (1)
  • RepoDetailView (140-351)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test

@DonnieBLT DonnieBLT enabled auto-merge (squash) March 20, 2025 23:41
@DonnieBLT DonnieBLT merged commit fefbf5e into OWASP-BLT:main Mar 21, 2025
10 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.

add statistic charts to the repo detail page

2 participants