Skip to content

Commit

Permalink
feat: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
andresgutgon committed Nov 13, 2024
1 parent 44c9436 commit 042741e
Show file tree
Hide file tree
Showing 7 changed files with 180 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function DatasetParams({
const onNextPage = (page: number) => data.onRowChange(page + 1)
return (
<div className='flex flex-col gap-y-4'>
<div className='flex flex-row items-center justify-between gap-x-4'>
<div className='flex flex-row items-center justify-between gap-x-4 border-b border-border pb-2'>
<Select
name='datasetId'
placeholder={data.isLoading ? 'Loading...' : 'Select dataset'}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { DEFAULT_PAGINATION_SIZE } from '@latitude-data/core/browser'
import { format } from 'date-fns'
import {
Badge,
cn,
Icon,
ReactStateDispatch,
Skeleton,
Text,
useCurrentCommit,
useCurrentProject,
} from '@latitude-data/web-ui'
Expand All @@ -13,6 +16,7 @@ import {
PlaygroundInputs,
} from '$/hooks/useDocumentParameters'
import { ROUTES } from '$/services/routes'
import { LogWithPosition } from '$/stores/documentLogWithPaginationPosition'
import Link from 'next/link'

import { InputParams } from '../Input'
Expand All @@ -23,15 +27,18 @@ const INDEX_OF_FIRST_PAGE = 1

function usePaginatedDocumentLogUrl({
page,
selectedLogUuid,
selectedLog,
isLoading,
}: {
selectedLogUuid: string | undefined
selectedLog: LogWithPosition['documentLog'] | undefined
page: number | undefined
isLoading: boolean
}) {
const document = useCurrentDocument()
const { project } = useCurrentProject()
const { commit } = useCurrentCommit()
if (page === undefined || !selectedLogUuid) return undefined
if (isLoading) return undefined
if (page === undefined || !selectedLog) return undefined

const pageInLogs =
Math.floor(page / DEFAULT_PAGINATION_SIZE) + INDEX_OF_FIRST_PAGE
Expand All @@ -40,10 +47,13 @@ function usePaginatedDocumentLogUrl({
.detail({ id: project.id })
.commits.detail({ uuid: commit.uuid })
.documents.detail({ uuid: document.documentUuid }).logs.root
const url = `${route}?page=${pageInLogs}&logUuid=${selectedLogUuid}`
const uuid = selectedLog.uuid
const url = `${route}?page=${pageInLogs}&logUuid=${uuid}`

const shortCode = selectedLogUuid.split('-')[0]
return { url, shortCode }
const shortCode = uuid.split('-')[0]

const createdAt = format(selectedLog.createdAt, 'PPp')
return { url, shortCode, createdAt }
}

export function HistoryLogParams({
Expand All @@ -59,29 +69,39 @@ export function HistoryLogParams({
}) {
const data = useLogHistoryParams({ inputs, setInputs, setForceReadMetadata })
const urlData = usePaginatedDocumentLogUrl({
selectedLogUuid: data.selectedLogUuid,
selectedLog: data.selectedLog,
page: data.page,
isLoading: data.isLoadingLog,
})
return (
<div className='flex flex-col gap-y-4'>
<div className='flex flex-row gap-x-4 justify-between border-border border-b pb-2'>
<div>
{urlData ? (
<div className='flex flex-row gap-x-4 justify-between items-center border-border border-b pb-2'>
<div className='flex-grow'>
{data.isLoadingLog ? (
<div className='flex flex-row gap-x-2 w-full'>
<Skeleton height='h3' className='w-2/3' />
<Skeleton height='h3' className='w-1/3' />
</div>
) : null}
{!data.isLoadingLog && urlData ? (
<Link href={urlData.url}>
<div className='flex flex-row items-center gap-x-1'>
<div className='flex flex-row items-center gap-x-2'>
<Text.H5>{urlData.createdAt}</Text.H5>
<Badge variant='accent'>{urlData.shortCode}</Badge>
<Icon name='externalLink' color='foregroundMuted' />
</div>
</Link>
) : null}
</div>
<ParametersPaginationNav
label='history logs'
currentIndex={data.page}
totalCount={data.count}
onPrevPage={data.onPrevPage}
onNextPage={data.onNextPage}
/>
<div>
<ParametersPaginationNav
label='history logs'
currentIndex={data.page}
totalCount={data.count}
onPrevPage={data.onPrevPage}
onNextPage={data.onNextPage}
/>
</div>
</div>
<div className={cn({ 'opacity-50': data.isLoading })}>
<InputParams inputs={inputs} setInput={setInput} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState } from 'react'
import { useCallback, useEffect, useRef } from 'react'

import { DocumentLog } from '@latitude-data/core/browser'
import { DocumentLogWithMetadataAndError } from '@latitude-data/core/repositories'
Expand All @@ -12,7 +12,11 @@ import {
PlaygroundInput,
PlaygroundInputs,
} from '$/hooks/useDocumentParameters'
import useDocumentLogs from '$/stores/documentLogs'
import { useFetchApi } from '$/hooks/useFetcher'
import {
buildDocumentLogsApiUrl,
documentLogsSerializer,
} from '$/stores/documentLogs'
import useDocumentLogWithPaginationPosition from '$/stores/documentLogWithPaginationPosition'
import useDocumentLogsPagination from '$/stores/useDocumentLogsPagination'

Expand All @@ -35,6 +39,7 @@ function getValue({
return typeof inputValue === 'string' ? inputValue : inputValue.value
}
}

function mapLogParametersToInputs({
inputs,
parameters,
Expand Down Expand Up @@ -70,79 +75,82 @@ export function useLogHistoryParams({
const document = useCurrentDocument()
const { saveRowInfo, selectedRow } = useSelectedLogRow({ document })
const selectedLogUuid = selectedRow?.documentLogUuid
/* const selectedLogUuid = '50494c4b-054c-4510-afb8-84b12fbe76f0' */
const { project } = useCurrentProject()
const { commit } = useCurrentCommit()
const [page, setPage] = useState<number | undefined>(
selectedLogUuid ? undefined : 1,
)
const { data: pagination, isLoading: isLoadingCounter } =
useDocumentLogsPagination({
projectId: project.id,
commitUuid: commit.uuid,
documentUuid: document.documentUuid,
page: page?.toString?.() ?? '1',
page: '1', // Not used really. This is only for the counter.
pageSize: ONLY_ONE_PAGE,
})
const [paginatedLog, setPaginatedLog] = useState<
DocumentLogWithMetadataAndError | undefined
>()
const onLogFetched = useCallback(
(logs: DocumentLogWithMetadataAndError[]) => {
const log = logs[0]
if (!log) return
setPaginatedLog(log)
saveRowInfo({ documentLogUuid: log.uuid })
},
[saveRowInfo, setPaginatedLog],
)
const { isLoading: isLoadingList } = useDocumentLogs({
documentUuid: !selectedLogUuid ? document.documentUuid : undefined,
commitUuid: commit.uuid,

const { isLoading: isLoadingLog, data } =
useDocumentLogWithPaginationPosition({
documentLogUuid: selectedLogUuid,
onFetched: (data) => {
const newInputs = mapLogParametersToInputs({
inputs,
parameters: data?.documentLog?.parameters,
})

if (!newInputs) return

setInputs(newInputs)

if (!mounted?.current) {
setForceReadMetadata(true)
mounted.current = true
}
},
})

const logsUrl = buildDocumentLogsApiUrl({
projectId: project.id,
page: page?.toString?.() ?? '1',
pageSize: ONLY_ONE_PAGE,
onFetched: onLogFetched,
commitUuid: commit.uuid,
documentUuid: document.documentUuid,
})
const { isLoading: isLoadingLog } = useDocumentLogWithPaginationPosition({
documentLogUuid: selectedLogUuid ?? paginatedLog?.uuid,
onFetched: (data) => {
const newInputs = mapLogParametersToInputs({
inputs,
parameters: data?.documentLog?.parameters,
})

if (!newInputs) return

setInputs(newInputs)
setPage(data.position) // Is pagination of 1. So position is the page

if (!mounted?.current) {
setForceReadMetadata(true)
mounted.current = true
}
},

const fetchLogs = useFetchApi<DocumentLogWithMetadataAndError[]>({
serializer: documentLogsSerializer,
})

const onNextPage = useCallback(
(page: number) => {
saveRowInfo({ documentLogUuid: undefined })
setPage(page + 1)
},
[setPage],
)
const onPrevPage = useCallback(
(page: number) => {
saveRowInfo({ documentLogUuid: undefined })
setPage(page - 1)
},
[setPage],
)

const isLoading = isLoadingList || isLoadingLog || isLoadingCounter
const fetchPage = useCallback(async (page: number) => {
const logs = await fetchLogs({
route: logsUrl,
searchParams: {
page: String(page),
pageSize: ONLY_ONE_PAGE,
},
})
const log = logs[0]
if (!log) return

saveRowInfo({ documentLogUuid: log.uuid })
}, [])

const onNextPage = useCallback(async (page: number) => {
fetchPage(page + 1)
}, [])
const onPrevPage = useCallback(async (page: number) => {
await fetchPage(page - 1)
}, [])

useEffect(() => {
if (selectedLogUuid) return

fetchPage(1)
}, [selectedLogUuid])

const isLoading = isLoadingLog || isLoadingCounter
console.log("PAGE", data?.position)
return {
selectedLogUuid,
selectedLog: data?.documentLog,
isLoadingLog,
isLoading,
page,
page: data?.position,
onNextPage,
onPrevPage,
count: pagination?.count ?? 0,
Expand Down
77 changes: 46 additions & 31 deletions apps/web/src/hooks/useFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,29 @@ import { ROUTES } from '$/services/routes'

import { useNavigate } from './useNavigate'

type ISearchParams =
| Record<string, string>
| string[][]
| string
| URLSearchParams
| undefined
function buildRoute(route: string, searchParams?: ISearchParams) {
if (!searchParams) return route

export default function useFetcher(
route?: string,
{
fallback = [],
serializer,
const params = new URLSearchParams(searchParams)
return route.toString() + '?' + params.toString()
}

export function useFetchApi({
fallback,
serializer,
}: {
fallback?: any
serializer?: (item: any) => any
}) {
const { toast } = useToast()
const navigate = useNavigate()
return async ({
route,
searchParams,
}: {
fallback?: any
serializer?: (item: any) => any
route: string
searchParams?: ISearchParams
} = { fallback: [] },
) {
const { toast } = useToast()
const navigate = useNavigate()

return async () => {
if (!route) return fallback

}) => {
const response = await fetch(buildRoute(route, searchParams), {
credentials: 'include',
})
Expand All @@ -47,27 +45,44 @@ export default function useFetcher(
variant: 'destructive',
})
} else {
const error = await response.json()

toast({
title: 'Error',
description: error.message,
description: 'An unknown error occurred',
variant: 'destructive',
})
}

return fallback
}

return serializer
? serializer(await response.json())
: await response.json()
const data = await response.json()
return serializer ? serializer(data) : data
}
}

function buildRoute(route: string, searchParams?: ISearchParams) {
if (!searchParams) return route
type ISearchParams =
| Record<string, string>
| string[][]
| string
| URLSearchParams
| undefined

const params = new URLSearchParams(searchParams)
return route.toString() + '?' + params.toString()
export default function useFetcher(
route?: string,
{
fallback = [],
serializer,
searchParams,
}: {
fallback?: any
serializer?: (item: any) => any
searchParams?: ISearchParams
} = { fallback: [] },
) {
const fetchApi = useFetchApi({ fallback, serializer })
return async () => {
if (!route) return fallback

return fetchApi({ route, searchParams })
}
}
Loading

0 comments on commit 042741e

Please sign in to comment.