Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

feat: Inifinite scroll

Blue Mouse45814efe16a6
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 49f29eaca..20175e4b1 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -49,6 +49,7 @@ import { askAI } from '~/api'
import useSpeechRecognition from '~/hooks/useSpeechRecognition'
import { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
@@ -1637,6 +1638,7 @@ const ChatHistoryPanel = ({
const { t } = useTranslation('common')
const isSearching = search.trim().length >= 2 || tagFilter !== null
const showEmpty = !isLoading && chats.length === 0
+ const scrollContainerRef = useRef<HTMLDivElement | null>(null)
const pinned = useMemo(() => chats.filter((c) => c.pinned), [chats])
const others = useMemo(() => chats.filter((c) => !c.pinned), [chats])
@@ -1696,7 +1698,10 @@ const ChatHistoryPanel = ({
</div>
) : null}
- <div className='-mx-1 max-h-[60vh] overflow-y-auto px-1'>
+ <div
+ ref={scrollContainerRef}
+ className='-mx-1 max-h-[60vh] overflow-y-auto px-1'
+ >
{showEmpty ? (
<Text
as='p'
@@ -1756,18 +1761,14 @@ const ChatHistoryPanel = ({
</div>
) : null}
- {chats.length < total ? (
- <Button
- variant='secondary'
- size='xs'
- onClick={onLoadMore}
- disabled={isFetchingMore}
- loading={isFetchingMore}
- className='justify-center self-center'
- >
- {t('project.askAi.loadMore')}
- </Button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={chats.length < total}
+ isLoading={isFetchingMore}
+ onLoadMore={onLoadMore}
+ disabled={isFetchingMore}
+ root={scrollContainerRef}
+ className='py-2'
+ />
</div>
)}
{isLoading && chats.length === 0 ? (
@@ -1947,7 +1948,13 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
if (pendingAllChatsSkip === 0 || pendingAllChatsSkip === null) {
setAllChats(result.chats)
} else {
- setAllChats((prev) => [...prev, ...result.chats])
+ setAllChats((prev) => {
+ const existingIds = new Set(prev.map((chat) => chat.id))
+ const uniqueChats = result.chats.filter(
+ (chat) => !existingIds.has(chat.id),
+ )
+ return [...prev, ...uniqueChats]
+ })
}
setAllChatsTotal(result.total)
}
diff --git a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
index c0b32c2d6..987b9c48e 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
@@ -27,8 +27,8 @@ import {
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import { Badge } from '~/ui/Badge'
-import Button from '~/ui/Button'
import Flag from '~/ui/Flag'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import { getRelativeDateIfPossible } from '~/utils/date'
@@ -603,18 +603,13 @@ export const ErrorDetails = ({
<SessionRow key={session.psid} session={session} />
))}
</div>
- {canLoadMoreSessions ? (
- <Button
- variant='secondary'
- size='sm'
- onClick={() => loadSessions()}
- disabled={!!sessionsLoading}
- loading={!!sessionsLoading}
- className='mx-2 mb-1 justify-center'
- >
- {t('project.loadMore')}
- </Button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreSessions}
+ isLoading={!!sessionsLoading}
+ onLoadMore={() => loadSessions()}
+ disabled={!!sessionsLoading}
+ className='mx-2 mb-1'
+ />
</div>
)}
</SectionCard>
diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
index 62453c186..27a66b6de 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
@@ -100,6 +100,7 @@ import { Badge } from '~/ui/Badge'
import BillboardChart from '~/ui/BillboardChart'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
@@ -1536,21 +1537,12 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
)}
</ClientOnly>
- {canLoadMoreErrors ? (
- <button
- type='button'
- title={t('project.loadMore')}
- onClick={loadMoreErrors}
- className={cx(
- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:bg-slate-950 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',
- {
- 'cursor-not-allowed opacity-50': errorsLoading,
- },
- )}
- >
- {t('project.loadMore')}
- </button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreErrors}
+ isLoading={!!errorsLoading}
+ onLoadMore={loadMoreErrors}
+ disabled={!!errorsLoading}
+ />
</div>
</>
) : null}
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
index 8001836b1..606e93c04 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
@@ -33,9 +33,9 @@ import Button from '~/ui/Button'
import { Badge } from '~/ui/Badge'
import Input from '~/ui/Input'
import Spin from '~/ui/icons/Spin'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
-import Pagination from '~/ui/Pagination'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
@@ -678,10 +678,10 @@ const ExperimentsView = ({
const isMountedRef = useRef(true)
const [total, setTotal] = useState(0)
const [experiments, setExperiments] = useState<Experiment[]>([])
- const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
const processedActionRef = useRef<string | null>(null)
+ const experimentsRequestModeRef = useRef<'replace' | 'append'>('replace')
// Results view state
const viewingResultsId = useMemo(
@@ -709,8 +709,6 @@ const ExperimentsView = ({
}
}, [])
- const pageAmount = Math.ceil(total / DEFAULT_EXPERIMENTS_TAKE)
-
const updateExperimentSearchParams = useCallback(
(updater: (params: URLSearchParams) => void) => {
const nextSearchParams = new URLSearchParams(searchParams.toString())
@@ -721,10 +719,17 @@ const ExperimentsView = ({
)
const loadExperiments = useCallback(
- (take: number, skip: number, showLoading = true, search?: string) => {
+ (
+ take: number,
+ skip: number,
+ showLoading = true,
+ search?: string,
+ mode: 'replace' | 'append' = 'replace',
+ ) => {
if (showLoading) {
setIsLoading(true)
}
+ experimentsRequestModeRef.current = mode
listFetcher.submit(
{
@@ -750,7 +755,19 @@ const ExperimentsView = ({
results: Experiment[]
total: number
}
- setExperiments(result.results)
+ if (experimentsRequestModeRef.current === 'append') {
+ setExperiments((prev) => {
+ const existingIds = new Set(
+ prev.map((experiment) => experiment.id),
+ )
+ const uniqueExperiments = result.results.filter(
+ (experiment) => !existingIds.has(experiment.id),
+ )
+ return [...prev, ...uniqueExperiments]
+ })
+ } else {
+ setExperiments(result.results)
+ }
setTotal(result.total)
setError(null)
} else if (listFetcher.data.error) {
@@ -776,8 +793,8 @@ const ExperimentsView = ({
if (actionFetcher.data.success) {
toast.success(t('experiments.deleted'))
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
@@ -788,8 +805,8 @@ const ExperimentsView = ({
if (actionFetcher.data.success) {
toast.success(t('experiments.started'))
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
@@ -800,8 +817,8 @@ const ExperimentsView = ({
if (actionFetcher.data.success) {
toast.success(t('experiments.paused'))
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
@@ -812,8 +829,8 @@ const ExperimentsView = ({
if (actionFetcher.data.success) {
toast.success(t('experiments.completed'))
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
@@ -826,7 +843,7 @@ const ExperimentsView = ({
actionFetcher.state,
t,
loadExperiments,
- page,
+ experiments.length,
filterQuery,
])
@@ -842,7 +859,6 @@ const ExperimentsView = ({
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setFilterQuery(value)
- setPage(1)
debouncedLoadExperiments(value)
},
[debouncedLoadExperiments],
@@ -855,14 +871,9 @@ const ExperimentsView = ({
}, [debouncedLoadExperiments])
useEffect(() => {
- loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
- true,
- filterQuery || undefined,
- )
+ loadExperiments(DEFAULT_EXPERIMENTS_TAKE, 0, true, filterQuery || undefined)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page])
+ }, [])
useEffect(() => {
if (experimentsRefreshTrigger > 0) {
@@ -875,27 +886,27 @@ const ExperimentsView = ({
return
}
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [experimentsRefreshTrigger, viewingResultsId, isModalOpen, page])
+ }, [experimentsRefreshTrigger, viewingResultsId, isModalOpen])
useEffect(() => {
if (!viewingResultsId && shouldRefreshListOnReturn) {
setShouldRefreshListOnReturn(false)
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [viewingResultsId, shouldRefreshListOnReturn, page])
+ }, [viewingResultsId, shouldRefreshListOnReturn])
const handleNewExperiment = useCallback(() => {
updateExperimentSearchParams((params) => {
@@ -925,12 +936,12 @@ const ExperimentsView = ({
const handleModalSuccess = useCallback(() => {
loadExperiments(
- DEFAULT_EXPERIMENTS_TAKE,
- (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ Math.max(experiments.length, DEFAULT_EXPERIMENTS_TAKE),
+ 0,
true,
filterQuery || undefined,
)
- }, [page, filterQuery, loadExperiments])
+ }, [experiments.length, filterQuery, loadExperiments])
const handleDeleteExperiment = useCallback(
(experimentId: string) => {
@@ -982,6 +993,27 @@ const ExperimentsView = ({
})
}, [updateExperimentSearchParams])
+ const canLoadMoreExperiments = experiments.length < total
+ const loadMoreExperiments = useCallback(() => {
+ if (isLoading || !canLoadMoreExperiments) {
+ return
+ }
+
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ experiments.length,
+ true,
+ filterQuery || undefined,
+ 'append',
+ )
+ }, [
+ canLoadMoreExperiments,
+ experiments.length,
+ filterQuery,
+ isLoading,
+ loadExperiments,
+ ])
+
if (error && isLoading === false && _isEmpty(experiments)) {
return (
<StatusPage
@@ -1091,16 +1123,13 @@ const ExperimentsView = ({
) : null}
</>
)}
- {pageAmount > 1 ? (
- <Pagination
- className='mt-4'
- page={page}
- pageAmount={pageAmount}
- setPage={setPage}
- total={total}
- pageSize={DEFAULT_EXPERIMENTS_TAKE}
- />
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreExperiments}
+ isLoading={!!isLoading}
+ onLoadMore={loadMoreExperiments}
+ disabled={!!isLoading}
+ className='mt-2'
+ />
<ExperimentSettingsModal
isOpen={isModalOpen}
diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
index ceda9eb86..874876eba 100644
--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
@@ -14,7 +14,6 @@ import {
UsersIcon,
PulseIcon,
CaretDownIcon,
- DownloadSimpleIcon,
CheckIcon,
XIcon,
} from '@phosphor-icons/react'
@@ -59,11 +58,11 @@ import type {
} from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Input from '~/ui/Input'
import Spin from '~/ui/icons/Spin'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
-import Pagination from '~/ui/Pagination'
import StatusPage from '~/ui/StatusPage'
import { Switch } from '~/ui/Switch'
import { Text } from '~/ui/Text'
@@ -471,30 +470,12 @@ const FeatureFlagRow = ({
/>
))}
</ul>
- {canLoadMoreProfiles ? (
- <button
- type='button'
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
- onLoadMoreProfiles(flag.id)
- }}
- disabled={profilesLoading}
- className={cx(
- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:bg-slate-950 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',
- {
- 'cursor-not-allowed opacity-50': profilesLoading,
- },
- )}
- >
- {profilesLoading ? (
- <Spin className='mr-2 size-5' />
- ) : (
- <DownloadSimpleIcon className='mr-2 h-5 w-5' />
- )}
- {t('featureFlags.loadMore')}
- </button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreProfiles}
+ isLoading={profilesLoading}
+ onLoadMore={() => onLoadMoreProfiles(flag.id)}
+ disabled={profilesLoading}
+ />
</>
)}
</div>
@@ -585,10 +566,10 @@ const FeatureFlagsViewInner = ({
Record<string, FeatureFlagStats | null>
>({})
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
- const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
const processedActionRef = useRef<string | null>(null)
+ const flagsRequestModeRef = useRef<'replace' | 'append'>('replace')
const isMountedRef = useRef(true)
@@ -634,13 +615,17 @@ const FeatureFlagsViewInner = ({
}
}, [revalidator.state, deferredData.featureFlagsData, isSearchMode])
- const pageAmount = Math.ceil(total / DEFAULT_FEATURE_FLAGS_TAKE)
-
const loadFlags = useCallback(
- (take: number, skip: number, search?: string) => {
+ (
+ take: number,
+ skip: number,
+ search?: string,
+ mode: 'replace' | 'append' = 'replace',
+ ) => {
if (listFetcher.state !== 'idle') {
return
}
+ flagsRequestModeRef.current = mode
setIsSearchMode(true)
listFetcher.submit(
@@ -669,8 +654,19 @@ const FeatureFlagsViewInner = ({
results: ProjectFeatureFlag[]
total: number
}
- setFlags(result.results)
+ if (flagsRequestModeRef.current === 'append') {
+ setFlags((prev) => {
+ const existingIds = new Set(prev.map((flag) => flag.id))
+ const uniqueFlags = result.results.filter(
+ (flag) => !existingIds.has(flag.id),
+ )
+ return [...prev, ...uniqueFlags]
+ })
+ } else {
+ setFlags(result.results)
+ }
setTotal(result.total)
+ setError(null)
} else if (listFetcher.data.error) {
setError(listFetcher.data.error)
}
@@ -689,16 +685,11 @@ const FeatureFlagsViewInner = ({
if (actionFetcher.data.intent === 'delete-feature-flag') {
if (actionFetcher.data.success) {
toast.success(t('featureFlags.deleted'))
- if (page === 1 && !filterQuery) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadFlags(
- DEFAULT_FEATURE_FLAGS_TAKE,
- (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
- filterQuery || undefined,
- )
- }
+ loadFlags(
+ Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
+ 0,
+ filterQuery || undefined,
+ )
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
@@ -720,9 +711,8 @@ const FeatureFlagsViewInner = ({
actionFetcher.state,
t,
loadFlags,
- page,
+ flags.length,
filterQuery,
- revalidator,
])
// Debounced search to avoid excessive API calls
@@ -739,7 +729,6 @@ const FeatureFlagsViewInner = ({
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setFilterQuery(value)
- setPage(1) // Reset to first page when searching
debouncedLoadFlags(value)
},
[debouncedLoadFlags],
@@ -878,31 +867,14 @@ const FeatureFlagsViewInner = ({
[loadFlagProfiles],
)
- // Handle page changes - use fetcher for pagination
+ // Refresh feature flags data when refresh button is clicked
useEffect(() => {
- if (page > 1 || isSearchMode) {
+ if (featureFlagsRefreshTrigger > 0) {
loadFlags(
- DEFAULT_FEATURE_FLAGS_TAKE,
- (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
+ Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
+ 0,
filterQuery || undefined,
)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page])
-
- // Refresh feature flags data when refresh button is clicked
- useEffect(() => {
- if (featureFlagsRefreshTrigger > 0) {
- if (page === 1 && !filterQuery) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadFlags(
- DEFAULT_FEATURE_FLAGS_TAKE,
- (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
- filterQuery || undefined,
- )
- }
setFlagStats({})
if (expandedFlagId) {
setFlagProfiles((prev) => ({ [expandedFlagId]: prev[expandedFlagId] }))
@@ -952,16 +924,11 @@ const FeatureFlagsViewInner = ({
}
const handleModalSuccess = () => {
- if (page === 1 && !filterQuery) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadFlags(
- DEFAULT_FEATURE_FLAGS_TAKE,
- (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
- filterQuery || undefined,
- )
- }
+ loadFlags(
+ Math.max(flags.length, DEFAULT_FEATURE_FLAGS_TAKE),
+ 0,
+ filterQuery || undefined,
+ )
}
const handleDeleteFlag = useCallback(
@@ -986,6 +953,20 @@ const FeatureFlagsViewInner = ({
[actionFetcher],
)
+ const canLoadMoreFlags = flags.length < total
+ const loadMoreFlags = useCallback(() => {
+ if (isLoading || !canLoadMoreFlags) {
+ return
+ }
+
+ loadFlags(
+ DEFAULT_FEATURE_FLAGS_TAKE,
+ flags.length,
+ filterQuery || undefined,
+ 'append',
+ )
+ }, [canLoadMoreFlags, filterQuery, flags.length, isLoading, loadFlags])
+
if (error && !isLoading) {
return (
<StatusPage
@@ -1093,16 +1074,13 @@ const FeatureFlagsViewInner = ({
) : null}
</>
)}
- {pageAmount > 1 ? (
- <Pagination
- className='mt-4'
- page={page}
- pageAmount={pageAmount}
- setPage={setPage}
- total={total}
- pageSize={DEFAULT_FEATURE_FLAGS_TAKE}
- />
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreFlags}
+ isLoading={isLoading}
+ onLoadMore={loadMoreFlags}
+ disabled={isLoading}
+ className='mt-2'
+ />
<FeatureFlagSettingsModal
isOpen={isModalOpen}
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index 20c9f5818..c11e2e2a7 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -72,9 +72,9 @@ import BillboardChart from '~/ui/BillboardChart'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Spin from '~/ui/icons/Spin'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
-import Pagination from '~/ui/Pagination'
import ProgressRing from '~/ui/ProgressRing'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
@@ -810,10 +810,10 @@ const GoalsViewInner = ({
{},
)
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
- const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
+ const goalsRequestModeRef = useRef<'replace' | 'append'>('replace')
const filtersKey = useMemo(() => JSON.stringify(filters), [filters])
// Expanded goal state
@@ -855,14 +855,11 @@ const GoalsViewInner = ({
}
}, [revalidator.state, deferredData.goalsData, isSearchMode])
- const pageAmount = Math.ceil(total / DEFAULT_GOALS_TAKE)
-
// Debounced search handler
// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedSetSearch = useCallback(
_debounce((value: string) => {
setDebouncedSearch(value)
- setPage(1) // Reset to first page when search changes
}, 300),
[],
)
@@ -876,8 +873,14 @@ const GoalsViewInner = ({
}, [filterQuery, debouncedSetSearch])
const loadGoals = useCallback(
- (take: number, skip: number, search?: string) => {
+ (
+ take: number,
+ skip: number,
+ search?: string,
+ mode: 'replace' | 'append' = 'replace',
+ ) => {
if (fetcher.state !== 'idle') return
+ goalsRequestModeRef.current = mode
setIsSearchMode(true)
setError(null)
@@ -906,7 +909,17 @@ const GoalsViewInner = ({
results: Goal[]
total: number
}
- setGoals(result.results)
+ if (goalsRequestModeRef.current === 'append') {
+ setGoals((prev) => {
+ const existingIds = new Set(prev.map((goal) => goal.id))
+ const uniqueGoals = result.results.filter(
+ (goal) => !existingIds.has(goal.id),
+ )
+ return [...prev, ...uniqueGoals]
+ })
+ } else {
+ setGoals(result.results)
+ }
setTotal(result.total)
setError(null)
} else if (fetcher.data.error) {
@@ -1002,17 +1015,12 @@ const GoalsViewInner = ({
[timeBucket, timeFormat, timezone],
)
- // Handle page/search changes - use fetcher for pagination
useEffect(() => {
- if (page > 1 || debouncedSearch || isSearchMode) {
- loadGoals(
- DEFAULT_GOALS_TAKE,
- (page - 1) * DEFAULT_GOALS_TAKE,
- debouncedSearch || undefined,
- )
+ if (debouncedSearch || isSearchMode) {
+ loadGoals(DEFAULT_GOALS_TAKE, 0, debouncedSearch || undefined)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page, debouncedSearch])
+ }, [debouncedSearch])
useEffect(() => {
// Load stats for all goals when goals change or date range changes
@@ -1035,16 +1043,11 @@ const GoalsViewInner = ({
// Refresh goals data when refresh button is clicked
useEffect(() => {
if (goalsRefreshTrigger > 0) {
- if (page === 1 && !debouncedSearch) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadGoals(
- DEFAULT_GOALS_TAKE,
- (page - 1) * DEFAULT_GOALS_TAKE,
- debouncedSearch || undefined,
- )
- }
+ loadGoals(
+ Math.max(goals.length, DEFAULT_GOALS_TAKE),
+ 0,
+ debouncedSearch || undefined,
+ )
// Clear cached chart data for non-expanded goals, silently refresh expanded goal
if (expandedGoalId) {
setGoalChartData((prev) => ({
@@ -1074,36 +1077,26 @@ const GoalsViewInner = ({
}
const handleModalSuccess = () => {
- if (page === 1 && !debouncedSearch) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadGoals(
- DEFAULT_GOALS_TAKE,
- (page - 1) * DEFAULT_GOALS_TAKE,
- debouncedSearch || undefined,
- )
- }
+ loadGoals(
+ Math.max(goals.length, DEFAULT_GOALS_TAKE),
+ 0,
+ debouncedSearch || undefined,
+ )
}
// Handle fetcher responses for delete
useEffect(() => {
if (fetcher.data?.success && fetcher.data?.intent === 'delete-goal') {
toast.success(t('goals.deleted'))
- if (page === 1 && !debouncedSearch) {
- setIsSearchMode(false)
- revalidator.revalidate()
- } else {
- loadGoals(
- DEFAULT_GOALS_TAKE,
- (page - 1) * DEFAULT_GOALS_TAKE,
- debouncedSearch || undefined,
- )
- }
+ loadGoals(
+ Math.max(goals.length, DEFAULT_GOALS_TAKE),
+ 0,
+ debouncedSearch || undefined,
+ )
} else if (fetcher.data?.error && fetcher.data?.intent === 'delete-goal') {
toast.error(fetcher.data.error)
}
- }, [fetcher.data, t, page, debouncedSearch, revalidator]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [fetcher.data, t, goals.length, debouncedSearch, loadGoals]) // eslint-disable-line react-hooks/exhaustive-deps
const handleDeleteGoal = (goalId: string) => {
const formData = new FormData()
@@ -1112,6 +1105,20 @@ const GoalsViewInner = ({
fetcher.submit(formData, { method: 'post' })
}
+ const canLoadMoreGoals = goals.length < total
+ const loadMoreGoals = useCallback(() => {
+ if (isLoading || !canLoadMoreGoals) {
+ return
+ }
+
+ loadGoals(
+ DEFAULT_GOALS_TAKE,
+ goals.length,
+ debouncedSearch || undefined,
+ 'append',
+ )
+ }, [canLoadMoreGoals, debouncedSearch, goals.length, isLoading, loadGoals])
+
if (error && !isLoading) {
return (
<StatusPage
@@ -1214,16 +1221,13 @@ const GoalsViewInner = ({
) : null}
</>
)}
- {pageAmount > 1 ? (
- <Pagination
- className='mt-4'
- page={page}
- pageAmount={pageAmount}
- setPage={setPage}
- total={total}
- pageSize={DEFAULT_GOALS_TAKE}
- />
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreGoals}
+ isLoading={isLoading}
+ onLoadMore={loadMoreGoals}
+ disabled={isLoading}
+ className='mt-2'
+ />
<GoalSettingsModal
isOpen={isModalOpen}
diff --git a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
index 4a8ee45db..e609832de 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
@@ -28,7 +28,7 @@ import {
Session,
} from '~/lib/models/Project'
import { useTheme } from '~/providers/ThemeProvider'
-import Button from '~/ui/Button'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
@@ -572,16 +572,13 @@ export const ProfileDetails = ({
hideUserDetails
currency={currency}
/>
- {canLoadMoreSessions ? (
- <Button
- onClick={onLoadMoreSessions}
- disabled={!!sessionsLoading}
- loading={!!sessionsLoading}
- className='mt-4 w-full'
- >
- {t('project.loadMore')}
- </Button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreSessions}
+ isLoading={!!sessionsLoading}
+ onLoadMore={onLoadMoreSessions}
+ disabled={!!sessionsLoading}
+ className='mt-2'
+ />
</>
)}
</div>
diff --git a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
index 90e773a4c..344644196 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
@@ -1,6 +1,4 @@
-import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
-import { DownloadSimpleIcon } from '@phosphor-icons/react'
import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
@@ -30,6 +28,7 @@ import {
useCurrentProject,
useProjectPassword,
} from '~/providers/CurrentProjectProvider'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import LoadingBar from '~/ui/LoadingBar'
import Filters from '../../View/components/Filters'
@@ -449,24 +448,13 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
<NoProfiles filters={filters} />
) : null}
<Profiles profiles={profiles} timeFormat={timeFormat} />
- {canLoadMoreProfiles ? (
- <button
- type='button'
- title={t('project.loadMore')}
- onClick={() => loadProfiles()}
- className={cx(
- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:bg-slate-950 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',
- {
- 'cursor-not-allowed opacity-50':
- profilesLoading || profilesLoading === null,
- hidden: profilesLoading && _isEmpty(profiles),
- },
- )}
- >
- <DownloadSimpleIcon className='mr-2 h-5 w-5' />
- {t('project.loadMore')}
- </button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreProfiles}
+ isLoading={profilesLoading || profilesLoading === null}
+ onLoadMore={() => loadProfiles()}
+ disabled={profilesLoading || profilesLoading === null}
+ className={profilesLoading && _isEmpty(profiles) ? 'hidden' : ''}
+ />
</>
)
}
diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
index fee1ce40d..95e626de8 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
@@ -1,6 +1,4 @@
-import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
-import { DownloadSimpleIcon } from '@phosphor-icons/react'
import {
Component,
useState,
@@ -33,7 +31,7 @@ import {
import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import type { ProjectLoaderData } from '~/routes/projects.$id'
-import Spin from '~/ui/icons/Spin'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import StatusPage from '~/ui/StatusPage'
@@ -290,9 +288,7 @@ const SessionsViewInner = ({
}
// Ignore stale proxy responses that were initiated before the last loader update
- if (
- proxyRequest.loaderUpdateCounter < loaderUpdateCounterRef.current
- ) {
+ if (proxyRequest.loaderUpdateCounter < loaderUpdateCounterRef.current) {
return
}
@@ -303,9 +299,7 @@ const SessionsViewInner = ({
const visibleSessions = newSessions.slice(0, proxyRequest.limit)
setSessions(visibleSessions)
setSessionsSkip(visibleSessions.length)
- setCanLoadMoreSessions(
- newSessions.length > (proxyRequest.limit || 0),
- )
+ setCanLoadMoreSessions(newSessions.length > (proxyRequest.limit || 0))
hasShownContentRef.current = !_isEmpty(visibleSessions)
} else {
setSessions((prev) => {
@@ -453,27 +447,13 @@ const SessionsViewInner = ({
timeFormat={timeFormat}
currency={project?.revenueCurrency}
/>
- {canLoadMoreSessions ? (
- <button
- type='button'
- title={t('project.loadMore')}
- onClick={loadMoreSessions}
- className={cx(
- 'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden dark:bg-slate-950 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300',
- {
- 'cursor-not-allowed opacity-50': sessionsLoading,
- hidden: sessionsLoading && _isEmpty(sessions),
- },
- )}
- >
- {sessionsLoading ? (
- <Spin className='mr-2 size-5' />
- ) : (
- <DownloadSimpleIcon className='mr-2 h-5 w-5' />
- )}
- {t('project.loadMore')}
- </button>
- ) : null}
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreSessions}
+ isLoading={sessionsLoading}
+ onLoadMore={loadMoreSessions}
+ disabled={sessionsLoading}
+ className={sessionsLoading && _isEmpty(sessions) ? 'hidden' : ''}
+ />
</div>
</>
)
diff --git a/web/app/ui/InfiniteScrollTrigger.tsx b/web/app/ui/InfiniteScrollTrigger.tsx
new file mode 100644
index 000000000..0e730593c
--- /dev/null
+++ b/web/app/ui/InfiniteScrollTrigger.tsx
@@ -0,0 +1,86 @@
+import cx from 'clsx'
+import { useEffect, useRef, type RefObject } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import Spin from '~/ui/icons/Spin'
+
+interface InfiniteScrollTriggerProps {
+ hasMore: boolean
+ isLoading: boolean
+ onLoadMore: () => void
+ className?: string
+ disabled?: boolean
+ root?: RefObject<Element | null>
+ rootMargin?: string
+}
+
+const InfiniteScrollTrigger = ({
+ hasMore,
+ isLoading,
+ onLoadMore,
+ className,
+ disabled = false,
+ root,
+ rootMargin = '240px',
+}: InfiniteScrollTriggerProps) => {
+ const { t } = useTranslation('common')
+ const sentinelRef = useRef<HTMLDivElement | null>(null)
+ const pendingRef = useRef(false)
+
+ useEffect(() => {
+ if (!isLoading) {
+ pendingRef.current = false
+ }
+ }, [isLoading])
+
+ useEffect(() => {
+ const sentinel = sentinelRef.current
+ if (!sentinel || !hasMore || disabled) {
+ return undefined
+ }
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries[0]?.isIntersecting && !isLoading && !pendingRef.current) {
+ pendingRef.current = true
+ onLoadMore()
+ }
+ },
+ {
+ root: root?.current || null,
+ rootMargin,
+ },
+ )
+
+ observer.observe(sentinel)
+ return () => observer.disconnect()
+ }, [disabled, hasMore, isLoading, onLoadMore, root, rootMargin])
+
+ if (!hasMore) {
+ return null
+ }
+
+ return (
+ <div
+ ref={sentinelRef}
+ role={isLoading ? 'status' : undefined}
+ aria-live={isLoading ? 'polite' : undefined}
+ className={cx(
+ 'flex min-h-10 items-center justify-center py-3',
+ className,
+ )}
+ >
+ <Spin
+ className={cx(
+ 'size-5 text-gray-400 transition-opacity duration-150 ease-out dark:text-gray-500',
+ !isLoading && 'opacity-0',
+ )}
+ />
+ <span className='sr-only'>
+ {isLoading ? t('common.loading') : t('project.loadMore')}
+ </span>
+ </div>
+ )
+}
+
+export default InfiniteScrollTrigger