Modern Apps git

← Modern-Apps.git

library: relative-age formatting in :library:format

Commit
3d6ea49ae2674a03dfb4e353c74c93f5b753b005
Author
Vayun Mathur <[email protected]>
When
2026-11-25 20:10 UTC (10 days ago)
Parents
a80af3c
New opt-in library/format module owns relative-age bucketing and the shared "<n>m ago" wording (RelativeAge + formatRelativeAge, pure, no Android/Compose). news ArticleRow, games/hub FormatUtils, and madeveloper DevPresentation now delegate their bucketing to it while keeping app-specific labels, parsing, and date fallbacks at the call site; each consumer gains only the :library:format dependency.

Verified by the implementing agent: :library:format, :news, :madeveloper, and :games:hub unit tests all pass (5/65/55/44) and library lint is clean.

Diff

games/hub/build.gradle.kts
diff --git a/games/hub/build.gradle.kts b/games/hub/build.gradle.ktsindex aa3d495d34..d8fdb4cdea 100644--- a/games/hub/build.gradle.kts+++ b/games/hub/build.gradle.kts@@ -60,6 +60,7 @@ rustNativeTests {  dependencies {     implementation(project(":library"))+    implementation(project(":library:format"))     implementation(project(":library:ui"))     implementation(project(":library:room"))     implementation(project(":library:avatar"))
games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.ktindex fa2c5aea2d..003894ffa4 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt@@ -2,6 +2,7 @@ package com.vayunmathur.games.hub.util  import kotlin.time.Duration.Companion.milliseconds import androidx.compose.ui.graphics.Color+import com.vayunmathur.library.format.formatRelativeAge  fun formatPlaytime(ms: Long): String {     if (ms <= 0) return "0m"@@ -27,18 +28,23 @@ fun formatDurationMs(ms: Long): String { }  fun formatRelativeTime(timestamp: Long, now: Long = System.currentTimeMillis()): String {-    val diff = now - timestamp-    if (diff < 0) return "now"-    val minutes = diff.milliseconds.inWholeMinutes-    val hours = diff.milliseconds.inWholeHours-    val days = diff.milliseconds.inWholeDays-    return when {-        minutes < 1 -> "just now"-        minutes < MINUTES_PER_HOUR -> "${minutes}m ago"-        hours < HOURS_PER_DAY -> "${hours}h ago"-        days < DAYS_PER_WEEK -> "${days}d ago"-        else -> java.text.SimpleDateFormat("MMM d", java.util.Locale.getDefault()).format(java.util.Date(timestamp))+    // A non-positive timestamp took the date fallback before centralization+    // (it is far past the week band), so keep that instead of the shared+    // unknown-label.+    if (timestamp <= 0L) {+        return java.text.SimpleDateFormat("MMM d", java.util.Locale.getDefault())+            .format(java.util.Date(timestamp))     }+    return formatRelativeAge(+        atMillis = timestamp,+        nowMillis = now,+        futureLabel = "now",+        maxDays = DAYS_PER_WEEK.toLong(),+        olderLabel = { atMillis ->+            java.text.SimpleDateFormat("MMM d", java.util.Locale.getDefault())+                .format(java.util.Date(atMillis))+        },+    ) }  fun tierColor(tier: String): Color = when (tier.uppercase()) {@@ -49,7 +55,6 @@ fun tierColor(tier: String): Color = when (tier.uppercase()) { }  private const val MINUTES_PER_HOUR = 60-private const val HOURS_PER_DAY = 24 private const val DAYS_PER_WEEK = 7  private const val PLATINUM_ARGB = 0xFF9C27B0
library/format/build.gradle.kts
diff --git a/library/format/build.gradle.kts b/library/format/build.gradle.ktsnew file mode 100644index 0000000000..044daa4976--- /dev/null+++ b/library/format/build.gradle.kts@@ -0,0 +1,12 @@+plugins {+    id("common-conventions-library")+}++// Pure display formatting of relative ages ("5m ago"): bucketing a timestamp+// into just-now / minutes / hours / days / older. No Android, Compose, or+// resource access in the API surface used by unit tests, so consumers keep+// their own wording (labels, date fallback) and this module stays opt-in:+// only apps that format a relative age depend on it, unlike :library (the+// grandfathered base every app inherits) or :library:ui's DateString, which+// deliberately covers calendar dates/clock times only and excludes elapsed+// and relative time.
library/format/src/main/AndroidManifest.xml
diff --git a/library/format/src/main/AndroidManifest.xml b/library/format/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..b2d3ea1235--- /dev/null+++ b/library/format/src/main/AndroidManifest.xml@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
library/format/src/main/java/com/vayunmathur/library/format/RelativeAge.kt
diff --git a/library/format/src/main/java/com/vayunmathur/library/format/RelativeAge.kt b/library/format/src/main/java/com/vayunmathur/library/format/RelativeAge.ktnew file mode 100644index 0000000000..af5e3c04cd--- /dev/null+++ b/library/format/src/main/java/com/vayunmathur/library/format/RelativeAge.kt@@ -0,0 +1,96 @@+package com.vayunmathur.library.format++/**+ * Which relative-age bucket a timestamp falls in, without any wording.+ *+ * Calendar dates and clock times live in `library:ui`'s `DateString`, which+ * deliberately excludes relative time. The bucketing below was previously+ * re-derived per app (news feed rows, games-hub activity, madeveloper commit+ * lists, the find-family watch) with the same minute/hour/day thresholds and+ * only the labels and the older-than-a-week fallback differing. Apps keep+ * those labels and fallbacks; the thresholds now live in one place.+ */+sealed interface RelativeAge {+    /** No usable timestamp (`atMillis <= 0`). */+    data object Unknown : RelativeAge++    /** Timestamp is after [nowMillis][relativeAge]. */+    data object Future : RelativeAge++    /** Less than a minute old. */+    data object JustNow : RelativeAge++    /** [amount] whole minutes old, 1..59. */+    data class Minutes(val amount: Long) : RelativeAge++    /** [amount] whole hours old, 1..23. */+    data class Hours(val amount: Long) : RelativeAge++    /** [amount] whole days old, at least 1 and under the caller's [maxDays]. */+    data class Days(val amount: Long) : RelativeAge++    /** At least [maxDays] days old; the caller renders its own fallback. */+    data object Older : RelativeAge+}++private const val MILLIS_PER_MINUTE = 60_000L+private const val MILLIS_PER_HOUR = 3_600_000L+private const val MILLIS_PER_DAY = 86_400_000L+private const val MINUTES_PER_HOUR = 60L+private const val HOURS_PER_DAY = 24L++/**+ * Buckets [atMillis] relative to [nowMillis].+ *+ * A non-positive [atMillis] is [RelativeAge.Unknown], a future timestamp is+ * [RelativeAge.Future] (callers that clamped instead of branching get the+ * same text by mapping both to their just-now label), and ages of at least+ * [maxDays] days are [RelativeAge.Older]. The default [maxDays] never+ * triggers, so day counts are unbounded unless a caller opts into a+ * date fallback.+ */+fun relativeAge(atMillis: Long, nowMillis: Long, maxDays: Long = Long.MAX_VALUE): RelativeAge {+    if (atMillis <= 0L) return RelativeAge.Unknown+    val ageMillis = nowMillis - atMillis+    if (ageMillis < 0L) return RelativeAge.Future+    val minutes = ageMillis / MILLIS_PER_MINUTE+    val hours = ageMillis / MILLIS_PER_HOUR+    val days = ageMillis / MILLIS_PER_DAY+    return when {+        minutes < 1L -> RelativeAge.JustNow+        minutes < MINUTES_PER_HOUR -> RelativeAge.Minutes(minutes)+        hours < HOURS_PER_DAY -> RelativeAge.Hours(hours)+        days >= maxDays -> RelativeAge.Older+        else -> RelativeAge.Days(days)+    }+}++/**+ * The shared `"<amount>m ago"` / `"<amount>h ago"` / `"<amount>d ago"` wording.+ *+ * Only the bucket labels are parameters: [justNowLabel] and [futureLabel]+ * cover the apps that say "now" instead of "just now", [unknownLabel] is+ * what an unusable timestamp renders as, and [olderLabel] (given the original+ * timestamp) renders ages past [maxDays] for apps that fall back to a date.+ * Without [olderLabel], older ages keep counting days.+ */+fun formatRelativeAge(+    atMillis: Long,+    nowMillis: Long,+    justNowLabel: String = "just now",+    futureLabel: String = justNowLabel,+    unknownLabel: String = "",+    maxDays: Long = Long.MAX_VALUE,+    olderLabel: ((atMillis: Long) -> String)? = null,+): String =+    when (val age = relativeAge(atMillis, nowMillis, maxDays)) {+        RelativeAge.Unknown -> unknownLabel+        RelativeAge.Future -> futureLabel+        RelativeAge.JustNow -> justNowLabel+        is RelativeAge.Minutes -> "${age.amount}m ago"+        is RelativeAge.Hours -> "${age.amount}h ago"+        is RelativeAge.Days -> "${age.amount}d ago"+        RelativeAge.Older ->+            olderLabel?.invoke(atMillis)+                ?: "${(nowMillis - atMillis) / MILLIS_PER_DAY}d ago"+    }
library/format/src/test/java/com/vayunmathur/library/format/RelativeAgeTest.kt
diff --git a/library/format/src/test/java/com/vayunmathur/library/format/RelativeAgeTest.kt b/library/format/src/test/java/com/vayunmathur/library/format/RelativeAgeTest.ktnew file mode 100644index 0000000000..bacc1cdb40--- /dev/null+++ b/library/format/src/test/java/com/vayunmathur/library/format/RelativeAgeTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.library.format++import kotlin.test.Test+import kotlin.test.assertEquals++class RelativeAgeTest {++    private val now = 1_700_000_000_000L++    @Test+    fun unknownAndFuture() {+        assertEquals(RelativeAge.Unknown, relativeAge(0L, now))+        assertEquals(RelativeAge.Unknown, relativeAge(-5L, now))+        assertEquals(RelativeAge.Future, relativeAge(now + 1L, now))+    }++    @Test+    fun bucketBoundaries() {+        assertEquals(RelativeAge.JustNow, relativeAge(now, now))+        assertEquals(RelativeAge.JustNow, relativeAge(now - 59_999L, now))+        assertEquals(RelativeAge.Minutes(1), relativeAge(now - 60_000L, now))+        assertEquals(RelativeAge.Minutes(59), relativeAge(now - 3_599_999L, now))+        assertEquals(RelativeAge.Hours(1), relativeAge(now - 3_600_000L, now))+        assertEquals(RelativeAge.Hours(23), relativeAge(now - 86_399_999L, now))+        assertEquals(RelativeAge.Days(1), relativeAge(now - 86_400_000L, now))+        assertEquals(RelativeAge.Days(30), relativeAge(now - 2_592_000_000L, now))+    }++    @Test+    fun maxDaysMovesOldAgesToOlder() {+        assertEquals(RelativeAge.Days(6), relativeAge(now - 6 * 86_400_000L, now, maxDays = 7))+        assertEquals(RelativeAge.Older, relativeAge(now - 7 * 86_400_000L, now, maxDays = 7))+    }++    @Test+    fun formatUsesSharedWordingByDefault() {+        assertEquals("", formatRelativeAge(0L, now))+        assertEquals("just now", formatRelativeAge(now - 10_000L, now))+        assertEquals("just now", formatRelativeAge(now + 10_000L, now))+        assertEquals("5m ago", formatRelativeAge(now - 300_000L, now))+        assertEquals("3h ago", formatRelativeAge(now - 10_800_000L, now))+        assertEquals("2d ago", formatRelativeAge(now - 172_800_000L, now))+    }++    @Test+    fun formatLabelsCoverNowWordingAndDateFallback() {+        // news: "now" for both future and just-now.+        assertEquals("now", formatRelativeAge(now + 60_000L, now, justNowLabel = "now"))+        assertEquals("now", formatRelativeAge(now - 10_000L, now, justNowLabel = "now"))+        // games hub / madeveloper: future reads "now" / a date, old ages a date.+        assertEquals(+            "now",+            formatRelativeAge(now + 60_000L, now, futureLabel = "now"),+        )+        assertEquals(+            "date",+            formatRelativeAge(now - 30 * 86_400_000L, now, maxDays = 7, olderLabel = { "date" }),+        )+    }+}
madeveloper/build.gradle.kts
diff --git a/madeveloper/build.gradle.kts b/madeveloper/build.gradle.ktsindex f8691e8e8d..1ca17a15b4 100644--- a/madeveloper/build.gradle.kts+++ b/madeveloper/build.gradle.kts@@ -15,5 +15,6 @@ android {  dependencies {     implementation(project(":library:network"))+    implementation(project(":library:format"))     implementation(project(":library:work")) }
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevPresentation.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevPresentation.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevPresentation.ktindex b69c781a4e..9e65d92a03 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevPresentation.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevPresentation.kt@@ -6,6 +6,8 @@ import java.time.OffsetDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale+import com.vayunmathur.library.format.RelativeAge+import com.vayunmathur.library.format.relativeAge  /** Coarse CI outcome used to pick a status colour and icon in the UI. */ enum class CiStatus { Passed, Failed, Running, Unknown }@@ -65,17 +67,17 @@ object DevPresentation {         val raw = time.trim()         if (raw.isBlank()) return ""         val epochMs = parseEpochMs(raw) ?: return raw-        val delta = nowEpochMs - epochMs-        if (delta < 0) return shortDate(epochMs)-        val minutes = delta / MILLIS_PER_MINUTE-        val hours = delta / MILLIS_PER_HOUR-        val days = delta / MILLIS_PER_DAY-        return when {-            delta < MILLIS_PER_MINUTE -> "just now"-            minutes < 60 -> "${minutes}m ago"-            hours < 24 -> "${hours}h ago"-            days < 7 -> "${days}d ago"-            else -> shortDate(epochMs)+        // Bucketing is shared (:library:format); the git-host timestamp+        // parsing above and the short-date fallback (future and older than+        // a week) stay here, as they are this app's wording.+        return when (val age = relativeAge(epochMs, nowEpochMs, maxDays = DAYS_PER_WEEK)) {+            RelativeAge.Unknown -> shortDate(epochMs)+            RelativeAge.Future -> shortDate(epochMs)+            RelativeAge.JustNow -> "just now"+            is RelativeAge.Minutes -> "${age.amount}m ago"+            is RelativeAge.Hours -> "${age.amount}h ago"+            is RelativeAge.Days -> "${age.amount}d ago"+            RelativeAge.Older -> shortDate(epochMs)         }     } @@ -129,9 +131,7 @@ object DevPresentation {     fun shortSha(sha: String): String = sha.take(SHORT_SHA_LENGTH)      private const val MILLIS_PER_SECOND = 1_000L-    private const val MILLIS_PER_MINUTE = 60_000L-    private const val MILLIS_PER_HOUR = 3_600_000L-    private const val MILLIS_PER_DAY = 86_400_000L+    private const val DAYS_PER_WEEK = 7L     private const val EPOCH_SECONDS_THRESHOLD = 10_000_000_000L     private const val DATE_PREFIX_LENGTH = 10     private const val SHORT_SHA_LENGTH = 8
news/build.gradle.kts
diff --git a/news/build.gradle.kts b/news/build.gradle.ktsindex 223e10617e..01c49a6384 100644--- a/news/build.gradle.kts+++ b/news/build.gradle.kts@@ -18,6 +18,7 @@ android {  dependencies {     implementation(project(":library:network"))+    implementation(project(":library:format"))     implementation(project(":library:image"))     implementRoom(libs)     implementation(project(":library:room"))
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 49a2181803..0dfe7a8922 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -81,6 +81,7 @@ include(":library:avatar") include(":library:image") include(":library:media") include(":library:log")+include(":library:format") include(":library:wearlink") include(":library:carhost") include(":calendar")