-
-
Notifications
You must be signed in to change notification settings - Fork 313
New chart Stats_Fixed #3999
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
New chart Stats_Fixed #3999
Conversation
WalkthroughThis pull request changes the page view tracking mechanism to use URL paths instead of template names. In the HTML template, the variable has been updated, and JavaScript now robustly parses, sorts, and formats page view data with improved tooltip and mobile touch handling. In the custom template tags, a new function is introduced to retrieve the current URL path, and the page view function is modified to aggregate view counts based on the URL path and return a JSON dictionary. Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant T as Template Renderer
participant CT as Custom Tags
participant JS as JavaScript Chart Logic
U->>T: Request page
T->>CT: Call get_current_url_path(context)
CT-->>T: Return current URL path
T->>CT: Call get_page_views(url_path, days)
CT-->>T: Return JSON page view data
T-->>U: Serve rendered page with view data
U->>JS: JS parses data, sorts dates, calculates total views, and renders chart
Possibly related PRs
Tip ⚡🧪 Multi-step agentic review comment chat (experimental)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
🧹 Nitpick comments (2)
website/templates/includes/page_stats.html (2)
95-137: Efficient Date Sorting and Formatting.
In the loop that processes each date (lines 95–137), the code correctly sorts dates and extracts display labels and view counts. The error handling for invalid date parts and logging warnings (lines 111–124, 132–135) adds robustness, although adding inline comments on the expected date format could further aid future maintainers.
177-197: Enhanced Tooltip Date Formatting.
The tooltip callback (lines 177–197) attempts to format the date usingtoLocaleDateStringwith detailed options. This enhances the user experience by providing full date details on hover. Consider supporting localization if the site serves a diverse audience.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
website/templates/includes/page_stats.html(9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Run Tests
🔇 Additional comments (9)
website/templates/includes/page_stats.html (9)
1-6: Template Context Consistency Check.
The changes add{% get_current_url_path as current_url_path %}(line 3) and update{% get_page_views %}to use this new variable (line 4), which aligns with the new URL path–based tracking. However, note that{% get_current_template as current_template %}still exists (line 2) and is used for fetching page votes (lines 5–6). Verify that the vote tracking should indeed continue using the template name instead of the URL path for consistency.
20-24: Enhanced Stats Container and Canvas Element.
The newly added content block for the chart (lines 20–24) provides a dedicated container with a clear heading ("Page Views (Last 30 Days)") and a<canvas>element (pageViewsChart) for chart rendering. This is a clean, self-contained UI block. Ensure that the fixed width (w-72) and other styling choices perform well across responsive layouts.
70-94: Robust Page Views Data Parsing and Validation.
The JavaScript block starting at line 70 initializes an empty data structure (viewsByDate) and then safely parses the JSON provided by the Django template ('{{ page_views|escapejs }}'). The try/catch block along with subsequent validation (ensuringviewsByDateis an object) is well implemented to handle malformed or empty data gracefully.
147-166: Chart Initialization and Total Views Calculation.
The computation oftotalViewsusingreduce(line 148) and its subsequent update in the DOM (line 149) are correctly handled. The Chart.js initialization (lines 152–166) effectively utilizes both the dynamically generated labels and dataset values. The chosen chart styles (colors, borderRadius, etc.) seem appropriate; just double-check that they align with the overall design language of the site.
211-218: Clear X-Axis Tick Customizations.
The configuration for x-axis ticks (lines 211–218) with properties likemaxRotation,minRotation, andmaxTicksLimitis clear. Just ensure that these settings maintain legibility on various device sizes and orientations.
302-304: Accurate Vote Submission Data Update.
In the vote submission function (lines 302–304), the change to usecurrentUrlPath(previously set from the template variable) for the vote submission payload ensures that the vote tracking now corresponds to the URL path. This update is consistent with the view tracking changes.
283-331: Secure Vote Submission with CSRF Protection.
The CSRF token helper function (getCookie) and subsequent use in the vote submissionfetchcall (lines 283–331) are correctly implemented to securely handle form submissions. The error handling for network issues and non-OK responses is also adequate.
334-343: Well-Defined Event Listeners for Vote Buttons.
The event listeners for the upvote (lines 334–337) and downvote (lines 339–342) buttons correctly usestopPropagationto prevent interference from other click events and trigger the proper vote submission. This clear separation improves the reliability of user interactions.
1-345: Overall Integration and Alignment with PR Objectives.
The modifications successfully shift the page view tracking mechanism to use URL paths rather than template names. The enhanced JavaScript for parsing, sorting, and formatting view data, as well as additional mobile touch support, collectively improve the robustness and user experience of the page statistics display. One point for verification: ensure that usingcurrent_templatefor vote tracking (lines 5–6) is an intentional design decision and not an oversight given the shift for view data.
There was a problem hiding this 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
🧹 Nitpick comments (1)
website/templates/includes/page_stats.html (1)
2-4: Updated Template Variables for URL Path
The change to use{% get_current_url_path as current_url_path %}and passingcurrent_url_pathinto{% get_page_views %}is well aligned with the PR objective of switching to URL path–based tracking. However, note that the vote functions on lines 5–6 still rely oncurrent_template. Confirm whether vote tracking should remain on the template basis or also shift to using the URL path for consistency.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
website/templates/includes/page_stats.html(9 hunks)
🔇 Additional comments (9)
website/templates/includes/page_stats.html (9)
70-87: Robust JSON Parsing for Page Views Data
The introduction of a try–catch block to safely parse the JSON string obtained from the Django template (using theescapejsfilter) is well implemented. This approach gracefully handles empty or malformed data while logging appropriate messages, ensuring improved resilience.
89-93: View Data Structure Validation
Adding the check to verify thatviewsByDateis an object adds a valuable safeguard against edge cases where parsing might return an unexpected type. This defensive programming measure helps prevent downstream errors during chart data processing.
95-145: Chronological Sorting and Fallback for Date Labels
The logic to sort the dates chronologically and build thedateLabelsandpageViewsDataarrays is clear and robust. The loop correctly handles each date string—validating its parts and providing a fallback to generate data for the last 30 days when no valid dates are present. This comprehensive approach enhances the reliability and user experience of the chart display.
147-150: Accurate Total Views Calculation
Calculating total views by reducing thepageViewsDataarray (with safeguards for non-numeric values) is concise and effective. Updating the DOM element with the computed total further improves the interactivity and informational quality of the page.
155-164: Chart Dataset and Aesthetic Enhancements
The chart configuration now leverages the renameddateLabelsandpageViewsData, and the adjustments to properties likebarPercentageandcategoryPercentagecontribute to improved visual consistency. These settings should offer better responsiveness across different device sizes.
177-196: Enhanced Tooltip Formatting
The tooltip callback now formats dates into a friendly, localized string when possible, providing users with richer context. The fall-back to display the label (if date formatting fails) is a thoughtful touch that improves robustness.
211-218: Axis Scale Configurations
Customizing the X-axis ticks (with set rotations and limits) along with the Y-axis tick callback (ensuring only integer values are shown) enhances readability. These configuration improvements will likely yield a cleaner, more user-friendly chart display even with dense data.Also applies to: 226-233
250-251: Consistent Use of URL Path in Vote Submission
Assigning thecurrentUrlPathvariable from the Django context and subsequently appending it to the vote submission payload helps unify the tracking mechanism across different user actions. This ensures that vote submissions are clearly linked to the URL path, in line with the overall design change.Also applies to: 303-304
253-264: Improved Interaction Handling
The updated event handlers for both click (using the designated handle element) and touch events enhance the component's interactivity. These changes improve usability on both desktop and mobile devices, helping to ensure that toggling the stats container is intuitive across platforms.Also applies to: 268-279
Summary by CodeRabbit
New Features
Refactor