Skip to content

refactor(web): consolidate duplicated relative-time helpers - #308

Merged
Quick104 merged 3 commits into
mainfrom
refactor/relative-time-helpers
Aug 20, 2026
Merged

Quick104 merged 3 commits into
mainfrom
refactor/relative-time-helpers

Conversation

@Quick104

@Quick104 Quick104 commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

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 formatRelativeTime in web/src/lib/date.ts with 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 like AdminHistoryImport's 24h absolute cutoff). The default absolute renderer is the preference-aware formatDate from lib/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", and AdminUsers' Intl.RelativeTimeFormat version.

Stacked on #304 (base = feat/issue-303-datetime-format-settings) because the absolute-date fallbacks route through the new lib/datetime formatters; retarget to main after #304 merges.

Verification

  • New unit tests for the extended helper (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 lint 0 errors ✓, pnpm run format:check ✓, pnpm run test: 1153 passed; the only 4 failures are the known pre-existing baseline (reproduce on clean origin/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

    • Improved relative-time formatting across administration, settings, playback, task, subtitle, and autoscan screens.
    • Added support for customizable rounding, “just now” labels, absolute-date thresholds, and fallback handling.
    • Dates now transition to absolute formatting after configured periods for clearer context.
  • Bug Fixes

    • Improved handling of missing, invalid, future, and older timestamps.
    • Standardized timestamp display for more consistent results across the application.

@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bd6d4dff-6773-43a7-b6fa-24cc98a1f9dd

📥 Commits

Reviewing files that changed from the base of the PR and between 2dedf3f and 6d4343a.

📒 Files selected for processing (10)
  • web/src/components/admin/deviceOverrides.tsx
  • web/src/components/admin/subtitles/AdminSubtitlesTable.tsx
  • web/src/lib/date.test.ts
  • web/src/lib/date.ts
  • web/src/pages/AdminHistoryImport.tsx
  • web/src/pages/AdminPlaybackHistory.tsx
  • web/src/pages/AdminTasks.tsx
  • web/src/pages/admin/autoscan/SourcesPanel.tsx
  • web/src/pages/settings/HistoryImportSettings.tsx
  • web/src/pages/settings/WatchProvidersSettings.tsx
🚧 Files skipped from review as they are similar to previous changes (8)
  • web/src/pages/AdminHistoryImport.tsx
  • web/src/components/admin/deviceOverrides.tsx
  • web/src/components/admin/subtitles/AdminSubtitlesTable.tsx
  • web/src/pages/settings/HistoryImportSettings.tsx
  • web/src/lib/date.test.ts
  • web/src/pages/admin/autoscan/SourcesPanel.tsx
  • web/src/pages/AdminTasks.tsx
  • web/src/pages/settings/WatchProvidersSettings.tsx

📝 Walkthrough

Walkthrough

The shared formatRelativeTime utility now supports configurable relative-time behavior and absolute-date rendering. Administrative and settings views use it instead of local timestamp calculations. Tests cover rounding, thresholds, labels, invalid inputs, and custom renderers.

Changes

Shared relative-time formatting

Layer / File(s) Summary
Relative-time formatter contract and behavior
web/src/lib/date.ts, web/src/lib/date.test.ts
Adds configurable rounding, labels, absolute-date thresholds, custom renderers, and deterministic tests.
Administrative timestamp adoption
web/src/components/admin/..., web/src/pages/AdminHistoryImport.tsx, web/src/pages/AdminPlaybackHistory.tsx, web/src/pages/AdminTasks.tsx, web/src/pages/admin/autoscan/SourcesPanel.tsx
Replaces local date calculations with shared formatting and preserves view-specific fallbacks and thresholds.
Settings timestamp adoption
web/src/pages/settings/HistoryImportSettings.tsx, web/src/pages/settings/WatchProvidersSettings.tsx
Uses shared relative-time formatting with floor rounding, custom labels, absolute-date thresholds, and existing fallbacks.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the consolidation of duplicated relative-time helpers across the web UI.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/relative-time-helpers

Comment @coderabbitai help to get the list of available commands.

Base automatically changed from feat/issue-303-datetime-format-settings to main July 5, 2026 20:45
@Quick104
Quick104 force-pushed the refactor/relative-time-helpers branch from 6eef2a8 to 68c8fbc Compare July 10, 2026 16:27
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
web/src/hooks/queries/settings.test.tsx (1)

9-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reset apiMock between tests to keep them isolated.

apiMock is module-scoped with no beforeEach reset. toHaveBeenCalledTimes(2) on Line 47 relies on the mock starting at zero, which only holds because test 1 runs first and consumes exactly its two mockImplementationOnce queues. 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 win

Consider centralizing the repeated “floor + Just now + Never” wrapper.

This exact 3-line wrapper (rounding: "floor", justNowLabel: "Just now", ?? "Never") is duplicated verbatim in WatchProvidersSettings.tsx and (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/date so 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 win

Duplicate "day, time" composition also present in AdminMarkerHistory.tsx.

formatTimestamp here rebuilds the same ${monthDay}, ${time} pattern as formatHistoryDate in web/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 to formatRelativeTime/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 win

Duplicate relative-time formatter left un-migrated.

formatRelative here reimplements the same minute/hour/day diff logic this PR consolidates elsewhere. AdminUserDetail.tsx already imports a shared formatRelative from @/components/admin/deviceOverrides for 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 | 🔵 Trivial

Consider a shared "short date + time" helper.

formatHistoryDate here and formatUpcomingDate/formatUpcomingTime in web/src/lib/upcomingEventPresentation.ts both independently compose date.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 into lib/datetime.ts as a formatShortDateTime-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

📥 Commits

Reviewing files that changed from the base of the PR and between 02b6648 and 68c8fbc.

📒 Files selected for processing (45)
  • internal/api/handlers/settings.go
  • internal/api/handlers/settings_registry_test.go
  • web/src/App.tsx
  • web/src/components/AdminCatalogMaintenance.tsx
  • web/src/components/AdminJobHistory.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/admin/deviceOverrides.tsx
  • web/src/components/admin/subtitles/AdminSubtitlesTable.tsx
  • web/src/components/markers/MarkerEditor.tsx
  • web/src/hooks/queries/settings.test.tsx
  • web/src/hooks/queries/settings.ts
  • web/src/hooks/useDateTimeFormat.tsx
  • web/src/lib/date.test.ts
  • web/src/lib/date.ts
  • web/src/lib/datetime.test.ts
  • web/src/lib/datetime.ts
  • web/src/lib/mediaRequests.ts
  • web/src/lib/upcomingEventPresentation.ts
  • web/src/pages/AdminActivity.tsx
  • web/src/pages/AdminApiKeys.tsx
  • web/src/pages/AdminHistoryImport.tsx
  • web/src/pages/AdminLibraries.tsx
  • web/src/pages/AdminLogs.tsx
  • web/src/pages/AdminMarkerHistory.tsx
  • web/src/pages/AdminNodes.tsx
  • web/src/pages/AdminPlaybackHistory.tsx
  • web/src/pages/AdminStats.tsx
  • web/src/pages/AdminTaskDetail.tsx
  • web/src/pages/AdminTasks.tsx
  • web/src/pages/AdminUserDetail.tsx
  • web/src/pages/AdminUsers.tsx
  • web/src/pages/ImportedCollectionEditor.tsx
  • web/src/pages/Notifications.tsx
  • web/src/pages/SettingsLayout.tsx
  • web/src/pages/admin-settings/CompatibilityProxiesSettings.tsx
  • web/src/pages/admin-settings/IntroSettings.tsx
  • web/src/pages/admin-settings/InviteCodesTab.tsx
  • web/src/pages/admin-settings/SearchSettings.tsx
  • web/src/pages/admin/autoscan/ActivityPanel.tsx
  • web/src/pages/admin/autoscan/SourcesPanel.tsx
  • web/src/pages/settings/AppearanceSettings.tsx
  • web/src/pages/settings/HistoryImportSettings.tsx
  • web/src/pages/settings/WatchProvidersSettings.tsx
  • web/src/player/components/PlayingNextScreen.tsx
  • web/src/utils/storage.ts

Comment thread web/src/lib/date.ts Resolved
Comment thread web/src/pages/AdminLogs.tsx Resolved
@Quick104
Quick104 force-pushed the refactor/relative-time-helpers branch from 68c8fbc to ef5c583 Compare July 20, 2026 12:33
Quick104 and others added 2 commits August 3, 2026 09:12
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]>
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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.

@Quick104
Quick104 merged commit d332b54 into main Aug 20, 2026
4 checks passed
@Quick104
Quick104 deleted the refactor/relative-time-helpers branch August 20, 2026 17:13
@zZebrahz zZebrahz mentioned this pull request Sep 27, 2026
10 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant