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

improve dropdown button on timeline #180

Merged
merged 2 commits into from
Nov 4, 2024

Conversation

koilebeit
Copy link

@koilebeit koilebeit commented Nov 4, 2024

Pull request

Proposed changes

fixes #176

Types of changes

  • New feature (non-breaking change which adds functionality).
  • Enhancement (non-breaking change which enhances functionality)
  • Bug Fix (non-breaking change which fixes an issue).
  • Breaking change (fix or feature that would cause existing functionality to change).

Checklist

  • I have read the CONTRIBUTING document.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.

Summary by CodeRabbit

  • New Features

    • Enhanced year navigation on the timeline page, allowing for a broader range of years and improved scrolling functionality.
    • Updated translations for the "years" label to a more action-oriented prompt in multiple languages.
  • Bug Fixes

    • Improved handling of year parts for dropdown items and scrolling behavior.
  • Documentation

    • Updated metadata export fields for better clarity and usability.

These changes collectively improve user interaction with the timeline feature and enhance the overall experience.

Copy link

changeset-bot bot commented Nov 4, 2024

⚠️ No Changeset found

Latest commit: 6afb1ea

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Nov 4, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on enhancing the timeline page's functionality. Key changes include an extensive update to the year navigation settings in _data/theme.yml, adjustments to translation labels in _data/translations.yml, and improved year navigation behavior in _layouts/timeline_edtf.html. The sorting method in _plugins/sort_edtf.rb has also been updated to include numeric representations in its output. These changes collectively aim to improve user interaction with the timeline feature.

Changes

File Change Summary
_data/theme.yml Updated year-navigation to a comprehensive list of years; changed year-nav-increment to 50; specified metadata-export-fields and metadata-facets-fields.
_data/translations.yml Updated translations for "years" label to "Jump to year" in English, Spanish, and German.
_layouts/timeline_edtf.html Modified year navigation logic, added scrollToYear function, and included data-numericyear attribute in <tr> elements.
_plugins/sort_edtf.rb Updated sort_edtf method to change output format to include numeric date representation.

Assessment against linked issues

Objective Addressed Explanation
Improvement of the year dropdown button (#176) The dropdown now offers all years, not just selected ones as requested.

Possibly related PRs

Suggested reviewers

  • mtwente
  • maehr

Poem

Hop, hop, let's celebrate,
With years that now navigate!
From past to future, we can see,
A timeline rich with history.
Jump to year, oh what a cheer,
In every language, loud and clear! 🐇✨


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.

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 (3)
_plugins/sort_edtf.rb (1)

15-15: Consider adding a comment to document the output format.

The string format "display_format:original:numeric" is used as a workaround for Liquid's limitations. Adding a comment would help future maintainers understand the format and its purpose.

+      # Returns an array of strings in format "display_format:original:numeric"
+      # Example: "2024:2024:2024" or "500 v. u. Z.:-0500:-500"
       sorted_dates.map { |date| "#{date[:display_format]}:#{date[:original]}:#{date[:numeric]}" }
_layouts/timeline_edtf.html (2)

55-88: Enhance scrollToYear function with user feedback and performance optimizations.

The implementation is solid but could benefit from some improvements:

Consider these enhancements:

   function scrollToYear(event, year) {
     event.preventDefault();
+    // Debounce scroll events
+    if (this.scrollTimeout) {
+      clearTimeout(this.scrollTimeout);
+    }
 
     // Try to find the exact element with data-numericyear equal to the target year
     let element = document.querySelector(`[data-numericyear="${year}"]`);
 
     // If no exact match, find the nearest year
     if (!element) {
       const yearElements = Array.from(document.querySelectorAll('[data-numericyear]'));
+      if (yearElements.length === 0) {
+        console.warn('No timeline entries found');
+        return;
+      }
 
       // Find the element with the closest data-numericyear value
       let closestElement = null;
       let closestDifference = Infinity;
 
-      yearElements.forEach((el) => {
+      // Cache numeric year to avoid repeated parsing
+      const targetYear = parseInt(year, 10);
+      const years = yearElements.map(el => ({
+        element: el,
+        year: parseInt(el.getAttribute('data-numericyear'), 10)
+      }));
+
+      years.forEach(({ element, year }) => {
-        const elementYear = parseInt(el.getAttribute('data-numericyear'), 10);
-        const difference = Math.abs(elementYear - year);
+        const difference = Math.abs(year - targetYear);
 
         if (difference < closestDifference) {
           closestDifference = difference;
-          closestElement = el;
+          closestElement = element;
         }
       });
 
       element = closestElement;
     }
 
     // Scroll to the found element if it exists
     if (element) {
-      element.scrollIntoView({ behavior: 'smooth' });
+      this.scrollTimeout = setTimeout(() => {
+        element.scrollIntoView({ behavior: 'smooth' });
+        // Highlight the row briefly to show where we scrolled to
+        element.classList.add('highlight-row');
+        setTimeout(() => element.classList.remove('highlight-row'), 2000);
+      }, 100);
     }
   }

Add this CSS to highlight the target row:

.highlight-row {
  animation: highlight 2s ease-out;
}

@keyframes highlight {
  0% { background-color: rgba(255, 255, 0, 0.5); }
  100% { background-color: transparent; }
}

Line range hint 42-119: Overall implementation review.

The changes effectively improve the year dropdown functionality as intended, with good UX considerations like smooth scrolling and finding the nearest year when an exact match isn't found. The implementation is solid but would benefit from the suggested enhancements for validation and user feedback.

Consider adding these architectural improvements:

  1. Add error boundary handling for the JavaScript functionality
  2. Consider implementing virtual scrolling for large datasets
  3. Add aria attributes for better accessibility
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c26c40e and 4e7a397.

📒 Files selected for processing (4)
  • _data/theme.yml (1 hunks)
  • _data/translations.yml (1 hunks)
  • _layouts/timeline_edtf.html (2 hunks)
  • _plugins/sort_edtf.rb (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • _data/translations.yml
🧰 Additional context used
📓 Learnings (1)
_plugins/sort_edtf.rb (2)
Learnt from: koilebeit
PR: Stadt-Geschichte-Basel/forschung.stadtgeschichtebasel.ch#171
File: _plugins/sort_edtf.rb:35-35
Timestamp: 2024-10-29T10:29:13.216Z
Learning: In `_plugins/sort_edtf.rb`, converting EDTF dates to exact numerical values is intentional to enable sorting and rendering of the data.
Learnt from: koilebeit
PR: Stadt-Geschichte-Basel/forschung.stadtgeschichtebasel.ch#171
File: _plugins/sort_edtf.rb:31-38
Timestamp: 2024-10-29T10:30:35.563Z
Learning: Due to Liquid's limitations in handling complex structures like objects, concatenated strings are returned instead, such as in the `sort_edtf` method in `_plugins/sort_edtf.rb`.
🔇 Additional comments (3)
_plugins/sort_edtf.rb (1)

15-15: LGTM! Verify downstream compatibility.

The addition of numeric values to the output format is well-implemented and aligns with the PR objectives for enhancing the year dropdown functionality.

Let's verify that the new format is properly handled in the timeline layout:

✅ Verification successful

The new format is properly handled in the timeline layout

The timeline layout (_layouts/timeline_edtf.html) correctly processes the new three-part format:

  • Line 71: Uses data-numericyear="{{ year[2] }}" to store the numeric value
  • Line 72-73: Uses year[0] for display and year[1] for the ID
  • The numeric year is utilized in the scrollToYear function for precise year navigation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the timeline layout correctly processes the new format
# Expected: Find usage of the numeric year value in the timeline layout

# Test: Search for string splitting operations on sort_edtf output
rg -t html "sort_edtf.*\|.*split.*:" _layouts/

Length of output: 48


Script:

#!/bin/bash
# Let's broaden our search to find any usage of sort_edtf in layouts and includes
rg "sort_edtf" _layouts/ _includes/

Length of output: 115


Script:

#!/bin/bash
# Also search for timeline-related files that might process dates
fd "timeline" --type f --exec rg -l "split|date"

Length of output: 201


Script:

#!/bin/bash
# Check if there are any JavaScript files that might handle the date processing
fd "\.js$" --type f --exec rg -l "split.*:|date"

Length of output: 571


Script:

#!/bin/bash
# Look for Liquid filters or tags that might process these dates
rg "{%.*sort_edtf|{%.*date" _layouts/ _includes/

Length of output: 148


Script:

#!/bin/bash
# Let's examine the timeline_edtf.html layout to see how it processes the sorted dates
cat _layouts/timeline_edtf.html

Length of output: 7049


Script:

#!/bin/bash
# Also check the timeline JavaScript implementation
cat _includes/js/timeline-js.html

Length of output: 786

_layouts/timeline_edtf.html (2)

42-46: Add input validation for year parameter.

While the changes improve the dropdown functionality, the year parameter passed to scrollToYear should be validated to prevent potential issues with invalid inputs.

Consider adding validation:

-          <a class="dropdown-item" href="#" onclick="scrollToYear(event, {{ y }})">{{ y }}</a>
+          {% assign numeric_year = y | plus: 0 %}
+          {% if numeric_year == y %}
+            <a class="dropdown-item" href="#" onclick="scrollToYear(event, {{ y }})">{{ y }}</a>
+          {% else %}
+            <span class="dropdown-item text-muted">Invalid year: {{ y }}</span>
+          {% endif %}

119-119: 🛠️ Refactor suggestion

Add validation for numeric year attribute.

The data-numericyear attribute relies on year[2] without validation. This could lead to invalid attributes if the year array doesn't contain the expected elements.

Add validation:

-      <tr id="y{{ year[1] }}" data-numericyear="{{ year[2] }}">
+      {% assign numeric_year = year[2] | default: year[1] | plus: 0 %}
+      <tr id="y{{ year[1] }}" data-numericyear="{{ numeric_year }}">

Let's verify the year array structure:

_data/theme.yml Show resolved Hide resolved
_data/theme.yml Show resolved Hide resolved
@koilebeit koilebeit requested review from maehr and mtwente November 4, 2024 10:17
@koilebeit koilebeit merged commit a62bf3a into Stadt-Geschichte-Basel:main Nov 4, 2024
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 4, 2024
7 tasks
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.

Improvement of the year dropdown button
2 participants