product-time.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. const MINUTE_MS = 60 * 1000;
  2. const HOUR_MS = 60 * MINUTE_MS;
  3. const DAY_MS = 24 * HOUR_MS;
  4. const FOUR_DAYS_MS = 4 * DAY_MS;
  5. const RECENT_CALENDAR_DAYS = 7;
  6. const EN_WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;
  7. const ZH_WEEKDAYS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] as const;
  8. const DEFAULT_TIME_ZONE = (() => {
  9. try {
  10. return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
  11. } catch {
  12. return 'UTC';
  13. }
  14. })();
  15. const formatterCache = new Map<string, Intl.DateTimeFormat>();
  16. export type ProductTimePreset =
  17. | 'social-precise'
  18. | 'social-compact'
  19. | 'community-relative'
  20. | 'common-precise'
  21. | 'common-date'
  22. | 'audit-datetime'
  23. | 'audit-date';
  24. export interface ProductTimeOptions {
  25. preset: ProductTimePreset;
  26. /** Runtime locale. Chinese locales use year-first hyphenated dates; others use English rules. */
  27. locale?: string;
  28. /** Injectable clock for deterministic rendering and tests. Defaults to Date.now(). */
  29. nowMs?: number;
  30. /** IANA timezone used for calendar boundaries. Defaults to the user's local timezone. */
  31. timeZone?: string;
  32. }
  33. type ProductTimeLocale = 'en' | 'zh';
  34. interface ZonedDateParts {
  35. year: number;
  36. month: number;
  37. day: number;
  38. hour: number;
  39. minute: number;
  40. }
  41. function getFormatter(timeZone: string): Intl.DateTimeFormat {
  42. const cached = formatterCache.get(timeZone);
  43. if (cached) return cached;
  44. const formatter = new Intl.DateTimeFormat('en-US-u-ca-gregory-nu-latn', {
  45. timeZone,
  46. year: 'numeric',
  47. month: '2-digit',
  48. day: '2-digit',
  49. hour: '2-digit',
  50. minute: '2-digit',
  51. hourCycle: 'h23',
  52. });
  53. formatterCache.set(timeZone, formatter);
  54. return formatter;
  55. }
  56. function getZonedDateParts(timestampMs: number, timeZone: string): ZonedDateParts {
  57. const values: Partial<Record<Intl.DateTimeFormatPartTypes, string>> = {};
  58. for (const part of getFormatter(timeZone).formatToParts(timestampMs)) {
  59. if (part.type !== 'literal') values[part.type] = part.value;
  60. }
  61. return {
  62. year: Number(values.year),
  63. month: Number(values.month),
  64. day: Number(values.day),
  65. hour: Number(values.hour),
  66. minute: Number(values.minute),
  67. };
  68. }
  69. function resolveLocale(locale?: string): ProductTimeLocale {
  70. return (locale ?? '').toLowerCase().startsWith('zh') ? 'zh' : 'en';
  71. }
  72. function padTwo(value: number): string {
  73. return String(value).padStart(2, '0');
  74. }
  75. function formatTime(parts: ZonedDateParts): string {
  76. return `${padTwo(parts.hour)}:${padTwo(parts.minute)}`;
  77. }
  78. function isSameDay(left: ZonedDateParts, right: ZonedDateParts): boolean {
  79. return left.year === right.year && left.month === right.month && left.day === right.day;
  80. }
  81. function formatDate(
  82. parts: ZonedDateParts,
  83. locale: ProductTimeLocale,
  84. includeYear: boolean,
  85. ): string {
  86. const month = padTwo(parts.month);
  87. const day = padTwo(parts.day);
  88. if (!includeYear) return locale === 'zh' ? `${month}-${day}` : `${month}/${day}`;
  89. return locale === 'zh' ? `${parts.year}-${month}-${day}` : `${month}/${day}/${parts.year}`;
  90. }
  91. function formatDateTime(
  92. parts: ZonedDateParts,
  93. locale: ProductTimeLocale,
  94. includeYear: boolean,
  95. ): string {
  96. return `${formatDate(parts, locale, includeYear)} ${formatTime(parts)}`;
  97. }
  98. function calendarDayIndex(parts: ZonedDateParts): number {
  99. return Date.UTC(parts.year, parts.month - 1, parts.day) / DAY_MS;
  100. }
  101. function formatWeekday(parts: ZonedDateParts, locale: ProductTimeLocale): string {
  102. const weekday = new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDay();
  103. const labels = locale === 'zh' ? ZH_WEEKDAYS : EN_WEEKDAYS;
  104. return labels[weekday] ?? labels[0];
  105. }
  106. function formatSocialTime(
  107. timestampMs: number,
  108. nowMs: number,
  109. timestamp: ZonedDateParts,
  110. now: ZonedDateParts,
  111. locale: ProductTimeLocale,
  112. precise: boolean,
  113. ): string {
  114. const sameYear = timestamp.year === now.year;
  115. if (timestampMs > nowMs) {
  116. return precise
  117. ? formatDateTime(timestamp, locale, !sameYear)
  118. : formatDate(timestamp, locale, !sameYear);
  119. }
  120. const elapsedMs = nowMs - timestampMs;
  121. if (elapsedMs < MINUTE_MS) return locale === 'zh' ? '刚刚' : 'Now';
  122. if (isSameDay(timestamp, now)) return formatTime(timestamp);
  123. const dayDelta = calendarDayIndex(now) - calendarDayIndex(timestamp);
  124. if (dayDelta === 1) {
  125. const yesterday = locale === 'zh' ? '昨天' : 'Yesterday';
  126. return `${yesterday} ${formatTime(timestamp)}`;
  127. }
  128. if (dayDelta > 1 && dayDelta < RECENT_CALENDAR_DAYS) {
  129. const weekday = formatWeekday(timestamp, locale);
  130. return precise ? `${weekday} ${formatTime(timestamp)}` : weekday;
  131. }
  132. return precise
  133. ? formatDateTime(timestamp, locale, !sameYear)
  134. : formatDate(timestamp, locale, !sameYear);
  135. }
  136. function formatCommunityTime(
  137. timestampMs: number,
  138. nowMs: number,
  139. timestamp: ZonedDateParts,
  140. now: ZonedDateParts,
  141. locale: ProductTimeLocale,
  142. ): string {
  143. const sameYear = timestamp.year === now.year;
  144. if (timestampMs > nowMs) return formatDate(timestamp, locale, !sameYear);
  145. const elapsedMs = nowMs - timestampMs;
  146. if (elapsedMs < MINUTE_MS) return locale === 'zh' ? '刚刚' : 'Now';
  147. if (elapsedMs < HOUR_MS) {
  148. const minutes = Math.floor(elapsedMs / MINUTE_MS);
  149. return locale === 'zh' ? `${minutes}分钟前` : `${minutes}m`;
  150. }
  151. if (elapsedMs < DAY_MS) {
  152. const hours = Math.floor(elapsedMs / HOUR_MS);
  153. return locale === 'zh' ? `${hours}小时前` : `${hours}h`;
  154. }
  155. if (elapsedMs < FOUR_DAYS_MS) {
  156. const days = Math.floor(elapsedMs / DAY_MS);
  157. return locale === 'zh' ? `${days}天前` : `${days}d`;
  158. }
  159. return formatDate(timestamp, locale, !sameYear);
  160. }
  161. /**
  162. * Project-wide UI timestamp calculator.
  163. *
  164. * Input must be Unix milliseconds. Choose a semantic preset instead of assembling date patterns
  165. * at a call site. See `.harness/docs/design/time-display.md` for preset selection and exclusions.
  166. */
  167. export function formatProductTime(
  168. timestampMs: number | null | undefined,
  169. options: ProductTimeOptions,
  170. ): string {
  171. if (typeof timestampMs !== 'number' || !Number.isFinite(timestampMs)) return '';
  172. const nowMs = options.nowMs ?? Date.now();
  173. if (!Number.isFinite(nowMs)) return '';
  174. const locale = resolveLocale(options.locale);
  175. const timeZone = options.timeZone ?? DEFAULT_TIME_ZONE;
  176. const timestamp = getZonedDateParts(timestampMs, timeZone);
  177. const now = getZonedDateParts(nowMs, timeZone);
  178. const sameYear = timestamp.year === now.year;
  179. switch (options.preset) {
  180. case 'social-precise':
  181. return formatSocialTime(timestampMs, nowMs, timestamp, now, locale, true);
  182. case 'social-compact':
  183. return formatSocialTime(timestampMs, nowMs, timestamp, now, locale, false);
  184. case 'community-relative':
  185. return formatCommunityTime(timestampMs, nowMs, timestamp, now, locale);
  186. case 'common-precise':
  187. return isSameDay(timestamp, now)
  188. ? formatTime(timestamp)
  189. : formatDateTime(timestamp, locale, !sameYear);
  190. case 'common-date':
  191. return isSameDay(timestamp, now)
  192. ? formatTime(timestamp)
  193. : formatDate(timestamp, locale, !sameYear);
  194. case 'audit-datetime':
  195. return formatDateTime(timestamp, locale, true);
  196. case 'audit-date':
  197. return formatDate(timestamp, locale, true);
  198. }
  199. }