feat(ui): page, search and filter packages on the server

The package list loaded every package, then grouped and paged in the
browser. The dashboard did the same to show ten recent rows.

- PackageList asks the server for one page of 25 groups. The registry
  filter and a debounced search box (300 ms) change the request. A newer
  request replaces the answer of an older one.
- Dashboard loads a page of 10 groups sorted by cached_at, newest first,
  and runs its stats, recent list and chart requests in parallel.
- Stats already used /api/stats only and does not change.
- The store keeps the loading flag on until the last overlapping request
  settles. Deleting a package no longer reloads the full list, and the
  list reloads its own page instead.
- VulnerablePackages keeps the unpaginated call because it filters on
  scan results in the browser.
This commit is contained in:
2026-11-23 13:26:50 +00:00
parent db5ca2539f
commit ac4f39322c
7 changed files with 423 additions and 158 deletions
+16 -39
View File
@@ -12,7 +12,7 @@ describe('Dashboard.vue', () => {
// Mock the fetch functions to prevent actual API calls
const store = usePackageStore()
vi.spyOn(store, 'fetchStats').mockResolvedValue()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
})
it('renders dashboard component', () => {
@@ -127,7 +127,7 @@ describe('Dashboard.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
store.recentPackages = [
{
id: '1',
registry: 'npm',
@@ -144,22 +144,12 @@ describe('Dashboard.vue', () => {
expect(wrapper.text()).toContain('Recent packages')
})
it('shows recent packages sorted by cached_at', async () => {
it('lists recent packages in the order the store holds them, newest first', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = [
{
id: '1',
registry: 'npm',
name: 'old-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
store.recentPackages = [
{
id: '2',
registry: 'npm',
@@ -170,46 +160,33 @@ describe('Dashboard.vue', () => {
last_accessed: '2025-01-02T00:00:00Z',
download_count: 5,
},
{
id: '1',
registry: 'npm',
name: 'old-package',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
await wrapper.vm.$nextTick()
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
// new-package should appear before old-package since it's more recent
// The store sorts by cached_at; the view keeps that order
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
recentPackagesSection.indexOf('old-package')
)
})
it('limits recent packages to 10 items', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = Array.from({ length: 15 }, (_, i) => ({
id: `${i}`,
registry: 'npm',
name: `package${i}`,
version: '1.0.0',
size: 1024,
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
download_count: i,
}))
await wrapper.vm.$nextTick()
const recentSection = wrapper.text().split('Recent packages')[1]
// Count how many "package" strings appear (each package has the word "package" in its name)
const packageCount = (recentSection.match(/package\d+/g) || []).length
expect(packageCount).toBeLessThanOrEqual(10)
})
it('handles empty packages array', async () => {
const wrapper = mount(Dashboard)
const store = usePackageStore()
store.loading = false
store.packages = []
store.recentPackages = []
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('0')
+4 -14
View File
@@ -75,7 +75,7 @@
</CardHeader>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="recentPackages.length === 0"
size="sm"
:icon="faBoxOpen"
title="No packages cached yet"
@@ -140,7 +140,7 @@ import {
} from '@/lib/icons'
const store = usePackageStore()
const { packages, stats, loading, error } = storeToRefs(store)
const { recentPackages, stats, loading, error } = storeToRefs(store)
const rt = useRealtimeStore()
const { lastStats, events: rtEvents } = storeToRefs(rt)
@@ -259,7 +259,7 @@ const packageColumns: DataTableColumn<Package>[] = [
function refresh() {
void store.fetchStats()
void store.fetchPackages()
void store.fetchRecentPackages()
}
function getChartLabel(index: number): string {
@@ -291,14 +291,6 @@ function getChartLabel(index: number): string {
return labels[selectedPeriod.value]?.(index) || `${index}`
}
// API returns clean, deduplicated data - just sort and limit
const recentPackages = computed(() => {
return packages.value
.slice()
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
.slice(0, 10)
})
// Watch for period changes and fetch new data
watch(selectedPeriod, () => {
fetchTimeSeriesData()
@@ -309,9 +301,7 @@ onMounted(async () => {
// initial polling resolves. Singleton survives navigation, so we
// intentionally do not disconnect on unmount.
rt.connect()
await store.fetchStats()
await store.fetchPackages()
await fetchTimeSeriesData()
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
})
</script>
+105 -26
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
@@ -6,6 +6,14 @@ import { defineComponent, h } from 'vue'
import PackageList from './PackageList.vue'
import { usePackageStore } from '../stores/packages'
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
// A page as the server sends it: whole groups, flattened to rows.
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
}
const Stub = defineComponent({ render: () => h('div') })
function createTestRouter(): Router {
@@ -41,7 +49,7 @@ describe('PackageList.vue', () => {
setActivePinia(createPinia())
// Prevent real network calls from store actions on mount
const store = usePackageStore()
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
})
it('renders package list component', async () => {
@@ -74,7 +82,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = []
setRows(store, [])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('No packages cached yet')
@@ -85,7 +93,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -96,17 +104,17 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
expect(wrapper.text()).toContain('1 version')
})
it('calls fetchPackages on mount', async () => {
it('asks the server for the first page on mount', async () => {
const store = usePackageStore()
// beforeEach already spied with mockResolvedValue; reuse that spy
const fetchSpy = store.fetchPackages as ReturnType<typeof vi.spyOn>
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
await mountWithRouter()
@@ -119,7 +127,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -140,7 +148,7 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-02T00:00:00Z',
download_count: 20,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('test-package')
@@ -152,7 +160,7 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '1',
registry: 'npm',
@@ -163,7 +171,7 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 10,
},
]
])
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('1 MB')
@@ -174,7 +182,17 @@ describe('PackageList.vue', () => {
const store = usePackageStore()
store.loading = false
store.packages = [
setRows(store, [
{
id: '3',
registry: 'go',
name: 'go-module',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 3,
},
{
id: '1',
registry: 'npm',
@@ -195,21 +213,11 @@ describe('PackageList.vue', () => {
last_accessed: '2025-01-01T00:00:00Z',
download_count: 5,
},
{
id: '3',
registry: 'go',
name: 'go-module',
version: '1.0.0',
size: 1024,
cached_at: '2025-01-01T00:00:00Z',
last_accessed: '2025-01-01T00:00:00Z',
download_count: 3,
},
]
])
await wrapper.vm.$nextTick()
// Verify that all registry badges are displayed
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
// The server sends groups in name order: go-module, npm-package, python-package
expect(wrapper.text()).toContain('npm')
expect(wrapper.text()).toContain('pypi')
expect(wrapper.text()).toContain('go')
@@ -223,7 +231,7 @@ describe('PackageList.vue', () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.packages = [
setRows(store, [
{
id: '1',
registry: 'pypi',
@@ -235,7 +243,7 @@ describe('PackageList.vue', () => {
last_accessed: '2026-11-23T00:00:00Z',
download_count: 0,
},
]
])
await wrapper.vm.$nextTick()
await wrapper.find('button[aria-expanded]').trigger('click')
await wrapper.vm.$nextTick()
@@ -243,4 +251,75 @@ describe('PackageList.vue', () => {
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
describe('server-side paging, search and registry filter', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('debounces the search box into one request with q and page 1', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
const input = wrapper.find('input[type="search"], input')
await input.setValue('l')
await input.setValue('le')
await input.setValue('left')
expect(fetchSpy).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(300)
expect(fetchSpy).toHaveBeenCalledTimes(1)
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
})
it('sends the registry of the route with every request', async () => {
const router = createTestRouter()
router.push('/packages/pypi')
await router.isReady()
const store = usePackageStore()
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
})
it('pages through the server, not the loaded rows', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
store.packagePage = {
packages: [
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
],
totalGroups: 60,
page: 1,
pageSize: 25,
}
await wrapper.vm.$nextTick()
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
fetchSpy.mockClear()
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
await next!.trigger('click')
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
})
it('says no packages match when a filter empties the page', async () => {
const wrapper = await mountWithRouter()
const store = usePackageStore()
store.loading = false
setRows(store, [])
await wrapper.find('input').setValue('zzz')
await vi.advanceTimersByTimeAsync(300)
expect(wrapper.text()).toContain('No packages match')
expect(wrapper.text()).not.toContain('No packages cached yet')
})
})
})
+66 -69
View File
@@ -2,7 +2,7 @@
<div class="flex flex-col gap-6">
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
<template #actions>
<Button variant="outline" :icon-start="faRotateRight" @click="store.fetchPackages()">Refresh</Button>
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
</template>
</PageHeader>
@@ -23,26 +23,26 @@
variant="card"
title="Could not load packages"
:message="error"
@retry="store.fetchPackages()"
@retry="load()"
/>
<Card v-else>
<CardContent>
<EmptyState
v-if="packages.length === 0"
v-if="totalGroups === 0 && !filtersActive"
:icon="faBoxOpen"
title="No packages cached yet"
description="Packages will appear here once they are downloaded through the proxy."
/>
<EmptyState
v-else-if="groupedPackages.length === 0"
v-else-if="groups.length === 0"
:icon="faMagnifyingGlass"
title="No packages match"
description="Change the registry filter or the search text."
/>
<Accordion v-else type="multiple" class="w-full">
<AccordionItem
v-for="group in groupedPackages"
v-for="group in groups"
:key="`${group.registry}:${group.name}`"
:value="`${group.registry}:${group.name}`"
>
@@ -110,12 +110,12 @@
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
<p class="m-0 text-sm text-muted-foreground">
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
</p>
<Pagination
:page="currentPage"
:total="allGroupedPackages.length"
:page-size="itemsPerPage"
:total="totalGroups"
:page-size="PAGE_SIZE"
:show-edges="false"
@update:page="changePage"
/>
@@ -136,7 +136,7 @@
</template>
<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { usePackageStore, type Package } from '../stores/packages'
@@ -179,7 +179,7 @@ const route = useRoute()
const router = useRouter()
const store = usePackageStore()
const toasts = useToastStore()
const { packages, loading, error } = storeToRefs(store)
const { packagePage, loading, error } = storeToRefs(store)
const showDeleteModal = ref(false)
const packageToDelete = ref<Package | null>(null)
@@ -190,88 +190,77 @@ const REGISTRY_OPTIONS = [
{ value: 'go', label: 'Go' },
]
const PAGE_SIZE = 25
const SEARCH_DEBOUNCE_MS = 300
const selectedRegistry = ref<string>(props.registry || 'all')
const searchTerm = ref<string>('')
// What the server was last asked: the search text lags the input by the debounce.
const activeQuery = ref<string>('')
const currentPage = ref<number>(1)
const itemsPerPage = ref<number>(10)
// Group packages by name
const allGroupedPackages = computed(() => {
const groups = new Map<string, Package[]>()
const totalGroups = computed(() => packagePage.value.totalGroups)
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
// Filter packages by selected registry and search term
let filteredPackages = selectedRegistry.value === 'all'
? packages.value
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
// Apply search filter if search term exists
if (searchTerm.value.trim()) {
const searchLower = searchTerm.value.toLowerCase()
filteredPackages = filteredPackages.filter(pkg =>
pkg.name.toLowerCase().includes(searchLower) ||
displayVersion(pkg).toLowerCase().includes(searchLower) ||
pkg.version.toLowerCase().includes(searchLower)
)
// The server pages whole (registry, name) groups and sends every version row of each.
const groups = computed(() => {
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
for (const pkg of packagePage.value.packages) {
const key = `${pkg.registry}\u0000${pkg.name}`
let group = byKey.get(key)
if (!group) {
group = { registry: pkg.registry, name: pkg.name, versions: [] }
byKey.set(key, group)
}
group.versions.push(pkg)
}
return Array.from(byKey.values()).map((group) => ({
...group,
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
}))
})
filteredPackages.forEach(pkg => {
const key = `${pkg.registry}:${pkg.name}`
if (!groups.has(key)) {
groups.set(key, [])
}
groups.get(key)!.push(pkg)
async function load() {
await store.fetchPackagePage({
page: currentPage.value,
pageSize: PAGE_SIZE,
registry: selectedRegistry.value,
q: activeQuery.value,
})
// Convert to array and sort versions within each group
return Array.from(groups.entries()).map(([key, versions]) => {
const [registry, name] = key.split(':')
return {
registry,
name,
versions: versions.sort((a, b) =>
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
),
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
}
}).sort((a, b) => a.name.localeCompare(b.name))
})
// Pagination
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
const groupedPackages = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage.value
const end = start + itemsPerPage.value
return allGroupedPackages.value.slice(start, end)
})
}
function changePage(page: number) {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page
void load()
// Scroll to top of packages list
window.scrollTo({ top: 0, behavior: 'smooth' })
}
}
// Reset to page 1 when filters change
function resetPagination() {
currentPage.value = 1
}
// Watch for filter/search changes and reset pagination
watch([selectedRegistry, searchTerm], () => {
resetPagination()
// A burst of keystrokes asks the server once.
let searchTimer: ReturnType<typeof setTimeout> | undefined
watch(searchTerm, (term) => {
clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
if (term === activeQuery.value) return
activeQuery.value = term
currentPage.value = 1
void load()
}, SEARCH_DEBOUNCE_MS)
})
onBeforeUnmount(() => clearTimeout(searchTimer))
// Watch for route parameter changes to update filter
watch(() => route.params.registry, (newRegistry) => {
selectedRegistry.value = (newRegistry as string) || 'all'
currentPage.value = 1
void load()
})
onMounted(async () => {
await store.fetchPackages()
})
onMounted(load)
function confirmDelete(pkg: Package) {
packageToDelete.value = pkg
@@ -289,7 +278,15 @@ async function deletePackage() {
toasts.error('Could not delete package', `${label}: ${store.error}`)
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
store.error = null
} else toasts.success('Package deleted', label)
} else {
toasts.success('Package deleted', label)
await load()
// Deleting the last group of the last page leaves that page empty.
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
currentPage.value = Math.max(totalPages.value, 1)
await load()
}
}
}
function showVulnerabilityDetails(registry: string, name: string, version: string) {
+1 -1
View File
@@ -208,7 +208,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
it('PackageList still fetches through the store on mount', async () => {
await smoke(PackageList, '/packages')
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
})
})