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

Skip to content

Show a tooltip when hovering over any DateTime #2003

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

Merged
merged 9 commits into from
May 1, 2025

Conversation

samejr
Copy link
Member

@samejr samejr commented May 1, 2025

When hovering over a DateTime anywhere in the app, we now show a tooltip:

  • Always shows local and UTC times + optionally shows the timeZone if manually set
  • Copy the date string in ISO format from the tooltip
  • Shows UTC offset for the local time
  • Optionally set to false if you don't want to show it

CleanShot 2025-05-01 at 07 49 31@2x

CleanShot 2025-05-01 at 07 49 18@2x

Summary by CodeRabbit

  • New Features
    • Introduced a reusable CopyButton component for copying text to the clipboard with customizable appearance and tooltip support.
    • Enhanced the DateTime component to display detailed date-time information in a tooltip, including multiple time zones and copyable ISO timestamps.
  • Refactor
    • Updated ClipboardField and CopyableText components to use shared copy-to-clipboard logic and components for consistency and maintainability.
  • Chores
    • Improved code organization and removed unused code and imports.
    • Reordered exports in the Tooltip component for clarity.

Copy link

changeset-bot bot commented May 1, 2025

⚠️ No Changeset found

Latest commit: bfc887e

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
Contributor

coderabbitai bot commented May 1, 2025

Walkthrough

This update introduces a reusable CopyButton component and a useCopy hook to standardize copy-to-clipboard functionality across the codebase. The ClipboardField and CopyableText components are refactored to delegate clipboard logic to these new utilities, removing their internal copy state management. The DateTime component is enhanced with a tooltip that displays detailed date-time information in multiple time zones, using the new CopyButton for copying ISO timestamps. Minor import and export order adjustments are made in the Tooltip component. No breaking changes are made to existing component signatures.

Changes

File(s) Change Summary
apps/webapp/app/components/primitives/ClipboardField.tsx Refactored to use the new CopyButton component for copy-to-clipboard functionality; removed internal copy state logic and manual timeout; simplified variant configuration and hardcoded input icon container padding; simplified secure input focus/blur state toggling; cleaned up unused imports and removed commented-out code.
apps/webapp/app/components/primitives/CopyButton.tsx Added new CopyButton component supporting customizable appearance, size, tooltip visibility, and button variants; uses useCopy hook for clipboard logic and copied state tracking; renders either an icon-only span or a styled button with dynamic icon toggling based on copy state; supports tooltips showing "Copy" or "Copied!" messages; uses utility functions for conditional class names and flexible styling.
apps/webapp/app/components/primitives/CopyableText.tsx Refactored to use the new useCopy hook for clipboard logic and copied state tracking, removing internal state and direct clipboard API calls; component rendering and event handling remain unchanged.
apps/webapp/app/components/primitives/DateTime.tsx Enhanced to optionally display a detailed tooltip with date-time information in multiple time zones; added optional showTooltip prop (default true); tracks local time zone via state; removed previous formatted string state and effect in favor of direct computation; added new helper formatDateTimeISO for ISO 8601 formatting; introduced internal DateTimeTooltipContent component rendering icon, formatted string, ISO timestamp, and copy button; tooltip shows local UTC offset when applicable; uses CopyButton for copying ISO timestamps; updated imports for icons and UI components used in tooltip; other date-time formatting helpers unchanged.
apps/webapp/app/components/primitives/Tooltip.tsx Reordered import statements: moved InformationCircleIcon import to top, followed by TooltipPrimitive and React; reordered export statement to export SimpleTooltip first, followed by other tooltip components; no functional or behavioral changes.
apps/webapp/app/hooks/useCopy.ts Introduced new useCopy React hook providing reusable clipboard copy functionality with copied state and configurable duration; accepts string value and optional duration; returns a copy function and copied boolean state; copy function writes to clipboard, sets copied state true, and resets it after the specified duration; prevents default and propagation on mouse events when copying.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ClipboardField/CopyableText/DateTime
    participant CopyButton
    participant useCopy Hook
    participant Clipboard API

    User->>ClipboardField/CopyableText/DateTime: Clicks copy button/icon
    ClipboardField/CopyableText/DateTime->>CopyButton: Renders CopyButton with value
    User->>CopyButton: Clicks CopyButton
    CopyButton->>useCopy Hook: Calls copy()
    useCopy Hook->>Clipboard API: navigator.clipboard.writeText(value)
    Clipboard API-->>useCopy Hook: Clipboard updated
    useCopy Hook-->>CopyButton: Sets copied state true, then resets after duration
    CopyButton-->>User: Shows "Copied!" feedback (icon/tooltip)
Loading
sequenceDiagram
    participant User
    participant DateTime
    participant SimpleTooltip
    participant CopyButton
    participant useCopy Hook
    participant Clipboard API

    User->>DateTime: Hovers over date/time
    DateTime->>SimpleTooltip: Renders tooltip with multi-zone info
    User->>CopyButton: Clicks copy icon for ISO timestamp
    CopyButton->>useCopy Hook: Calls copy()
    useCopy Hook->>Clipboard API: navigator.clipboard.writeText(isoString)
    Clipboard API-->>useCopy Hook: Clipboard updated
    useCopy Hook-->>CopyButton: Sets copied state true, then resets
    CopyButton-->>User: Shows "Copied!" feedback
Loading

Poem

🐇
A button to copy, a hook to repeat,
Clipboard magic now feels so neat!
Tooltips with time zones, ISO in tow,
One click to copy, and off you go.
Refactors and helpers, all in a row—
This bunny is happy to see it all flow!
✨📋


📜 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 b8215c6 and bfc887e.

📒 Files selected for processing (1)
  • apps/webapp/app/components/primitives/DateTime.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/components/primitives/DateTime.tsx
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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: 2

🧹 Nitpick comments (2)
apps/webapp/app/hooks/useCopy.ts (1)

1-22: Well-structured React hook for clipboard operations

This new useCopy hook nicely encapsulates copy-to-clipboard functionality with a temporary success state. The implementation is clean and follows React best practices with proper use of useState and useCallback.

Consider adding error handling for clipboard operations, as they can fail due to browser permissions or other issues:

  const copy = useCallback(
    (e?: React.MouseEvent) => {
      if (e) {
        e.preventDefault();
        e.stopPropagation();
      }
-     navigator.clipboard.writeText(value);
-     setCopied(true);
+     navigator.clipboard.writeText(value)
+       .then(() => {
+         setCopied(true);
+       })
+       .catch((err) => {
+         console.error("Failed to copy:", err);
+       });
      setTimeout(() => {
        setCopied(false);
      }, duration);
    },
    [value, duration]
  );

Also, consider adding a cleanup function to clear the timeout if the component unmounts before the timeout completes:

  const copy = useCallback(
    (e?: React.MouseEvent) => {
      if (e) {
        e.preventDefault();
        e.stopPropagation();
      }
      navigator.clipboard.writeText(value);
      setCopied(true);
-     setTimeout(() => {
+     const timeoutId = setTimeout(() => {
        setCopied(false);
      }, duration);
+     return () => clearTimeout(timeoutId);
    },
    [value, duration]
  );
apps/webapp/app/components/primitives/ClipboardField.tsx (1)

94-94: Use optional chaining for safer element access

Use optional chaining for safer code:

- onClick={() => inputIcon.current && inputIcon.current.focus()}
+ onClick={() => inputIcon.current?.focus()}
🧰 Tools
🪛 Biome (1.9.4)

[error] 94-94: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf9460a and b8215c6.

📒 Files selected for processing (6)
  • apps/webapp/app/components/primitives/ClipboardField.tsx (3 hunks)
  • apps/webapp/app/components/primitives/CopyButton.tsx (1 hunks)
  • apps/webapp/app/components/primitives/CopyableText.tsx (1 hunks)
  • apps/webapp/app/components/primitives/DateTime.tsx (4 hunks)
  • apps/webapp/app/components/primitives/Tooltip.tsx (2 hunks)
  • apps/webapp/app/hooks/useCopy.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/webapp/app/components/primitives/CopyableText.tsx (1)
apps/webapp/app/hooks/useCopy.ts (1)
  • useCopy (3-22)
🪛 Biome (1.9.4)
apps/webapp/app/components/primitives/ClipboardField.tsx

[error] 94-94: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (16)
apps/webapp/app/components/primitives/CopyableText.tsx (1)

9-9: Good refactoring to use the shared hook

The component now delegates clipboard functionality to the useCopy hook, which centralizes the logic and makes the component more maintainable.

apps/webapp/app/components/primitives/Tooltip.tsx (1)

1-3: Minor import and export order adjustments

The reordering of imports and exports doesn't affect functionality and appears to be just code style improvements.

Also applies to: 118-118

apps/webapp/app/components/primitives/ClipboardField.tsx (2)

1-4: Good refactoring to use the CopyButton component

The component now delegates clipboard functionality to the CopyButton component, which centralizes the logic and makes the component more maintainable.

Also applies to: 122-129


112-113: Simplified state updates for secure input

The change from functional state updates to direct boolean assignments is appropriate here since the new state doesn't depend on the previous state.

Also applies to: 118-119

apps/webapp/app/components/primitives/CopyButton.tsx (6)

1-6: Good component structure with clear imports and dependencies

The imports are well-organized, bringing in the necessary icons, hooks, and utility functions for the copy functionality.


7-20: Well-defined size configurations with consistent styling

Using a structured object for sizes provides a scalable approach to maintain consistent sizing across different component variants. Good job on the organization here.


22-30: Comprehensive props interface with good type safety

The props definition is well-structured with clear types. Nice work on providing flexibility through optional props with reasonable defaults.


32-42: Effective use of the useCopy hook for state management

The component properly leverages the custom useCopy hook to handle clipboard operations and copied state, removing the need for internal state management.


43-86: Well-implemented conditional rendering for different variants

The component intelligently renders either a styled span or a Button component based on the variant prop, with appropriate styling adjustments for the copied state.


88-99: Clean implementation of optional tooltip with clear user feedback

The tooltip implementation provides excellent user feedback, showing either "Copy" or "Copied!" based on the state. The conditional rendering based on showTooltip is clean and effective.

apps/webapp/app/components/primitives/DateTime.tsx (6)

1-7: Appropriate imports for enhanced tooltip functionality

The new imports support the tooltip feature with appropriate icons for different time zones and the CopyButton component for clipboard operations.


9-26: Good extension of component API with backward compatibility

Adding the showTooltip prop with a default value of true preserves backward compatibility while enabling new functionality.


27-35: Proper detection and handling of user's local timezone

The component correctly detects the user's local timezone using the Intl API and uses it as a fallback when no explicit timezone is provided.


37-62: Well-structured tooltip content with clear time zone differentiation

The tooltip content is organized logically with visual distinction between different time zones using appropriate icons and formatting.


64-79: Clean implementation of conditional rendering for tooltip

The component efficiently handles both tooltip and non-tooltip rendering paths with minimal code duplication.


260-296: Effective implementation of the DateTimeTooltipContent component

The component cleanly encapsulates the rendering of each timezone entry in the tooltip with appropriate styling and layout. The integration with CopyButton for ISO timestamp copying is well-implemented.

Comment on lines +100 to +102
export function formatDateTimeISO(date: Date, timeZone: string): string {
return new Date(date.toLocaleString("en-US", { timeZone })).toISOString();
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve timezone handling in ISO date formatting

The current implementation using toLocaleString() followed by new Date() and toISOString() may lead to inconsistent results across browsers and environments.

Consider a more robust implementation:

-export function formatDateTimeISO(date: Date, timeZone: string): string {
-  return new Date(date.toLocaleString("en-US", { timeZone })).toISOString();
-}
+export function formatDateTimeISO(date: Date, timeZone: string): string {
+  // Get the ISO string in UTC
+  const isoString = date.toISOString();
+  
+  // If timezone is UTC, return as is
+  if (timeZone === "UTC") return isoString;
+  
+  // For other timezones, we need to indicate that the time is in that timezone
+  // This approach keeps the exact same timestamp but indicates the timezone context
+  return isoString;
+}

Alternatively, consider using a specialized library like date-fns-tz or Luxon for more reliable timezone handling.

Committable suggestion skipped: line range outside the PR's diff.

@matt-aitken matt-aitken merged commit 553a035 into main May 1, 2025
11 of 12 checks passed
@matt-aitken matt-aitken deleted the show-tooltip-for-dateTime-component branch May 1, 2025 09:00
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