All files / apps / web/src / features / conversation / lib timeline.ts

100% Statements 16/16
100% Branches 12/12
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                6x     134x               16x     16x 57x 57x 57x   57x   57x     57x         57x 57x     16x       35x    
import type { Message } from '../types'
 
export type TimelineRow =
  | { type: 'day'; key: string; dayStart: number }
  | { type: 'new'; key: string }
  | { type: 'message'; key: string; message: Message; isCompact: boolean }
 
// A follow-up from the same person within five minutes drops its avatar and name.
const COMPACT_WINDOW_MS = 5 * 60 * 1000
 
function startOfDay(time: number): number {
  return new Date(time).setHours(0, 0, 0, 0)
}
 
// Turns a message list into what the screen shows: day dividers, the "new messages" line, messages.
export function buildTimeline(
  messages: Message[],
  lastReadMessageId: string | null,
): TimelineRow[] {
  const rows: TimelineRow[] = []
  let previous: Message | undefined
 
  for (const message of messages) {
    const dayStart = startOfDay(message.sentAt)
    const isNewDay = !previous || startOfDay(previous.sentAt) !== dayStart
    const isFirstNew = previous !== undefined && previous.id === lastReadMessageId
 
    if (isNewDay) rows.push({ type: 'day', key: `day-${dayStart}`, dayStart })
 
    if (isFirstNew) rows.push({ type: 'new', key: 'new' })
 
    const isCompact =
      !isNewDay &&
      !isFirstNew &&
      previous?.authorId === message.authorId &&
      message.sentAt - previous.sentAt <= COMPACT_WINDOW_MS
 
    rows.push({ type: 'message', key: message.id, message, isCompact })
    previous = message
  }
 
  return rows
}
 
export function dayOffset(dayStart: number, now: number): number {
  return Math.round((startOfDay(now) - dayStart) / (24 * 60 * 60 * 1000))
}