Skip to content

feat: show timerange on chart tooltip#2985

Merged
chronark merged 5 commits intomainfrom
show-timerange-chart-tooltip
Mar 18, 2025
Merged

feat: show timerange on chart tooltip#2985
chronark merged 5 commits intomainfrom
show-timerange-chart-tooltip

Conversation

@ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented Mar 18, 2025

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features
    • Dashboard charts now offer enhanced tooltip labels that display clear time intervals between data points, providing improved context and readability when interacting with charts.
  • Bug Fixes
    • Removed outdated timestamp formatting methods to streamline tooltip label generation across various chart components.

@changeset-bot
Copy link

changeset-bot bot commented Mar 18, 2025

⚠️ No Changeset found

Latest commit: a206bf1

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.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

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

@vercel
Copy link

vercel bot commented Mar 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 3:59pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 3:59pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 3:59pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 3:59pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 18, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This PR updates the tooltip label formatting logic across several chart components. The old function formatTimestampTooltip has been removed and replaced by a new utility, createTimeIntervalFormatter, which formats timestamps based on time intervals. The changes affect log charts, overview charts, and stats charts, while the overall component structure, state, and error handling remain unchanged.

Changes

File(s) Change Summary
apps/dashboard/components/logs/chart/index.tsx, apps/dashboard/components/logs/overview-charts/overview-area-chart.tsx, apps/dashboard/components/logs/overview-charts/overview-bar-chart.tsx, apps/dashboard/components/stats-card/components/chart/stats-chart.tsx Removed import and usage of formatTimestampTooltip; updated tooltip label formatting to use createTimeIntervalFormatter(data)(payload).
apps/dashboard/components/logs/overview-charts/utils.tsx Added a new utility function createTimeIntervalFormatter to generate formatted time interval tooltips.
internal/clickhouse/src/ratelimits.ts Updated SQL query string in createTimeseriesQuery to use ${interval.step} instead of ${intervalUnit} for defining time intervals.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as Chart Component
    participant T as ChartTooltip
    participant F as Formatter (createTimeIntervalFormatter)
    
    U->>C: Hover over chart
    C->>T: Trigger tooltip rendering
    T->>F: Call createTimeIntervalFormatter(data)(payload)
    F-->>T: Return formatted label
    T-->>C: Display tooltip with updated label
Loading

Possibly related PRs

  • unkeyed/unkey#2796: The changes in the main PR are related to those in the retrieved PR as both involve the modification of tooltip label formatting logic to utilize the createTimeIntervalFormatter function instead of formatTimestampTooltip.
  • unkeyed/unkey#2732: The changes in the main PR are related to those in the retrieved PR as both involve the removal of formatTimestampTooltip and the introduction of createTimeIntervalFormatter in the tooltip label formatting logic for chart components.
  • unkeyed/unkey#2984: The changes in the main PR and the retrieved PR both involve the removal of formatTimestampTooltip and the introduction of createTimeIntervalFormatter for formatting tooltip labels, indicating a direct modification to the same functionality in different components.

Suggested labels

Improvement, Needs Approval

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8a96f4 and a206bf1.

📒 Files selected for processing (1)
  • internal/clickhouse/src/ratelimits.ts (1 hunks)

🪧 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.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 18, 2025

Thank you for following the naming conventions for pull request titles! 🙏

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 (6)
apps/dashboard/components/logs/overview-charts/utils.tsx (6)

12-13: Consider using more specific types instead of any

The function parameter tooltipPayload: any[] uses the any type, which bypasses TypeScript's type checking. This can lead to potential runtime errors and makes the code harder to maintain.

-export function createTimeIntervalFormatter(data?: TimeseriesData[]) {
-  return (tooltipPayload: any[]) => {
+export function createTimeIntervalFormatter(data?: TimeseriesData[]) {
+  return (tooltipPayload: Array<{payload?: {originalTimestamp?: number; displayX?: string}}>) => {

15-17: Improve validation to handle edge cases

The validation logic only checks if the first element's payload exists. If tooltipPayload is empty, tooltipPayload[0] would be undefined, leading to a potential runtime error.

-    if (!tooltipPayload?.[0]?.payload) {
+    if (!tooltipPayload?.length || !tooltipPayload[0]?.payload) {
       return "";
     }

19-21: Add type assertions for better safety

These assignments are extracting properties from any type objects. Adding type assertions would make the code more robust.

-    const currentPayload = tooltipPayload[0].payload;
-    const currentTimestamp = currentPayload.originalTimestamp;
-    const currentDisplayX = currentPayload.displayX;
+    const currentPayload = tooltipPayload[0].payload;
+    const currentTimestamp = currentPayload.originalTimestamp as number | undefined;
+    const currentDisplayX = currentPayload.displayX as string | undefined;

34-35: Consider caching timestamp indexes for better performance

Using findIndex inside the tooltip formatter function could be inefficient, especially if this formatter is called frequently during chart interactions. Consider pre-computing a lookup map outside this function.

+export function createTimeIntervalFormatter(data?: TimeseriesData[]) {
+  // Pre-compute a timestamp-to-index lookup map for faster access
+  const timestampToIndexMap = new Map();
+  data?.forEach((item, index) => {
+    if (item?.originalTimestamp) {
+      timestampToIndexMap.set(item.originalTimestamp, index);
+    }
+  });
+
   return (tooltipPayload: any[]) => {
     // ...
     
-    // Find position in the data array
-    const currentIndex = data.findIndex((item) => item?.originalTimestamp === currentTimestamp);
+    // Get position from lookup map
+    const currentIndex = timestampToIndexMap.get(currentTimestamp) ?? -1;

38-54: Reduce code duplication in conditional rendering

The code for rendering just the current timestamp is duplicated in two different conditions. This can be refactored to eliminate redundancy.

-    // If this is the last item or not found, just show current timestamp
-    if (currentIndex === -1 || currentIndex >= data.length - 1) {
-      return (
-        <div>
-          <span className="font-mono text-accent-9 text-xs px-4">{currentDisplayX}</span>
-        </div>
-      );
-    }
-
-    // Get the next point in the sequence
-    const nextPoint = data[currentIndex + 1];
-    if (!nextPoint) {
-      return (
-        <div>
-          <span className="font-mono text-accent-9 text-xs px-4">{currentDisplayX}</span>
-        </div>
-      );
-    }
+    // If this is the last item, not found, or next point doesn't exist
+    if (currentIndex === -1 || currentIndex >= data.length - 1) {
+      return (
+        <div>
+          <span className="font-mono text-accent-9 text-xs px-4">{currentDisplayX}</span>
+        </div>
+      );
+    }
+
+    // Get the next point in the sequence
+    const nextPoint = data[currentIndex + 1];
+    if (!nextPoint) {
+      // This condition should rarely be hit given the previous check
+      return (
+        <div>
+          <span className="font-mono text-accent-9 text-xs px-4">{currentDisplayX}</span>
+        </div>
+      );
+    }

56-60: Extract common rendering logic to a helper function

The pattern of rendering a timestamp into a tooltip appears multiple times. Consider extracting this to reduce repetition.

+  // Helper to render a single timestamp tooltip
+  function renderSingleTimestamp(displayText: string) {
+    return (
+      <div>
+        <span className="font-mono text-accent-9 text-xs px-4">{displayText}</span>
+      </div>
+    );
+  }
+
   // Format the next timestamp
   const nextDisplayX =
     nextPoint.displayX ||
     (nextPoint.originalTimestamp ? formatTimestampTooltip(nextPoint.originalTimestamp) : "");

Then use this helper function in all the places where you're rendering a single timestamp.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2b4258 and dd9cdb0.

📒 Files selected for processing (5)
  • apps/dashboard/components/logs/chart/index.tsx (2 hunks)
  • apps/dashboard/components/logs/overview-charts/overview-area-chart.tsx (3 hunks)
  • apps/dashboard/components/logs/overview-charts/overview-bar-chart.tsx (3 hunks)
  • apps/dashboard/components/logs/overview-charts/utils.tsx (1 hunks)
  • apps/dashboard/components/stats-card/components/chart/stats-chart.tsx (2 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
apps/dashboard/components/stats-card/components/chart/stats-chart.tsx (1)
apps/dashboard/components/logs/overview-charts/utils.tsx (1) (1)
  • createTimeIntervalFormatter (12:70)
apps/dashboard/components/logs/overview-charts/overview-bar-chart.tsx (1)
apps/dashboard/components/logs/overview-charts/utils.tsx (1) (1)
  • createTimeIntervalFormatter (12:70)
apps/dashboard/components/logs/chart/index.tsx (1)
apps/dashboard/components/logs/overview-charts/utils.tsx (1) (1)
  • createTimeIntervalFormatter (12:70)
apps/dashboard/components/logs/overview-charts/overview-area-chart.tsx (1)
apps/dashboard/components/logs/overview-charts/utils.tsx (1) (1)
  • createTimeIntervalFormatter (12:70)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Go API Local / Test
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (10)
apps/dashboard/components/logs/overview-charts/overview-bar-chart.tsx (2)

18-18: Imported new time interval formatter utility.

The createTimeIntervalFormatter utility has been imported from the local utils module to replace the previous timestamp tooltip formatting approach.


245-247: Enhanced tooltip to show time ranges between data points.

The tooltip now displays a time range interval between consecutive data points, which provides more context than the previous single-point timestamp display. This implementation correctly passes the entire data array to the formatter for interval calculation.

The new approach appears more informative as it shows users the time span that each data bar represents, rather than just a single moment in time.

apps/dashboard/components/logs/overview-charts/overview-area-chart.tsx (2)

24-24: Imported new time interval formatter utility.

The createTimeIntervalFormatter utility has been imported from the local utils module to replace the previous timestamp tooltip formatting approach.


242-244: Enhanced tooltip to show time ranges between data points.

The tooltip now displays a time range interval between consecutive data points, which provides more context than the previous single-point timestamp display. This implementation correctly passes the entire data array to the formatter for interval calculation.

This change maintains consistency with the same approach used in the bar chart component, ensuring a uniform user experience across different chart types.

apps/dashboard/components/stats-card/components/chart/stats-chart.tsx (2)

3-3: Imported time interval formatter from logs components.

The createTimeIntervalFormatter is now imported from a shared location in the logs component directory, replacing the previous timestamp tooltip formatter.


100-100: Enhanced tooltip to show time ranges between data points.

The tooltip now displays a time range interval between consecutive data points, providing more context than the previous single-point timestamp display. This implementation correctly passes the entire data array to the formatter for interval calculation.

This change ensures consistency across all chart components in the application, delivering a unified tooltip experience for users when interacting with time-based data.

apps/dashboard/components/logs/chart/index.tsx (3)

14-14: Imported time interval formatter from overview charts utils.

The createTimeIntervalFormatter utility has been imported from the overview charts utils module to replace the previous timestamp tooltip formatting approach.


18-18: Updated import to only include formatTimestampLabel.

The import statement has been updated to only include the formatTimestampLabel function, removing the previously used formatTimestampTooltip function.


187-187: Enhanced tooltip to show time ranges between data points.

The tooltip now displays a time range interval between consecutive data points instead of a single timestamp. This aligns with the PR objective to show timerange on chart tooltips, improving the data context provided to users.

The implementation correctly passes both the required parameters to the formatter function:

  1. The data array necessary for finding adjacent data points
  2. The payload from the tooltip event to identify the current point
apps/dashboard/components/logs/overview-charts/utils.tsx (1)

1-70: Good implementation of the time interval tooltip formatter

Overall, this utility function is well-structured with good error handling and fallbacks. The JSDoc is clear and informative, and the code generally follows a logical flow with appropriate comments explaining each section.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd9cdb0 and f8a96f4.

📒 Files selected for processing (1)
  • internal/clickhouse/src/ratelimits.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Go API Local / Test
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)

@chronark chronark disabled auto-merge March 18, 2025 15:50
@chronark chronark merged commit 29b655e into main Mar 18, 2025
21 of 28 checks passed
@chronark chronark deleted the show-timerange-chart-tooltip branch March 18, 2025 15:50
Copy link
Contributor Author

@chronark check and lemme know

Copy link
Collaborator

ya

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.

2 participants