Skip to content

feat(settings): per-user date and time display format settings - #304

Merged
Quick104 merged 5 commits into
mainfrom
feat/issue-303-datetime-format-settings
Jul 5, 2026
Merged

Quick104 merged 5 commits into
mainfrom
feat/issue-303-datetime-format-settings

Conversation

@Quick104

@Quick104 Quick104 commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Dates and clock times render in whatever the browser locale dictates (and in a few places a hardcoded en-US), so international users see ambiguous formats — "05/06/2026" reads as May 6 or June 5 depending on region, and 12h/24h clock is not selectable. Confirmed no date/time format or locale setting exists anywhere in the server or web UI (settings registry, profile fields, user settings, web hooks all checked).

Approach

Per-user setting following the existing ui_theme-style preference pattern, rather than a server-global or profile-column approach — display formatting is a user preference, needs no migration (user_settings is key-value), and stays additive on /api/v1:

  • Server: ui.date_format (auto | DD/MM/YYYY | MM/DD/YYYY | YYYY-MM-DD) and ui.time_format (auto | 12h | 24h) registered as validated user-scoped settings with auto defaults (internal/api/handlers/settings.go). Purely additive; clients can also read them via /settings/effective.
  • Web: new shared formatter module web/src/lib/datetime.ts (module state + subscribe) so plain helpers and components format consistently; DateTimeFormatProvider syncs persisted settings → module state, with localStorage as a pre-resolution warm start only — once the authenticated settings load they are authoritative (missing key = auto), so another user's device-local value can never leak in. A ReactiveAppRoutes wrapper re-renders the routed tree on preference change (a Layout-level subscription can't re-render stable children elements); memoized AdminLogs rows and the out-of-route PlayingNextScreen subscribe directly.
  • UI: "Date & time" section in Settings → Appearance with live preview; searchable via settings search.
  • All ~45 absolute date/time display call sites across ~28 files converted to the shared formatters. auto preserves today's behavior exactly. Deliberately unchanged: calendarWeek.ts calendar header labels (month/weekday names, unambiguous) and month-name fragments under the ISO preference (ISO has no month-name form; they fall back to browser ordering — documented on preferredDateLocale).
  • Shared useSetSetting hardened (benefits all settings): rollback is per-key and guarded against newer optimistic saves; list/detail invalidated on settle. Regression test included.

Verification

  • web: pnpm run build ✓, pnpm run lint 0 errors ✓, pnpm run format:check ✓, pnpm run test: 1145 passed; the only 4 failures (ServerStorageStep ×3, CompatibilityProxiesSettings ×1, ResizeObserver is not defined) reproduce identically on clean origin/main — pre-existing baseline.
  • New tests: web/src/lib/datetime.test.ts (16 cases: pattern/locale/hourCycle mapping, store semantics), web/src/hooks/queries/settings.test.tsx (overlapping same-key mutation rollback), internal/api/handlers/settings_registry_test.go (enum validation + scope).
  • Go: GOWORK=off go build ./internal/... ./cmd/... ✓, go test ./internal/api/handlers/ ok, golangci-lint clean on touched files, make verify-local-paths ✓.

Adversarial review

3 iterations (Codex, --base main). All material findings fixed:

  • Cross-user localStorage fallback → loaded API settings now authoritative, missing keys resolve to auto.
  • Stale-render risk (stable-children bailout made a Layout subscription ineffective — reviewer verified empirically) → ReactiveAppRoutes + direct subscriptions for memo/out-of-route components.
  • Overlapping-save rollback races (both cross-key and same-key) → guarded per-key rollback + settle invalidation, with regression test; fixed exactly per the reviewer's recommendation.
  • Rebutted (deliberate, documented): month-name fragments (e.g. "Fri, Jun 5") keep browser ordering under the ISO preference since ISO has no month-name form and a year-less "06-05" is less readable.

Risks & follow-up

  • Client follow-up: silo-android / silo-apple can adopt ui.date_format/ui.time_format (user-scoped, readable via /settings and /settings/effective) for cross-device consistency; until then they keep platform-locale formatting.
  • Settings are per login account (like ui_theme), not per household profile — matches the issue's "per-user profile" option at the account level; a per-profile split would be a follow-up if wanted.
  • UI change: screenshots still needed — this environment can't run the full stack to capture the new Settings → Appearance section; happy to add on request.
  • Known duplication (pre-existing, out of scope): three near-identical relative-time helpers (lib/date.ts, deviceOverrides.tsx, AdminSubtitlesTable.tsx).

Closes #303

AI-use disclosure

Implemented by Claude Code (issue-to-pr skill) with human oversight; adversarially reviewed by Codex.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added user-selectable date and time display preferences in Appearance, with live preview and persistence.
    • Introduced preference-aware date/time formatting so changes update throughout the app.
  • Bug Fixes

    • Fixed overlapping setting saves to prevent newer values from being overwritten by failed/older requests.
    • Standardized timestamp/date rendering across admin pages, cards, logs, history, notifications, and player screens.
  • Tests

    • Added tests for date/time preference formatting, settings validation, and optimistic update concurrency/rollback behavior.

Quick104 and others added 4 commits July 5, 2026 01:06
Add ui.date_format (auto, DD/MM/YYYY, MM/DD/YYYY, YYYY-MM-DD) and
ui.time_format (auto, 12h, 24h) as validated user-scoped settings, a
shared preference-aware formatter module (web/src/lib/datetime.ts)
synced via DateTimeFormatProvider, a Date & time section in Appearance
settings, and convert all absolute date/time display call sites to the
shared formatters.

Closes #303

Co-Authored-By: Claude Fable 5 <[email protected]>
…ormats

Address adversarial review: once the authenticated settings request
resolves, a missing ui.date_format/ui.time_format key means "auto"
instead of falling back to device-wide localStorage (which could carry
another user's preference), and failed saves roll back through the
query cache. Layout and AdminLayout subscribe to the format store so
all routed pages re-render live when the preference changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
…hanges

ReactiveAppRoutes re-renders the routed page tree when the format
preference changes (a Layout-level subscription cannot re-render stable
children elements); memoized AdminLogs rows and the out-of-route
PlayingNextScreen subscribe directly. useSetSetting now rolls back only
the mutated key on error and invalidates the settings list on settle so
overlapping saves cannot resurrect stale values.

Co-Authored-By: Claude Fable 5 <[email protected]>
Roll back a failed setting save only while its optimistic value is
still current in the cache, invalidate the detail query on settle, and
add a regression test for overlapping same-key mutations.

Co-Authored-By: Claude Fable 5 <[email protected]>
@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: 0c91195e-36fd-45e0-a963-93342863a780

📥 Commits

Reviewing files that changed from the base of the PR and between f0c75c6 and 98458df.

📒 Files selected for processing (4)
  • web/src/hooks/useDateTimeFormat.tsx
  • web/src/lib/datetime.test.ts
  • web/src/lib/datetime.ts
  • web/src/utils/storage.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • web/src/lib/datetime.test.ts
  • web/src/utils/storage.ts
  • web/src/hooks/useDateTimeFormat.tsx
  • web/src/lib/datetime.ts

📝 Walkthrough

Walkthrough

Adds user-scoped date/time format settings on the backend, a shared frontend datetime formatting system and provider, an Appearance settings UI, broad UI timestamp migration to shared helpers, and a concurrency-safe rollback update for settings mutations.

Changes

Date/Time Format Settings Feature

Layer / File(s) Summary
Backend settings registry
internal/api/handlers/settings.go, internal/api/handlers/settings_registry_test.go
Adds ui.date_format and ui.time_format user-scoped settings with "auto" defaults, enum validation, and registry validation tests.
Shared datetime formatting library
web/src/lib/datetime.ts, web/src/lib/datetime.test.ts
Adds preference parsing, a subscribable preference store, locale selection, and formatDate/formatTime/formatDateTime helpers with tests.
Provider state and app wiring
web/src/hooks/useDateTimeFormat.tsx, web/src/utils/storage.ts, web/src/App.tsx
Adds the datetime preference provider/hooks, new storage keys, and app routing wiring that subscribes rendering to preference changes.
Appearance settings UI
web/src/pages/settings/AppearanceSettings.tsx, web/src/pages/SettingsLayout.tsx
Adds date/time format controls with live preview and expands Appearance navigation metadata.
Admin timestamp rendering updates
web/src/components/AdminCatalogMaintenance.tsx, web/src/components/AdminJobHistory.tsx, web/src/components/admin/deviceOverrides.tsx, web/src/components/admin/subtitles/AdminSubtitlesTable.tsx, web/src/components/markers/MarkerEditor.tsx, web/src/pages/Admin*.tsx, web/src/pages/admin-settings/*.tsx, web/src/pages/admin/autoscan/ActivityPanel.tsx
Replaces inline locale formatting with shared datetime helpers across admin views and related UI.
User-facing timestamp rendering updates
web/src/components/ItemCard.tsx, web/src/lib/date.ts, web/src/lib/mediaRequests.ts, web/src/lib/upcomingEventPresentation.ts, web/src/pages/ImportedCollectionEditor.tsx, web/src/pages/Notifications.tsx, web/src/pages/settings/HistoryImportSettings.tsx, web/src/player/components/PlayingNextScreen.tsx
Updates user-facing date/time display logic to use the shared helpers and preferred locale selection.

Settings Mutation Concurrency Fix

Layer / File(s) Summary
Key-specific optimistic rollback
web/src/hooks/queries/settings.ts, web/src/hooks/queries/settings.test.tsx
Stores the attempted optimistic value, rolls back only when the cached value still matches it, invalidates affected queries, and adds overlap/failure tests.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • Silo-Server/silo-server#26: Also changes internal/api/handlers/settings.go and related validation around settings registry entries.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: per-user date and time display format settings.
Linked Issues check ✅ Passed The PR implements user-scoped date/time format choices and applies them across the UI, matching the linked issue.
Out of Scope Changes check ✅ Passed The changes stay focused on date/time formatting, settings UI, and related regression hardening with no clear unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-303-datetime-format-settings

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f0c75c6058

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// whatever this device saw last" — localStorage only bridges the gap until
// the request resolves, and rollback of a failed save flows back through the
// query cache. Local state covers logged-out rendering.
const apiLoaded = loadApiSettings && apiSettings !== undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop using localStorage after settings load fails

When an authenticated GET /settings request errors, React Query leaves apiSettings as undefined, so apiLoaded stays false and the provider keeps using the localStorage warm-start values indefinitely. On a shared browser, if user A stored DD/MM/YYYY locally and user B has no saved preference, any transient settings failure makes user B's session render with A's format instead of the authoritative default auto, contrary to the comment that localStorage only bridges until the request resolves. Treat a settled error as authoritative no preference (or otherwise clear the fallback) rather than continuing to trust device-local state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 98458df. The localStorage warm start is now tagged with the user id that mirrored it (silo-ui-datetime-format-owner) and is ignored when a different user is authenticated — so a failed GET /settings can no longer leak another account's format; it falls back to auto instead. The same-user case keeps the local warm start on transient failures, which is the resilience we want.

@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: 2

🧹 Nitpick comments (9)
web/src/pages/settings/AppearanceSettings.tsx (3)

178-181: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Preview line shows two unlabeled date renderings.

formatDate(previewDate) and formatDate(previewDate, "medium") are shown side by side with only a middle dot separating them, giving no indication of what each represents to the user.

💡 Example clarification
-          <p className="text-muted-foreground text-[13px]">
-            Preview: {formatDate(previewDate)} · {formatDate(previewDate, "medium")} ·{" "}
-            {formatTime(previewDate)}
-          </p>
+          <p className="text-muted-foreground text-[13px]">
+            Preview: {formatDate(previewDate)} ({formatDate(previewDate, "medium")}) ·{" "}
+            {formatTime(previewDate)}
+          </p>
🤖 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/settings/AppearanceSettings.tsx` around lines 178 - 181, The
preview text in AppearanceSettings is ambiguous because it renders two date
formats from formatDate(previewDate) and formatDate(previewDate, "medium")
without labels. Update the Preview line in the AppearanceSettings component to
clearly label each rendered value (or otherwise distinguish them) so users can
tell which format they are seeing, keeping the existing formatDate and
formatTime usage intact.

30-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Clarify why useDateTimeFormat() is called with no destructured value.

Its return is discarded, and dateFormat/timeFormat are already sourced from useDateTimeFormatSettings(). If this call exists purely to subscribe the component to the shared module-level formatter store (so formatDate/formatTime calls in the preview re-render on change), a short comment would help future readers avoid removing it as "dead code."

🤖 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/settings/AppearanceSettings.tsx` at line 30, The standalone
useDateTimeFormat() call in AppearanceSettings is confusing because its return
value is unused while dateFormat and timeFormat come from
useDateTimeFormatSettings(); add a short explanatory comment near this call
clarifying that it intentionally subscribes the component to the shared
formatter store so the preview updates when formatDate/formatTime changes, and
keep the call even though no destructured value is needed.

134-151: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Custom radiogroup lacks keyboard arrow-key navigation.

Per WAI-ARIA APG, a role="radiogroup" should support arrow-key movement between options with a single roving tab stop; here every Button remains individually focusable via Tab and there's no onKeyDown handling for Arrow keys. Mouse and per-button Tab/Enter still work, so this isn't a hard blocker, but it deviates from expected radiogroup keyboard semantics.

Also applies to: 158-175

🤖 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/settings/AppearanceSettings.tsx` around lines 134 - 151, The
custom radiogroup built in AppearanceSettings (the DATE_FORMAT_CHOICES mapping
that renders each Button inside the role="radiogroup" container) does not follow
expected keyboard semantics. Update the radiogroup so only one option is
tabbable at a time and add arrow-key handling on the group or buttons to move
focus and selection between date format options, preserving the existing
aria-checked state and setDateFormat behavior; apply the same fix to the similar
radiogroup block that also renders Buttons.
web/src/hooks/useDateTimeFormat.tsx (1)

93-104: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Context value object recreated every render.

value={{ dateFormat, timeFormat, setDateFormat, setTimeFormat }} is a fresh object on every render of DateTimeFormatProvider, so every consumer of useDateTimeFormatSettings() re-renders whenever the provider re-renders, even if only one field is actually new. Consider useMemo keyed on the four values.

♻️ Suggested tweak
+  const value = useMemo(
+    () => ({ dateFormat, timeFormat, setDateFormat, setTimeFormat }),
+    [dateFormat, timeFormat, setDateFormat, setTimeFormat],
+  );
   return (
-    <DateTimeFormatContext
-      value={{
-        dateFormat,
-        timeFormat,
-        setDateFormat,
-        setTimeFormat,
-      }}
-    >
+    <DateTimeFormatContext value={value}>
       {children}
     </DateTimeFormatContext>
   );
🤖 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/useDateTimeFormat.tsx` around lines 93 - 104, The
DateTimeFormatContext provider in DateTimeFormatProvider recreates its value
object on every render, which forces all useDateTimeFormatSettings consumers to
re-render unnecessarily. Memoize the context value with useMemo using
dateFormat, timeFormat, setDateFormat, and setTimeFormat as dependencies, and
pass the memoized object to DateTimeFormatContext so the value identity stays
stable when nothing changes.
web/src/lib/datetime.test.ts (1)

67-84: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

No coverage for sub-10 hours in 24h mode.

All formatTime fixtures use hour 15, so the leading-zero gap flagged in datetime.ts (formatTime, lines 129-149) isn't caught here. Worth adding a case with an early-morning hour once that's fixed.

🤖 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/lib/datetime.test.ts` around lines 67 - 84, Add a `formatTime` test
that uses an early-morning sample hour in 24h mode, because the current
`datetime.test.ts` cases only cover hour 15 and miss the leading-zero behavior
flagged in `formatTime`. Update the `describe("formatTime")` block to include a
fixture with an hour below 10 and assert the 24h output preserves the
zero-padded hour, alongside the existing `setDateTimeFormatPreferences`
coverage.
web/src/components/ItemCard.tsx (1)

11-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Correct migration, but duplicated helper logic.

The delegation to the shared formatDate is correct. However, this exact formatDate(value) wrapper (DATE_ONLY_PATTERN check + formatPreferredDate(date, "medium") || null) is duplicated verbatim across several other files in this PR (e.g. AdminUserDetail.tsx, AdminApiKeys.tsx, AdminHistoryImport.tsx, AppearanceSettings.tsx, per the provided graph context). Consider hoisting this into @/lib/datetime.ts (e.g. a formatDateOnlyOrDateTime helper) so all call sites share one implementation instead of five near-identical copies.

🤖 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/ItemCard.tsx` around lines 11 - 21, The date formatting
wrapper is duplicated across multiple components, so centralize the
DATE_ONLY_PATTERN check and medium-format fallback into a shared helper in
datetime utilities (for example alongside formatPreferredDate in
`@/lib/datetime`). Update ItemCard and the other duplicated call sites like
AdminUserDetail, AdminApiKeys, AdminHistoryImport, and AppearanceSettings to
call that shared helper instead of keeping near-identical local formatDate
functions.
web/src/components/admin/deviceOverrides.tsx (1)

88-101: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

formatRelative is duplicated across 4 files.

Same implementation exists verbatim in AdminSubtitlesTable.tsx, AdminPlaybackHistory.tsx, and AdminUserDetail.tsx. Now that a shared @/lib/datetime module exists, consider moving this helper there instead of patching each copy independently (as was done here and in the sibling files).

♻️ Proposed consolidation
+// web/src/lib/datetime.ts
+export function formatRelative(iso: string | undefined): string {
+  if (!iso) return "—";
+  const then = new Date(iso).getTime();
+  if (Number.isNaN(then)) return "—";
+  const diff = Date.now() - then;
+  const m = Math.round(diff / 60000);
+  if (m < 1) return "just now";
+  if (m < 60) return `${m}m ago`;
+  const h = Math.round(m / 60);
+  if (h < 24) return `${h}h ago`;
+  const d = Math.round(h / 24);
+  if (d < 30) return `${d}d ago`;
+  return formatDate(iso);
+}

Then import formatRelative from @/lib/datetime in each of the 4 call sites instead of redefining it locally.

As per coding guidelines, "Keep shared frontend utilities in web/src/lib or web/src/utils."

🤖 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/admin/deviceOverrides.tsx` around lines 88 - 101, The
`formatRelative` helper is duplicated in `deviceOverrides.tsx` and the other
admin table/detail components, so it should be centralized. Move the shared
implementation into the existing `@/lib/datetime` module under `web/src/lib`,
then update `formatRelative` call sites in `AdminSubtitlesTable.tsx`,
`AdminPlaybackHistory.tsx`, `AdminUserDetail.tsx`, and `deviceOverrides.tsx` to
import it instead of redefining it locally. Keep the logic unchanged and remove
the duplicated local copies.

Source: Coding guidelines

web/src/components/markers/MarkerEditor.tsx (1)

245-250: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

formatHistoryDate duplicated and drops the year.

This function is copy-pasted verbatim in AdminMarkerHistory.tsx (lines 179-184). Additionally, the date portion only includes month/day — no year — so history entries from a prior year become ambiguous (e.g., "Jun 5" could be this year or last). The shared formatDate(date, "medium") in @/lib/datetime already includes year: "numeric"; consider using that (or extending the shared lib with a "short, with year" variant) instead of reimplementing toLocaleDateString here and in the sibling file.

♻️ Proposed fix (include year, reuse shared formatter)
-function formatHistoryDate(value: string): string {
-  const date = new Date(value);
-  if (Number.isNaN(date.getTime())) return value;
-  const day = date.toLocaleDateString(preferredDateLocale(), { month: "short", day: "numeric" });
-  return `${day}, ${formatTime(date)}`;
-}
+function formatHistoryDate(value: string): string {
+  const date = new Date(value);
+  if (Number.isNaN(date.getTime())) return value;
+  return formatDateTime(date, { dateStyle: "medium" });
+}

Please confirm whether the previous combined toLocaleString(undefined, ...) call included the year — if so this is a display regression rather than an intentional simplification.

🤖 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` around lines 245 - 250,
`formatHistoryDate` in `MarkerEditor` is duplicated in `AdminMarkerHistory` and
currently formats only month/day, which omits the year and makes older entries
ambiguous. Replace the inline `toLocaleDateString` logic with the shared
datetime helper from `@/lib/datetime` (or add a shared “short with year”
variant) and update both `formatHistoryDate` call sites so they reuse the same
formatter. Also verify whether the prior `toLocaleString` behavior included the
year and preserve that display if this is a regression.

Source: Coding guidelines

web/src/pages/admin/autoscan/ActivityPanel.tsx (1)

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

Duplicate formatTimestamp logic across admin pages — consider centralizing in datetime.ts.

This exact "short month/day + hour:minute" composition (including the preferredDateLocale() call) is duplicated verbatim in web/src/pages/admin-settings/CompatibilityProxiesSettings.tsx. Since the shared datetime library already centralizes formatDate/formatTime/formatDateTime, this pattern (medium date without year, no seconds) is a good candidate to extract into web/src/lib/datetime.ts as e.g. formatShortDateTime, so both call sites (and any future ones) share validation and locale logic in one place.

As per coding guidelines, "Keep shared frontend utilities in web/src/lib or web/src/utils."

♻️ Proposed extraction into datetime.ts
+export function formatShortDateTime(
+  value: Date | string | number,
+  timeOptions?: Intl.DateTimeFormatOptions,
+): string {
+  const date = toDate(value);
+  if (!date) {
+    return "";
+  }
+  const day = date.toLocaleDateString(preferredDateLocale(), {
+    month: "short",
+    day: "numeric",
+  });
+  return `${day}, ${formatTime(date, timeOptions ?? { hour: "2-digit" })}`;
+}

Then in ActivityPanel.tsx:

-import { formatTime as formatTimePreferred, preferredDateLocale } from "`@/lib/datetime`";
+import { formatTime as formatTimePreferred, formatShortDateTime } from "`@/lib/datetime`";
...
-function formatTimestamp(value: string | undefined): string {
-  if (!value) return "-";
-  const day = new Date(value).toLocaleDateString(preferredDateLocale(), {
-    month: "short",
-    day: "numeric",
-  });
-  return `${day}, ${formatTimePreferred(value, { hour: "2-digit" })}`;
-}
+function formatTimestamp(value: string | undefined): string {
+  if (!value) return "-";
+  return formatShortDateTime(value);
+}

Also applies to: 82-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 timestamp
formatting in ActivityPanel is duplicated in another admin page, so centralize
it in the shared datetime utility. Extract the “short month/day + hour:minute”
logic that uses preferredDateLocale() into a reusable helper in
web/src/lib/datetime.ts, such as formatShortDateTime, and then update
ActivityPanel to import and use that helper instead of composing the date/time
inline. Make the same switch in CompatibilityProxiesSettings so both call sites
share the single implementation and locale behavior.

Source: Coding guidelines

🤖 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/hooks/useDateTimeFormat.tsx`:
- Around line 45-91: The date/time format can briefly revert because
DateTimeFormatProvider in useDateTimeFormat.tsx reads stale apiSettings before
the optimistic settings update lands. Update the settings mutation flow in
useDateTimeFormat.tsx and the related useSetSetting logic so the query cache is
written with the new DATE_FORMAT_SETTING_KEY/TIME_FORMAT_SETTING_KEY value
before any re-read can occur, preventing the module store from being pushed back
to the old format during save.

In `@web/src/lib/datetime.ts`:
- Around line 129-149: The 24h branch in formatTime is still using hour:
"numeric", so single-digit hours may not be zero-padded in some locales. Update
the formatTime logic to use hour: "2-digit" when preferences.timeFormat is
"24h", while keeping the existing 12h handling and the merged
Intl.DateTimeFormatOptions in place so times render as 09:04 instead of 9:04.

---

Nitpick comments:
In `@web/src/components/admin/deviceOverrides.tsx`:
- Around line 88-101: The `formatRelative` helper is duplicated in
`deviceOverrides.tsx` and the other admin table/detail components, so it should
be centralized. Move the shared implementation into the existing
`@/lib/datetime` module under `web/src/lib`, then update `formatRelative` call
sites in `AdminSubtitlesTable.tsx`, `AdminPlaybackHistory.tsx`,
`AdminUserDetail.tsx`, and `deviceOverrides.tsx` to import it instead of
redefining it locally. Keep the logic unchanged and remove the duplicated local
copies.

In `@web/src/components/ItemCard.tsx`:
- Around line 11-21: The date formatting wrapper is duplicated across multiple
components, so centralize the DATE_ONLY_PATTERN check and medium-format fallback
into a shared helper in datetime utilities (for example alongside
formatPreferredDate in `@/lib/datetime`). Update ItemCard and the other duplicated
call sites like AdminUserDetail, AdminApiKeys, AdminHistoryImport, and
AppearanceSettings to call that shared helper instead of keeping near-identical
local formatDate functions.

In `@web/src/components/markers/MarkerEditor.tsx`:
- Around line 245-250: `formatHistoryDate` in `MarkerEditor` is duplicated in
`AdminMarkerHistory` and currently formats only month/day, which omits the year
and makes older entries ambiguous. Replace the inline `toLocaleDateString` logic
with the shared datetime helper from `@/lib/datetime` (or add a shared “short
with year” variant) and update both `formatHistoryDate` call sites so they reuse
the same formatter. Also verify whether the prior `toLocaleString` behavior
included the year and preserve that display if this is a regression.

In `@web/src/hooks/useDateTimeFormat.tsx`:
- Around line 93-104: The DateTimeFormatContext provider in
DateTimeFormatProvider recreates its value object on every render, which forces
all useDateTimeFormatSettings consumers to re-render unnecessarily. Memoize the
context value with useMemo using dateFormat, timeFormat, setDateFormat, and
setTimeFormat as dependencies, and pass the memoized object to
DateTimeFormatContext so the value identity stays stable when nothing changes.

In `@web/src/lib/datetime.test.ts`:
- Around line 67-84: Add a `formatTime` test that uses an early-morning sample
hour in 24h mode, because the current `datetime.test.ts` cases only cover hour
15 and miss the leading-zero behavior flagged in `formatTime`. Update the
`describe("formatTime")` block to include a fixture with an hour below 10 and
assert the 24h output preserves the zero-padded hour, alongside the existing
`setDateTimeFormatPreferences` coverage.

In `@web/src/pages/admin/autoscan/ActivityPanel.tsx`:
- Line 69: The timestamp formatting in ActivityPanel is duplicated in another
admin page, so centralize it in the shared datetime utility. Extract the “short
month/day + hour:minute” logic that uses preferredDateLocale() into a reusable
helper in web/src/lib/datetime.ts, such as formatShortDateTime, and then update
ActivityPanel to import and use that helper instead of composing the date/time
inline. Make the same switch in CompatibilityProxiesSettings so both call sites
share the single implementation and locale behavior.

In `@web/src/pages/settings/AppearanceSettings.tsx`:
- Around line 178-181: The preview text in AppearanceSettings is ambiguous
because it renders two date formats from formatDate(previewDate) and
formatDate(previewDate, "medium") without labels. Update the Preview line in the
AppearanceSettings component to clearly label each rendered value (or otherwise
distinguish them) so users can tell which format they are seeing, keeping the
existing formatDate and formatTime usage intact.
- Line 30: The standalone useDateTimeFormat() call in AppearanceSettings is
confusing because its return value is unused while dateFormat and timeFormat
come from useDateTimeFormatSettings(); add a short explanatory comment near this
call clarifying that it intentionally subscribes the component to the shared
formatter store so the preview updates when formatDate/formatTime changes, and
keep the call even though no destructured value is needed.
- Around line 134-151: The custom radiogroup built in AppearanceSettings (the
DATE_FORMAT_CHOICES mapping that renders each Button inside the
role="radiogroup" container) does not follow expected keyboard semantics. Update
the radiogroup so only one option is tabbable at a time and add arrow-key
handling on the group or buttons to move focus and selection between date format
options, preserving the existing aria-checked state and setDateFormat behavior;
apply the same fix to the similar radiogroup block that also renders Buttons.
🪄 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: 47056330-d794-46f4-be52-0eb75f1af1e6

📥 Commits

Reviewing files that changed from the base of the PR and between 0d5f44b and f0c75c6.

📒 Files selected for processing (42)
  • 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.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/settings/AppearanceSettings.tsx
  • web/src/pages/settings/HistoryImportSettings.tsx
  • web/src/player/components/PlayingNextScreen.tsx
  • web/src/utils/storage.ts

Comment thread web/src/hooks/useDateTimeFormat.tsx Resolved
Comment thread web/src/lib/datetime.ts Resolved
Address PR review: the localStorage warm start is now tagged with the
user id that mirrored it and is ignored for a different authenticated
user, so a failed settings request can no longer leak another account's
format on a shared browser. The 24h branch of formatTime defaults to
2-digit hours ("09:04") since h23 alone does not guarantee padding in
every locale.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit 932aea1 into main Jul 5, 2026
11 checks passed
@Quick104
Quick104 deleted the feat/issue-303-datetime-format-settings branch July 5, 2026 20:45
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…Server#304)

* feat(settings): per-user date and time display format settings

Add ui.date_format (auto, DD/MM/YYYY, MM/DD/YYYY, YYYY-MM-DD) and
ui.time_format (auto, 12h, 24h) as validated user-scoped settings, a
shared preference-aware formatter module (web/src/lib/datetime.ts)
synced via DateTimeFormatProvider, a Date & time section in Appearance
settings, and convert all absolute date/time display call sites to the
shared formatters.

Closes Silo-Server#303

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): make loaded API settings authoritative for date/time formats

Address adversarial review: once the authenticated settings request
resolves, a missing ui.date_format/ui.time_format key means "auto"
instead of falling back to device-wide localStorage (which could carry
another user's preference), and failed saves roll back through the
query cache. Layout and AdminLayout subscribe to the format store so
all routed pages re-render live when the preference changes.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): reliable re-render and rollback for date/time format changes

ReactiveAppRoutes re-renders the routed page tree when the format
preference changes (a Layout-level subscription cannot re-render stable
children elements); memoized AdminLogs rows and the out-of-route
PlayingNextScreen subscribe directly. useSetSetting now rolls back only
the mutated key on error and invalidates the settings list on settle so
overlapping saves cannot resurrect stale values.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): guard same-key rollback against newer optimistic saves

Roll back a failed setting save only while its optimistic value is
still current in the cache, invalidate the detail query on settle, and
add a regression test for overlapping same-key mutations.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): owner-bind the datetime format warm start, pad 24h hours

Address PR review: the localStorage warm start is now tagged with the
user id that mirrored it and is ignored for a different authenticated
user, so a failed settings request can no longer leak another account's
format on a shared browser. The 24h branch of formatTime defaults to
2-digit hours ("09:04") since h23 alone does not guarantee padding in
every locale.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
@zZebrahz zZebrahz mentioned this pull request Sep 26, 2026
12 tasks done
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.

[v1] Universal date/time format settings (per-server or per-profile)

1 participant