eletrotupi / tcc/ commit / 6b5692b

frontend: add specific hook to fetch data for the feed

Pedro Lucas Porcellis porcellis@eletrotupi.com · 5 months ago 6b5692bd7b0965769ac35dc7432b86babe675797 Browse files
Parents 9964daf
Changed files
2
Additions
+62
Deletions
0
/dev/null → frontend/hooks/useHistoryFeed.ts
1 +
// hooks/useHistoryFeed.ts
2 +
import { useMemo } from 'react'
3 +
import { mergeAndSort, filterByCategory, groupByDate } from '@/lib/utils/history'
4 +
import {
5 +
  mapMoodToHistoryCard,
6 +
  mapSleepToHistoryCard,
7 +
  mapTriggerToHistoryCard,
8 +
  mapInterventionToHistoryCard
9 +
} from '@/lib/history/mappers'
10 +
import type { HistoryCategory } from '@/lib/history/types'
11 +
import { useMoodEntries, useSleepRecords } from '@/hooks';
12 +

13 +
export function useHistoryFeed(activeFilter: HistoryCategory | 'all') {
14 +
  const { data: moodsPage }        = useMoodEntries({})
15 +
  const { data: sleepPage }        = useSleepRecords({})
16 +

17 +
  const moods        = moodsPage?.entries ?? []
18 +
  const sleepRecords = sleepPage?.entries ?? []
19 +

20 +
  const grouped = useMemo(() => {
21 +
    const merged = mergeAndSort([
22 +
      moods.map(mapMoodToHistoryCard),
23 +
      sleepRecords.map(mapSleepToHistoryCard),
24 +
    ])
25 +
    const filtered = filterByCategory(merged, activeFilter)
26 +
    return groupByDate(filtered)
27 +
  }, [moods, sleepRecords, activeFilter])
28 +

29 +
  // TODO: expose the isLoading here
30 +
  return grouped
31 +
}
/dev/null → frontend/lib/utils/history.ts
1 +
// TODO: add a barrel import here ffs
2 +
import type { HistoryCard, HistoryCategory } from '@/lib/history/types'
3 +

4 +
export function mergeAndSort(cards: HistoryCard[][]): HistoryCard[] {
5 +
  return cards
6 +
  .flat()
7 +
  .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
8 +
}
9 +

10 +
export function groupByDate(cards: HistoryCard[]): Record<string, HistoryCard[]> {
11 +
  return cards.reduce<Record<string, HistoryCard[]>>((acc, card) => {
12 +
    const key = new Date(card.timestamp).toLocaleDateString('pt-BR', {
13 +
      weekday: 'long',
14 +
      day: 'numeric',
15 +
      month: 'long',
16 +
    });
17 +

18 +
    // XXX: Hacky as fuck
19 +
    (acc[key] ??= []).push(card)
20 +

21 +
    return acc
22 +
  }, {})
23 +
}
24 +

25 +
export function filterByCategory(
26 +
  cards: HistoryCard[],
27 +
  active: HistoryCategory | 'all',
28 +
): HistoryCard[] {
29 +
  if (active === 'all') return cards
30 +
    return cards.filter(c => c.category === active)
31 +
}