#include "screens/components/RelativeTime.hpp" #include #include #include "ui/Palette.hpp" namespace dp { namespace { struct Unit { const char* narrowSingular; const char* narrowPlural; const char* wideSingular; const char* widePlural; }; constexpr Unit kSec{"sec.", "sec.", "second", "seconds"}; constexpr Unit kMin{"min.", "min.", "minute", "minutes"}; constexpr Unit kHour{"hr.", "hr.", "hour", "hours"}; constexpr Unit kDay{"day", "days", "day", "days"}; constexpr Unit kWeek{"wk.", "wk.", "week", "weeks"}; constexpr Unit kMonth{"mo.", "mo.", "month", "months"}; constexpr Unit kYear{"yr.", "yr.", "year", "years"}; std::string phrase(long value, const Unit& u, bool past, RelativeTime::Style style) { const bool one = value == 1; const char* unit = style == RelativeTime::Style::Narrow ? (one ? u.narrowSingular : u.narrowPlural) : (one ? u.wideSingular : u.widePlural); const std::string body = std::to_string(value) + " " + unit; return past ? body + " ago" : "in " + body; } } // namespace std::string RelativeTime::format(Date date, Date now, Style style) { using namespace std::chrono; const double secs = duration(date - now).count(); const bool past = secs <= 0; const double a = std::fabs(secs); const bool narrow = style == Style::Narrow; if (a < 1.0) return "now"; if (a < 60) return phrase(static_cast(std::lround(a)), kSec, past, style); if (a < 3600) return phrase(static_cast(std::lround(a / 60)), kMin, past, style); if (a < 86400) return phrase(static_cast(std::lround(a / 3600)), kHour, past, style); const long days = static_cast(std::lround(a / 86400)); if (days < 7) { if (days == 1) return past ? "yesterday" : "tomorrow"; return phrase(days, kDay, past, style); } if (days < 30) { const long weeks = std::max(1L, static_cast(std::lround(days / 7.0))); if (weeks == 1) return past ? (narrow ? "last wk." : "last week") : (narrow ? "next wk." : "next week"); return phrase(weeks, kWeek, past, style); } if (days < 365) { const long months = std::max(1L, static_cast(std::lround(days / 30.4375))); if (months == 1) return past ? (narrow ? "last mo." : "last month") : (narrow ? "next mo." : "next month"); return phrase(months, kMonth, past, style); } const long years = std::max(1L, static_cast(std::lround(days / 365.25))); if (years == 1) return past ? (narrow ? "last yr." : "last year") : (narrow ? "next yr." : "next year"); return phrase(years, kYear, past, style); } ui::ViewPtr RelativeTimeLabel(Date date, RelativeTime::Style style) { using namespace ui; return Text(RelativeTime::format(date, DateCodec::now(), style))->font(FontSpec::system(12))->foreground(Palette::fg2()); } } // namespace dp