summaryrefslogtreecommitdiff
path: root/apps/web/lib/queries/use-entry-highlights.ts
blob: 3fdada5f3922ff9ca78baaf7507a09a6bfd4fe0f (plain) (blame)
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
49
50
51
52
53
54
55
56
"use client"

import { useQuery } from "@tanstack/react-query"
import { createSupabaseBrowserClient } from "@/lib/supabase/client"
import { queryKeys } from "./query-keys"
import type { Highlight } from "@/lib/types/highlight"

interface HighlightRow {
  id: string
  entry_id: string
  highlighted_text: string
  note: string | null
  text_offset: number
  text_length: number
  text_prefix: string
  text_suffix: string
  color: string
  created_at: string
}

function mapRowToHighlight(row: HighlightRow): Highlight {
  return {
    identifier: row.id,
    entryIdentifier: row.entry_id,
    highlightedText: row.highlighted_text,
    note: row.note,
    textOffset: row.text_offset,
    textLength: row.text_length,
    textPrefix: row.text_prefix,
    textSuffix: row.text_suffix,
    color: row.color,
    createdAt: row.created_at,
  }
}

export function useEntryHighlights(entryIdentifier: string | null) {
  const supabaseClient = createSupabaseBrowserClient()

  return useQuery({
    queryKey: queryKeys.highlights.forEntry(entryIdentifier ?? ""),
    enabled: !!entryIdentifier,
    queryFn: async () => {
      const { data, error } = await supabaseClient
        .from("user_highlights")
        .select(
          "id, entry_id, highlighted_text, note, text_offset, text_length, text_prefix, text_suffix, color, created_at"
        )
        .eq("entry_id", entryIdentifier!)
        .order("text_offset", { ascending: true })

      if (error) throw error

      return ((data as unknown as HighlightRow[]) ?? []).map(mapRowToHighlight)
    },
  })
}