OverviewFilesCommitsIssuesDocsReleasesPeers

keet-deobfuscated / @holepunchto / keet-store / store / chat / message / message-create.js

62 lines · javascript ref:
import { MS_5_MINUTES as t, formatTimestamp as e } from "../../lib/date"
import { MESSAGE_CATEGORY as r } from "../chat.constant"
import { groupByAuthor as o } from "./message-create-author"
import { groupByDate as s } from "./message-create-date"
import { calcMessageCategory as a, getIsGroupCountLimitReached as m } from "./message"
function n(t, e, r) {
  const o = t[r],
    s = t[e],
    a = s.id
  let m, n
  for (let o = r; o < e; o += 1) {
    let e = t[o]
    ;(e.isHead || e.datetime || e.parentId !== a) &&
      ((m ||= e.isHead),
      e.datetime && !n && (n = e.datetime),
      (e = { ...e, isHead: !1, datetime: void 0, parentId: a }),
      (t[o] = e))
  }
  const i = []
  for (let o = e; o >= r; o -= 1) {
    const { memberId: e, targetMemberId: r } = t[o]
    r ? i.push(r) : i.push(e)
  }
  const d = e - r + 1,
    p = o.seq
  t[e] = { ...s, isHead: !0, groupMemberIds: i, groupCount: d, groupSeq: p }
  const u = r - 1
  n && u >= 0 && !t[u].datetime && (t[u] = { ...t[u], datetime: n })
}
export function groupByCategory(t) {
  let e = r.NO_CATEGORY,
    o = -1
  for (let r = t.length - 1; r >= 0; r -= 1) {
    const s = t[r],
      i = a(s),
      d = r + 1,
      p = m(i, o > -1 ? o - d + 1 : 0),
      u = i !== e || p
    ;(u && o > -1 && n(t, o, d), i && u && (o = r), i || (o = -1), (e = i))
  }
  return (o > -1 && n(t, o, 0), t)
}
export function markOutOfOrders(t, r) {
  const { now: o } = r
  let s = t.length,
    a = t[t.length - 1],
    m = a?.timestamp
  for (; s > 0; ) {
    ;((s -= 1), (a = t[s]))
    const { timestamp: r } = a,
      n = r > o || (m > a.timestamp && e(m) !== e(a.timestamp))
    ;(!!a.isOutOfOrder !== n && (t[s] = { ...a, isOutOfOrder: n }), n || (m = r))
  }
  return t
}
export function groupMessages(e, r = { now: Date.now() + t }) {
  if (!e?.length) return []
  const a = markOutOfOrders(e, r),
    m = o(a)
  return groupByCategory(s(m))
}