diff --git a/frontend/src/views/knowledge/gallery/GalleryViewer.vue b/frontend/src/views/knowledge/gallery/GalleryViewer.vue index 712f20ef..0464c357 100644 --- a/frontend/src/views/knowledge/gallery/GalleryViewer.vue +++ b/frontend/src/views/knowledge/gallery/GalleryViewer.vue @@ -12,14 +12,11 @@ export interface GalleryAttrRow { } const props = defineProps<{ - /** The images of the page on screen; the viewer walks them in order. */ + /** The loaded images; the viewer walks them in order. */ items: ImageAsset[] index: number - /** Position of items[0] in the whole result set, so the counter and the - * prev/next bounds speak about every image, not just this page. */ - offset: number total: number - /** A neighbouring page is being fetched; navigation waits for it. */ + /** More images are being fetched; navigation waits for them. */ loading: boolean thumbUrls: Record resolveSrc: (url: string) => Promise @@ -29,8 +26,8 @@ const props = defineProps<{ const emit = defineEmits<{ (e: 'close'): void (e: 'select', index: number): void - /** Step past the page edge; the gallery loads the neighbouring page. */ - (e: 'step', delta: 1 | -1): void + /** Step past the loaded edge; the gallery loads more images. */ + (e: 'load-more'): void (e: 'open-source', knowledgeId: string): void }>() @@ -38,20 +35,19 @@ const NS = 'knowledgeEditor.wikiBrowser.gallery' const { t, locale } = useI18n() const current = computed(() => props.items[props.index] ?? null) -const position = computed(() => props.offset + props.index + 1) +const position = computed(() => props.index + 1) const hasPrev = computed(() => position.value > 1) const hasNext = computed(() => position.value < props.total) function prev(): void { if (props.loading || !hasPrev.value) return - if (props.index > 0) emit('select', props.index - 1) - else emit('step', -1) + emit('select', props.index - 1) } function next(): void { if (props.loading || !hasNext.value) return if (props.index < props.items.length - 1) emit('select', props.index + 1) - else emit('step', 1) + else emit('load-more') } // --------------------------------------------------------------------------- @@ -431,7 +427,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey)) type="button" class="igv-strip__item" :class="{ 'is-current': i === index }" - :aria-label="img.caption || String(offset + i + 1)" + :aria-label="img.caption || String(i + 1)" @click="emit('select', i)" > diff --git a/frontend/src/views/knowledge/gallery/ImageGallery.test.ts b/frontend/src/views/knowledge/gallery/ImageGallery.test.ts new file mode 100644 index 00000000..b879ae45 --- /dev/null +++ b/frontend/src/views/knowledge/gallery/ImageGallery.test.ts @@ -0,0 +1,147 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' +import vm from 'node:vm' +import ts from 'typescript' +import * as vue from 'vue' +import type { ImageAsset, ImageListParams, ImageListResult } from '@/api/image-gallery' + +// Exercise the component's actual loading and viewer logic with deferred API +// responses so races and retries are deterministic, without a live backend. +const source = readFileSync(new URL('./ImageGallery.vue', import.meta.url), 'utf8') + .split('')[0] +const compiled = ts.transpileModule(`${source}\nexport { + items, page, total, loading, error, keyword, hasMore, viewerIndex, viewerOpen, + reload, loadMore, openViewer, onViewerLoadMore, initGallery, +}`, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText + +function setup() { + const calls: Array<{ + kb: string; params: ImageListParams + resolve: (value: ImageListResult) => void; reject: (reason: Error) => void + }> = [] + const props = vue.reactive({ knowledgeBaseId: 'kb-1' }) + const modules: Record = { + vue: { ...vue, onMounted() {}, onBeforeUnmount() {}, watch() {} }, + 'vue-i18n': { useI18n: () => ({ t: (key: string) => key, te: () => false }) }, + '@/api/image-gallery': { + listGalleryImages: (kb: string, params: ImageListParams) => new Promise((resolve, reject) => { + calls.push({ kb, params, resolve, reject }) + }), + fetchGalleryConfig: async () => ({ attributes: [], attribute_sources: [], mode: 'all', status: {} }), + }, + '@/api/auth': { updateMyPreferences: async () => {} }, + './galleryImageSrc': { galleryImageRequest: () => null }, + } + const state: any = {} + vm.runInNewContext(compiled, { + exports: state, defineProps: () => props, defineEmits: () => () => {}, + setTimeout, clearTimeout, URL, console, Error, + require: (id: string) => { + assert.ok(id in modules, `unexpected import ${id}`) + return modules[id] + }, + }) + const respond = (index: number, ids: string[], total = 60) => calls[index].resolve({ + items: ids.map(id => ({ id, url: `https://example.com/${id}.png` }) as ImageAsset), + total, page: calls[index].params.page!, pageSize: 24, + }) + const ids = () => Array.from(state.items.value, (img: ImageAsset) => img.id) + return { state, calls, props, respond, ids } +} + +test('scroll appends unique images, serializes requests, and stops at the total', async () => { + const { state, calls, respond, ids } = setup() + const first = state.reload() + respond(0, ['a', 'b']) + await first + const next = state.loadMore() + assert.equal(await state.loadMore(), false) + assert.equal(calls.length, 2) + assert.equal(calls[1].params.page, 2) + respond(1, ['b', 'c'], 48) + await next + assert.deepEqual(ids(), ['a', 'b', 'c']) + assert.equal(state.hasMore.value, false) + assert.equal(await state.loadMore(), false) +}) + +test('append failures retain cards and retry the same page', async () => { + const { state, calls, respond, ids } = setup() + const first = state.reload() + respond(0, ['a']) + await first + const next = state.loadMore() + calls[1].reject(new Error('offline')) + assert.equal(await next, false) + assert.deepEqual(ids(), ['a']) + assert.equal(state.page.value, 1) + assert.equal(state.error.value, 'offline') + const retry = state.loadMore() + assert.equal(calls[2].params.page, 2) + respond(2, ['b']) + await retry + assert.deepEqual(ids(), ['a', 'b']) + assert.equal(state.error.value, '') +}) + +test('a new search discards an older append and resets the viewer', async () => { + const { state, calls, respond, ids } = setup() + const first = state.reload() + respond(0, ['a']) + await first + state.openViewer(0) + const older = state.onViewerLoadMore() + state.keyword.value = 'new search' + const fresh = state.reload() + assert.equal(state.viewerOpen.value, false) + assert.equal(calls[2].params.keyword, 'new search') + respond(2, ['new'], 1) + await fresh + respond(1, ['old']) + await older + assert.deepEqual(ids(), ['new']) + assert.equal(state.total.value, 1) +}) + +test('viewer loads past the last card without dropping previous images', async () => { + const { state, respond, ids } = setup() + const first = state.reload() + respond(0, ['a', 'b']) + await first + state.openViewer(1) + const step = state.onViewerLoadMore() + respond(1, ['c', 'd']) + await step + assert.deepEqual(ids(), ['a', 'b', 'c', 'd']) + assert.equal(state.viewerIndex.value, 2) + assert.equal(state.viewerOpen.value, true) +}) + +test('switching knowledge bases invalidates the previous request immediately', async () => { + const { state, props, calls, respond, ids } = setup() + const old = state.reload() + props.knowledgeBaseId = 'kb-2' + const fresh = state.initGallery() + respond(0, ['old']) + await old + await vue.nextTick() + assert.deepEqual(ids(), []) + assert.equal(calls[1].kb, 'kb-2') + respond(1, ['new'], 1) + await fresh + assert.deepEqual(ids(), ['new']) +}) + +test('an empty batch stops automatic loading even if the total is stale', async () => { + const { state, respond, calls } = setup() + const first = state.reload() + respond(0, ['a']) + await first + const next = state.loadMore() + respond(1, [], 100) + await next + assert.equal(state.hasMore.value, false) + assert.equal(await state.loadMore(), false) + assert.equal(calls.length, 2) +}) diff --git a/frontend/src/views/knowledge/gallery/ImageGallery.vue b/frontend/src/views/knowledge/gallery/ImageGallery.vue index e5eeeaba..e2b4d317 100644 --- a/frontend/src/views/knowledge/gallery/ImageGallery.vue +++ b/frontend/src/views/knowledge/gallery/ImageGallery.vue @@ -32,8 +32,10 @@ const loading = ref(false) const error = ref('') const items = ref([]) const total = ref(0) -const page = ref(1) -const pageSize = ref(24) +const page = ref(0) +const pageSize = 24 +const exhausted = ref(false) +const hasMore = computed(() => !exhausted.value && page.value * pageSize < total.value) const keyword = ref('') const sortBy = ref('') @@ -42,6 +44,11 @@ const sortOrder = ref<'asc' | 'desc'>('desc') const filterPanelVisible = ref(false) const sortPanelVisible = ref(false) const scrollEl = ref(null) +const gridEl = ref(null) +const loadMoreEl = ref(null) +const imageRatios = ref>({}) +let cardObserver: ResizeObserver | undefined +let scrollObserver: ResizeObserver | undefined // Attribute selections for free-text ("keywords") attributes: namespaced attr // id -> literal values (OR within the attribute, AND across attributes). @@ -135,19 +142,46 @@ function resolveImageSrc(rawUrl: string): Promise { return pending } -async function resolveThumbnails(token: number) { - const imgs = items.value - const urls = await Promise.all(imgs.map((img) => resolveImageSrc(img.url))) - // A newer listing owns the grid now; its own pass maps the thumbnails. - if (token !== listToken) return - const next: Record = {} - imgs.forEach((img, i) => { - next[img.id] = urls[i] +async function resolveThumbnails(imgs: ImageAsset[], token: number) { + await Promise.all(imgs.map(async (img) => { + const url = await resolveImageSrc(img.url) + if (token !== listToken) return + thumbUrls.value[img.id] = url + })) + if (token === listToken) releaseBlobs(new Set(items.value.map((img) => img.url))) +} + +function onThumbLoad(id: string, event: Event) { + const image = event.target as HTMLImageElement + if (image.naturalWidth && image.naturalHeight) { + imageRatios.value[id] = image.naturalWidth / image.naturalHeight + } +} + +// Keep DOM order (and keyboard/viewer order) while cards span only the rows +// their natural image height needs. Existing cards stay put when appending. +function sizeCards(cards: HTMLElement[]) { + const spans = cards.map((card) => Math.ceil((card.getBoundingClientRect().height + 12) / 13)) + cards.forEach((card, index) => { + card.style.gridRowEnd = `span ${spans[index]}` }) - // Revoke blob URLs that are no longer on screen to avoid leaks. - releaseBlobs(new Set(imgs.map((img) => img.url))) - thumbUrls.value = next - thumbBroken.value = {} +} + +function observeCards() { + cardObserver?.disconnect() + const cards = Array.from(gridEl.value?.querySelectorAll('.ig-card') ?? []) + sizeCards(cards) + cards.forEach((card) => cardObserver?.observe(card)) +} + +function checkLoadMore() { + if (loading.value || error.value || viewerOpen.value || !hasMore.value) return + const scroll = scrollEl.value + const sentinel = loadMoreEl.value + if (scroll && sentinel && scroll.clientHeight > 0 && + sentinel.getBoundingClientRect().top <= scroll.getBoundingClientRect().bottom + 300) { + void loadMore() + } } function onThumbError(id: string) { @@ -288,7 +322,7 @@ function setVerdict(attrId: string, value: string, verdict: Verdict): void { if (verdict === 'default') delete perValue[value] else perValue[value] = verdict attrVerdicts.value = { ...attrVerdicts.value, [attrId]: perValue } - resetPageAndReload() + reload() } function verdictLabel(v: Verdict): string { @@ -303,7 +337,7 @@ function onKeywordsInput(attrId: string, raw: string) { .map((s) => s.trim()) .filter(Boolean) attrSelections.value = { ...attrSelections.value, [attrId]: values } - resetPageAndReload() + reload() } function keywordsInputValue(attrId: string): string { @@ -318,7 +352,7 @@ function clearFilters(): void { searchMode.value = 'all' persistSearchPrefs() } - resetPageAndReload() + reload() } /** The empty state's way back: forget the keyword as well. */ @@ -354,7 +388,7 @@ function onSearchFieldToggle(attrId: string, checked: boolean) { searchStatus.value = next searchMode.value = on.size === searchAttrs.value.length ? 'all' : 'custom' persistSearchPrefs() - if (keyword.value.trim()) resetPageAndReload() + if (keyword.value.trim()) reload() } function isLastSearchField(attrId: string): boolean { @@ -373,13 +407,13 @@ const sortFieldLabel = computed(() => { function selectSortField(id: string): void { if (sortBy.value === id) return sortBy.value = id - resetPageAndReload() + reload() } function selectSortOrder(order: 'asc' | 'desc'): void { if (sortOrder.value === order) return sortOrder.value = order - resetPageAndReload() + reload() } // --------------------------------------------------------------------------- @@ -395,69 +429,76 @@ function buildParams(): ImageListParams { sortOrder: sortOrder.value, attrFilters: Object.keys(selections).length ? selections : undefined, attrRules: Object.keys(rules).length ? rules : undefined, - page: page.value, - pageSize: pageSize.value, + pageSize, } } -// Bumped by every listing, so a slower earlier response (a debounced search -// overtaken by a page change) cannot overwrite the grid of a newer query. +// A query owns all of its appended pages; stale responses cannot replace it. let listToken = 0 +let queryParams: ImageListParams = {} -/** - * Fetch the current page. `focus` is where the viewer lands on the new page - * when it walked past a page edge; it is applied together with the new items - * so the viewer never renders a stale index against them. - */ -async function reload(focus?: 'first' | 'last') { - if (!props.knowledgeBaseId) return - const token = ++listToken +async function fetchNextPage(): Promise { + if (!props.knowledgeBaseId) return false + const token = listToken + const nextPage = page.value + 1 loading.value = true error.value = '' try { - const res = await listGalleryImages(props.knowledgeBaseId, buildParams()) - if (token !== listToken) return - items.value = res.items + const res = await listGalleryImages(props.knowledgeBaseId, { ...queryParams, page: nextPage }) + if (token !== listToken) return false + const existing = new Set(items.value.map((img) => img.id)) + const incoming = res.items.filter((img) => !existing.has(img.id)) + items.value.push(...incoming) + page.value = nextPage total.value = res.total - if (focus && res.items.length) viewerIndex.value = focus === 'first' ? 0 : res.items.length - 1 - else if (viewerOpen.value && viewerIndex.value >= res.items.length) closeViewer() - void resolveThumbnails(token) + exhausted.value = res.items.length === 0 + void resolveThumbnails(incoming, token) + await nextTick() + observeCards() + return true } catch (e) { - if (token !== listToken) return - error.value = e instanceof Error ? e.message : String(e) - items.value = [] - total.value = 0 - thumbUrls.value = {} - closeViewer() + if (token === listToken) error.value = e instanceof Error ? e.message : String(e) + return false } finally { - if (token === listToken) loading.value = false + if (token === listToken) { + loading.value = false + void nextTick(checkLoadMore) + } } } -function resetPageAndReload() { - page.value = 1 - scrollGridToTop() - reload() +function loadMore(): Promise { + if (loading.value || !hasMore.value) return Promise.resolve(false) + return fetchNextPage() } -function scrollGridToTop() { +function resetResults() { + listToken++ + viewerOpen.value = false + items.value = [] + total.value = 0 + page.value = 0 + exhausted.value = false + thumbUrls.value = {} + thumbBroken.value = {} + imageRatios.value = {} scrollEl.value?.scrollTo({ top: 0 }) } +function reload() { + resetResults() + queryParams = buildParams() + return fetchNextPage() +} + let searchTimer: ReturnType | undefined function onSearchInput() { if (searchTimer) clearTimeout(searchTimer) - searchTimer = setTimeout(() => resetPageAndReload(), 350) + searchTimer = setTimeout(() => reload(), 350) } function onSearchNow() { if (searchTimer) clearTimeout(searchTimer) - resetPageAndReload() -} - -function onPageChange(next: number) { - page.value = next - scrollGridToTop() reload() } @@ -475,7 +516,7 @@ function openViewer(index: number) { function closeViewer() { if (!viewerOpen.value) return viewerOpen.value = false - // The viewer may have walked onto another image, or another page; bring + // The viewer may have walked onto another image; bring // the card it stopped on into view so the grid picks up where it left off. const index = viewerIndex.value void nextTick(() => { @@ -485,12 +526,13 @@ function closeViewer() { }) } -/** The viewer walked past the edge of this page: load the neighbour. */ -async function onViewerStep(delta: 1 | -1) { - const target = page.value + delta - if (target < 1 || (target - 1) * pageSize.value >= total.value) return - page.value = target - await reload(delta > 0 ? 'first' : 'last') +/** At the loaded edge, append the next batch and keep the viewer continuous. */ +async function onViewerLoadMore() { + const token = listToken + const nextIndex = items.value.length + if (await loadMore() && token === listToken && viewerOpen.value && items.value.length > nextIndex) { + viewerIndex.value = nextIndex + } } function onOpenSource(knowledgeId: string) { @@ -520,6 +562,9 @@ onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) // Orphan any in-flight listing so it cannot map new blobs after unmount. listToken++ + initToken++ + cardObserver?.disconnect() + scrollObserver?.disconnect() releaseBlobs() }) @@ -534,16 +579,13 @@ let initToken = 0 // everything scoped to the previous knowledge base is dropped first. async function initGallery() { const token = ++initToken - viewerOpen.value = false - items.value = [] - total.value = 0 - page.value = 1 + resetResults() + if (searchTimer) clearTimeout(searchTimer) + error.value = '' keyword.value = '' sortBy.value = '' attrSelections.value = {} attrVerdicts.value = {} - thumbUrls.value = {} - thumbBroken.value = {} releaseBlobs() configLoaded.value = false config.value = { attribute_sources: [], attributes: [], mode: 'all', status: {} } @@ -566,7 +608,19 @@ async function initGallery() { await reload() } -onMounted(initGallery) +onMounted(() => { + cardObserver = new ResizeObserver((entries) => { + sizeCards(entries.map((entry) => entry.target as HTMLElement)) + void nextTick(checkLoadMore) + }) + scrollObserver = new ResizeObserver(checkLoadMore) + if (scrollEl.value) scrollObserver.observe(scrollEl.value) + void initGallery() +}) + +watch(viewerOpen, (open) => { + if (!open) void nextTick(checkLoadMore) +}) watch( () => props.knowledgeBaseId, @@ -759,9 +813,12 @@ watch( -
- -
{{ error }}
+
+ + {{ t(`${NS}.clearFilters`) }} -
+
-
- - @@ -1176,9 +1230,10 @@ watch( } .ig-loading { - min-height: 100%; display: flex; flex-direction: column; + + .is-empty & { min-height: 100%; } } .ig-error { @@ -1189,7 +1244,9 @@ watch( .ig-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(180px, 100%), 1fr)); + grid-auto-rows: 1px; gap: 12px; + align-items: start; align-content: start; } @@ -1225,7 +1282,7 @@ watch( &__thumb { position: relative; - aspect-ratio: 4 / 3; + width: 100%; display: flex; align-items: center; justify-content: center; @@ -1235,7 +1292,7 @@ watch( img { width: 100%; height: 100%; - object-fit: cover; + object-fit: contain; transition: transform var(--app-motion-slow) ease; } } @@ -1300,12 +1357,15 @@ watch( } } -.ig-footer { +.ig-load-more { display: flex; - justify-content: flex-end; - flex-shrink: 0; - padding: 12px 0 16px; - border-top: 1px solid var(--td-component-stroke); + align-items: center; + justify-content: center; + gap: 8px; + min-height: 56px; + padding: 16px 0; + color: var(--td-text-color-placeholder); + font-size: var(--app-text-sm); } @container image-gallery (max-width: 780px) {