Repository navigation
refactor(web): consolidate duplicated relative-time helpers - #308
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (10)
🚧 Files skipped from review as they are similar to previous changes (8)
📝 WalkthroughWalkthroughThe shared ChangesShared relative-time formatting
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
6eef2a8 to
68c8fbc
Compare
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
web/src/hooks/queries/settings.test.tsx (1)
9-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReset
apiMockbetween tests to keep them isolated.
apiMockis module-scoped with nobeforeEachreset.toHaveBeenCalledTimes(2)on Line 47 relies on the mock starting at zero, which only holds because test 1 runs first and consumes exactly its twomockImplementationOncequeues. Adding tests or reordering would make call counts and leftover implementations leak across tests.♻️ Add per-test reset
-import { describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const apiMock = vi.hoisted(() => vi.fn()); vi.mock("`@/api/client`", () => ({ api: apiMock })); + +beforeEach(() => { + apiMock.mockReset(); +});🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/hooks/queries/settings.test.tsx` around lines 9 - 10, Reset the hoisted apiMock before each test to isolate call counts and queued implementations. Add a beforeEach in the settings query test suite that clears mock history and restores the default mock behavior, ensuring assertions in each test do not depend on execution order.web/src/pages/admin/autoscan/SourcesPanel.tsx (1)
76-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider centralizing the repeated “floor + Just now + Never” wrapper.
This exact 3-line wrapper (
rounding: "floor",justNowLabel: "Just now",?? "Never") is duplicated verbatim inWatchProvidersSettings.tsxand (per graph context)AdminTasks.tsx. Since this PR's goal is consolidating duplicated relative-time formatters, consider exporting a small preset (e.g.,formatRelativeTimeShort) from@/lib/dateso these call sites don't each redeclare the same options object.♻️ Proposed consolidation
// web/src/lib/date.ts +export function formatRelativeTimeShort( + value: string | null | undefined, + fallback = "Never", +): string { + return formatRelativeTime(value, { rounding: "floor", justNowLabel: "Just now" }) ?? fallback; +}-import { formatRelativeTime as formatRelativeTimeBase } from "`@/lib/date`"; +import { formatRelativeTimeShort } from "`@/lib/date`"; ... -function formatRelativeTime(isoString: string | null): string { - return ( - formatRelativeTimeBase(isoString, { rounding: "floor", justNowLabel: "Just now" }) ?? "Never" - ); -} +const formatRelativeTime = formatRelativeTimeShort;Also applies to: 104-108
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin/autoscan/SourcesPanel.tsx` at line 76, Centralize the repeated short relative-time formatting wrapper by exporting a preset such as formatRelativeTimeShort from the date utility module, configured with floor rounding, “Just now,” and a “Never” fallback. Update the formatter usage in SourcesPanel.tsx, WatchProvidersSettings.tsx, and AdminTasks.tsx to call the shared preset instead of redeclaring the options object.web/src/pages/admin/autoscan/ActivityPanel.tsx (1)
69-69: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate "day, time" composition also present in
AdminMarkerHistory.tsx.
formatTimestamphere rebuilds the same${monthDay}, ${time}pattern asformatHistoryDateinweb/src/pages/AdminMarkerHistory.tsx. Given this PR's goal of consolidating duplicated date/time formatting, consider hoisting this into a small shared helper in@/lib/datetime(similar toformatRelativeTime/formatDateTime).As per coding guidelines, "Keep shared frontend utilities in web/src/lib or web/src/utils."
Also applies to: 77-89
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin/autoscan/ActivityPanel.tsx` at line 69, The date/time composition is duplicated between ActivityPanel’s formatTimestamp and AdminMarkerHistory’s formatHistoryDate. Add a shared helper in "`@/lib/datetime`" for the localized `${monthDay}, ${time}` format, then update both functions to use it and remove their duplicated formatting logic.Source: Coding guidelines
web/src/pages/AdminPlaybackHistory.tsx (1)
434-445: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate relative-time formatter left un-migrated.
formatRelativehere reimplements the same minute/hour/day diff logic this PR consolidates elsewhere.AdminUserDetail.tsxalready imports a sharedformatRelativefrom@/components/admin/deviceOverridesfor the identical "started/updated … ago" use case (see its lines 82-86, 456, 829). Consider replacing this local copy with the shared helper to avoid drift between the two implementations (e.g., differing "just now" thresholds or rounding).♻️ Suggested consolidation
-function formatRelative(value: string) { - const date = new Date(value); - const diff = Date.now() - date.getTime(); - if (Number.isNaN(date.getTime())) return value; - const minutes = Math.max(0, Math.floor(diff / 60_000)); - if (minutes < 1) return "just now"; - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - const days = Math.floor(hours / 24); - return `${days}d ago`; -} +import { formatRelative } from "`@/components/admin/deviceOverrides`";🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/AdminPlaybackHistory.tsx` around lines 434 - 445, Remove the local formatRelative implementation in AdminPlaybackHistory and import the shared formatRelative helper from "`@/components/admin/deviceOverrides`", matching AdminUserDetail’s usage. Update all references in the page to use the shared formatter and remove any now-unused code or imports.web/src/components/markers/MarkerEditor.tsx (1)
23-23: 📐 Maintainability & Code Quality | 🔵 TrivialConsider a shared "short date + time" helper.
formatHistoryDatehere andformatUpcomingDate/formatUpcomingTimeinweb/src/lib/upcomingEventPresentation.tsboth independently composedate.toLocaleDateString(preferredDateLocale(), { month: "short", day: "numeric" })with a time part. Since this PR's goal is de-duplicating relative/absolute-time formatters, this composition could move intolib/datetime.tsas aformatShortDateTime-style helper.
[optional_refactor_only_2_call_sites]Also applies to: 245-250
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/markers/MarkerEditor.tsx` at line 23, Extract the duplicated short date-and-time composition into a shared helper in lib/datetime.ts, such as formatShortDateTime, using preferredDateLocale() and the existing time formatting behavior. Update formatHistoryDate in MarkerEditor.tsx and formatUpcomingDate/formatUpcomingTime in upcomingEventPresentation.ts to call the shared helper while preserving their current output and APIs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/lib/date.ts`:
- Around line 31-48: Update the relative-time calculation in the date formatting
function to derive minutes, hours, and days independently from the raw
millisecond delta rather than from previously rounded values. Preserve the
existing rounding strategy and thresholds, but compute each tier directly from
Date.now() minus date.getTime() to avoid compounded rounding near boundaries.
In `@web/src/pages/AdminLogs.tsx`:
- Around line 24-25: Subscribe the AdminLogs page component to date-format
preference changes by calling useDateTimeFormat() at the component level,
alongside its existing imports and before rendering SheetDescription or
PlaybackSessionSummary, so those formatDateTime consumers re-render when
preferences change.
In `@web/src/pages/settings/AppearanceSettings.tsx`:
- Around line 134-151: Replace the button-based controls in the date and time
format sections of AppearanceSettings with the existing radio-group primitive,
wiring each option as a radio item with the current value and change handler.
Ensure the groups provide roving tabindex and arrow-key navigation while
preserving labels, selected styling, and accessibility attributes.
---
Nitpick comments:
In `@web/src/components/markers/MarkerEditor.tsx`:
- Line 23: Extract the duplicated short date-and-time composition into a shared
helper in lib/datetime.ts, such as formatShortDateTime, using
preferredDateLocale() and the existing time formatting behavior. Update
formatHistoryDate in MarkerEditor.tsx and formatUpcomingDate/formatUpcomingTime
in upcomingEventPresentation.ts to call the shared helper while preserving their
current output and APIs.
In `@web/src/hooks/queries/settings.test.tsx`:
- Around line 9-10: Reset the hoisted apiMock before each test to isolate call
counts and queued implementations. Add a beforeEach in the settings query test
suite that clears mock history and restores the default mock behavior, ensuring
assertions in each test do not depend on execution order.
In `@web/src/pages/admin/autoscan/ActivityPanel.tsx`:
- Line 69: The date/time composition is duplicated between ActivityPanel’s
formatTimestamp and AdminMarkerHistory’s formatHistoryDate. Add a shared helper
in "`@/lib/datetime`" for the localized `${monthDay}, ${time}` format, then update
both functions to use it and remove their duplicated formatting logic.
In `@web/src/pages/admin/autoscan/SourcesPanel.tsx`:
- Line 76: Centralize the repeated short relative-time formatting wrapper by
exporting a preset such as formatRelativeTimeShort from the date utility module,
configured with floor rounding, “Just now,” and a “Never” fallback. Update the
formatter usage in SourcesPanel.tsx, WatchProvidersSettings.tsx, and
AdminTasks.tsx to call the shared preset instead of redeclaring the options
object.
In `@web/src/pages/AdminPlaybackHistory.tsx`:
- Around line 434-445: Remove the local formatRelative implementation in
AdminPlaybackHistory and import the shared formatRelative helper from
"`@/components/admin/deviceOverrides`", matching AdminUserDetail’s usage. Update
all references in the page to use the shared formatter and remove any now-unused
code or imports.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ca81a604-1079-4b30-b8df-5da86eb82844
📒 Files selected for processing (45)
internal/api/handlers/settings.gointernal/api/handlers/settings_registry_test.goweb/src/App.tsxweb/src/components/AdminCatalogMaintenance.tsxweb/src/components/AdminJobHistory.tsxweb/src/components/ItemCard.tsxweb/src/components/admin/deviceOverrides.tsxweb/src/components/admin/subtitles/AdminSubtitlesTable.tsxweb/src/components/markers/MarkerEditor.tsxweb/src/hooks/queries/settings.test.tsxweb/src/hooks/queries/settings.tsweb/src/hooks/useDateTimeFormat.tsxweb/src/lib/date.test.tsweb/src/lib/date.tsweb/src/lib/datetime.test.tsweb/src/lib/datetime.tsweb/src/lib/mediaRequests.tsweb/src/lib/upcomingEventPresentation.tsweb/src/pages/AdminActivity.tsxweb/src/pages/AdminApiKeys.tsxweb/src/pages/AdminHistoryImport.tsxweb/src/pages/AdminLibraries.tsxweb/src/pages/AdminLogs.tsxweb/src/pages/AdminMarkerHistory.tsxweb/src/pages/AdminNodes.tsxweb/src/pages/AdminPlaybackHistory.tsxweb/src/pages/AdminStats.tsxweb/src/pages/AdminTaskDetail.tsxweb/src/pages/AdminTasks.tsxweb/src/pages/AdminUserDetail.tsxweb/src/pages/AdminUsers.tsxweb/src/pages/ImportedCollectionEditor.tsxweb/src/pages/Notifications.tsxweb/src/pages/SettingsLayout.tsxweb/src/pages/admin-settings/CompatibilityProxiesSettings.tsxweb/src/pages/admin-settings/IntroSettings.tsxweb/src/pages/admin-settings/InviteCodesTab.tsxweb/src/pages/admin-settings/SearchSettings.tsxweb/src/pages/admin/autoscan/ActivityPanel.tsxweb/src/pages/admin/autoscan/SourcesPanel.tsxweb/src/pages/settings/AppearanceSettings.tsxweb/src/pages/settings/HistoryImportSettings.tsxweb/src/pages/settings/WatchProvidersSettings.tsxweb/src/player/components/PlayingNextScreen.tsxweb/src/utils/storage.ts
68c8fbc to
ef5c583
Compare
Eight copies of the compact "5m ago / 3h ago" relative-time formatter existed across components and pages, differing only in rounding, "just now" capitalization, absolute-date cutoff, and missing-value fallback. Extend lib/date.ts formatRelativeTime with options for those axes (backwards compatible for existing callers) and convert the duplicates to thin wrappers preserving each call site's exact output. Co-Authored-By: Claude Fable 5 <[email protected]>
…ed helper Address PR review: compute each relative-time tier from the raw millisecond delta instead of the previously rounded coarser tier (89.5 minutes now shows "1h ago", not "2h ago"), with a regression test; and migrate AdminPlaybackHistory's overlooked local formatRelative duplicate to the shared helper. Co-Authored-By: Claude Fable 5 <[email protected]>
ef5c583 to
9ca264c
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
Problem
Eight near-identical copies of the compact "5m ago / 3h ago / 2d ago" relative-time formatter existed across the web UI (
lib/date.ts,deviceOverrides.tsx,AdminSubtitlesTable.tsx,AdminHistoryImport.tsx,AdminTasks.tsx,WatchProvidersSettings.tsx,HistoryImportSettings.tsx,SourcesPanel.tsx), differing only in rounding (round vs floor), "just now" capitalization, when they switch to an absolute date (never / 1d / 7d / 30d), and their missing-value fallback ("—" / "Never" / raw value / null). CLAUDE.md calls this duplication out as a code smell.Approach
Extend the existing
formatRelativeTimeinweb/src/lib/date.tswith an options object covering exactly those four axes (rounding,justNowLabel,absoluteAfterDays,absolute) — backwards compatible for its existing callers — and convert each duplicate to a thin wrapper. Missing-value fallbacks stay at the call sites via?? "—"etc., so every call site's exact output is preserved (verified tier-by-tier against each original, including boundary behavior likeAdminHistoryImport's 24h absolute cutoff). The default absolute renderer is the preference-awareformatDatefromlib/datetime, which is what all the absolute fallbacks already used.Deliberately left alone (genuinely different output shapes, not duplicates):
lib/timeAgo.ts("Added N minutes ago", null after 30d),ImportedCollectionEditor's long-form "5 mins/hours/days/months/years ago", andAdminUsers'Intl.RelativeTimeFormatversion.Stacked on #304 (base =
feat/issue-303-datetime-format-settings) because the absolute-date fallbacks route through the newlib/datetimeformatters; retarget tomainafter #304 merges.Verification
web/src/lib/date.test.ts): tiers, null handling, future timestamps, round-vs-floor boundary, custom just-now label, absolute cutoffs (30d and the 1-day AdminHistoryImport shape), custom absolute renderer — all with fake timers.pnpm run build✓,pnpm run lint0 errors ✓,pnpm run format:check✓,pnpm run test: 1153 passed; the only 4 failures are the known pre-existing baseline (reproduce on cleanorigin/main).Risks & follow-up
Pure web refactor, no API or behavior change. No client (silo-android/silo-apple) impact.
AI-use disclosure
Implemented by Claude Code with human oversight.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes