mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
fix(journey): select all takes every photo in the range and imports keep their order
The photo picker's Select all took only the pages already loaded, 50 at a time, and replaced whatever had been picked on another tab. It now loads the rest of a day, trip or date-range search before selecting (cancelled by closing the picker or switching tab), adds to earlier picks, and Deselect all only clears what is in view. Add stays disabled until that loading is done. The whole-library tab keeps selecting what is loaded and shows the count as "N+". A date-filtered Immich search stopped at 1,000 photos without a word, because its page budget was absolute; it is now relative to the page asked for, with an absolute ceiling of 270 raw pages sized so the picker's deepest page still gets a full answer. Adds go out in batches of 500 ids, under the JSON body limit, and each batch is sent oldest first, so photos land in an entry in the order they were taken. When a later batch fails, the photos already saved are counted and the journey reloads while the error still shows, through one hook for desktop and phone. After a provider add, the capture-time lookup runs at most four at a time per user, shared by all of that user's batches. When it fills a row, a journey:photos:updated event reloads open journeys once per batch, from the REST routes and the MCP add tool alike. Device uploads, which arrive one file per request, get the same lookup without the event. Addresses discussion #1587.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// FE-APISURF-001 to FE-APISURF-058
|
||||
// FE-APISURF-001 to FE-APISURF-059
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import type { AxiosResponse } from 'axios'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
@@ -645,6 +645,41 @@ describe('client > request payloads', () => {
|
||||
.toEqual({ provider: 'immich', asset_ids: ['a1'], caption: 'cap', passphrase: 'secret', media_types: ['image', 'video'] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-059: a provider-photo add past the batch size goes out in batches and answers as one (#1587)', async () => {
|
||||
const bodies: Array<{ url: string; body: Record<string, unknown> }> = []
|
||||
server.use(http.post(/\/provider-photos$/, async ({ request }) => {
|
||||
const body = await request.json() as { asset_ids: string[] }
|
||||
bodies.push({ url: new URL(request.url).pathname, body })
|
||||
return HttpResponse.json({ photos: body.asset_ids.map(id => ({ asset_id: id })), added: body.asset_ids.length })
|
||||
}))
|
||||
const ids = Array.from({ length: 1001 }, (_, i) => `a${i}`)
|
||||
const types = ids.map((_, i) => (i % 3 === 0 ? 'video' : 'image'))
|
||||
|
||||
const entry = await journeyApi.addProviderPhotos(9, 'immich', ids, 'cap', 'pw', types)
|
||||
|
||||
// One request of 2,180 Immich ids already hit the 100 kB body limit.
|
||||
expect(bodies.map(b => (b.body.asset_ids as string[]).length)).toEqual([500, 500, 1])
|
||||
for (const { url, body } of bodies) {
|
||||
expect(url).toBe('/api/journeys/entries/9/provider-photos')
|
||||
expect(body).toMatchObject({ provider: 'immich', caption: 'cap', passphrase: 'pw' })
|
||||
// Each id keeps its own media type across the cut.
|
||||
const sent = body.asset_ids as string[]
|
||||
expect(body.media_types).toEqual(sent.map(id => types[Number(id.slice(1))]))
|
||||
}
|
||||
expect(bodies.flatMap(b => b.body.asset_ids as string[])).toEqual(ids)
|
||||
expect(entry.added).toBe(1001)
|
||||
expect(entry.photos).toHaveLength(1001)
|
||||
|
||||
bodies.length = 0
|
||||
const gallery = await journeyApi.addProviderPhotosToGallery(2, 'immich', ids.slice(0, 501))
|
||||
expect(bodies.map(b => b.url)).toEqual(['/api/journeys/2/gallery/provider-photos', '/api/journeys/2/gallery/provider-photos'])
|
||||
expect(bodies.map(b => b.body)).toEqual([
|
||||
{ provider: 'immich', asset_ids: ids.slice(0, 500) },
|
||||
{ provider: 'immich', asset_ids: ids.slice(500, 501) },
|
||||
])
|
||||
expect(gallery.added).toBe(501)
|
||||
})
|
||||
|
||||
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
|
||||
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
|
||||
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { z } from 'zod'
|
||||
import type { Day, Place, Trip } from '../types'
|
||||
import type { TransitProvider } from '@trek/shared'
|
||||
import { randomId } from '../utils/randomId'
|
||||
import { postProviderPhotosInBatches } from './providerPhotoBatches'
|
||||
import {
|
||||
weatherResultSchema, type WeatherResult,
|
||||
inAppListResultSchema, type InAppListResult,
|
||||
@@ -1018,9 +1019,13 @@ export const journeyApi = {
|
||||
/** A clip on one entry: the video plus the poster frame the browser grabbed (issue #2341). */
|
||||
uploadEntryVideo: (entryId: number, formData: FormData, opts?: UploadOptions) =>
|
||||
postMultipart(`/journeys/entries/${entryId}/video`, formData, opts),
|
||||
addProviderPhotosToGallery: (journeyId: number, provider: string, assetIds: string[], passphrase?: string, mediaTypes?: string[]) => apiClient.post(`/journeys/${journeyId}/gallery/provider-photos`, { provider, asset_ids: assetIds, ...(passphrase ? { passphrase } : {}), ...(mediaTypes ? { media_types: mediaTypes } : {}) } satisfies JourneyProviderPhotosRequest).then(r => r.data),
|
||||
// Both provider-photo adds go out in batches of PROVIDER_PHOTO_BATCH ids: one
|
||||
// request for a whole trip ran into the 100 kB body limit (#1587).
|
||||
addProviderPhotosToGallery: (journeyId: number, provider: string, assetIds: string[], passphrase?: string, mediaTypes?: string[]) =>
|
||||
postProviderPhotosInBatches(assetIds, mediaTypes, (ids, types) => apiClient.post(`/journeys/${journeyId}/gallery/provider-photos`, { provider, asset_ids: ids, ...(passphrase ? { passphrase } : {}), ...(types ? { media_types: types } : {}) } satisfies JourneyProviderPhotosRequest).then(r => r.data)),
|
||||
addProviderPhoto: (entryId: number, provider: string, assetId: string, caption?: string, passphrase?: string) => apiClient.post(`/journeys/entries/${entryId}/provider-photos`, { provider, asset_id: assetId, caption, ...(passphrase ? { passphrase } : {}) }).then(r => r.data),
|
||||
addProviderPhotos: (entryId: number, provider: string, assetIds: string[], caption?: string, passphrase?: string, mediaTypes?: string[]) => apiClient.post(`/journeys/entries/${entryId}/provider-photos`, { provider, asset_ids: assetIds, caption, ...(passphrase ? { passphrase } : {}), ...(mediaTypes ? { media_types: mediaTypes } : {}) }).then(r => r.data),
|
||||
addProviderPhotos: (entryId: number, provider: string, assetIds: string[], caption?: string, passphrase?: string, mediaTypes?: string[]) =>
|
||||
postProviderPhotosInBatches(assetIds, mediaTypes, (ids, types) => apiClient.post(`/journeys/entries/${entryId}/provider-photos`, { provider, asset_ids: ids, caption, ...(passphrase ? { passphrase } : {}), ...(types ? { media_types: types } : {}) }).then(r => r.data)),
|
||||
linkPhoto: (entryId: number, journeyPhotoId: number) => apiClient.post(`/journeys/entries/${entryId}/link-photo`, { journey_photo_id: journeyPhotoId }).then(r => r.data),
|
||||
unlinkPhoto: (entryId: number, journeyPhotoId: number) => apiClient.delete(`/journeys/entries/${entryId}/photos/${journeyPhotoId}`).then(r => r.data),
|
||||
deleteGalleryPhoto: (journeyId: number, journeyPhotoId: number) => apiClient.delete(`/journeys/${journeyId}/gallery/${journeyPhotoId}`).then(r => r.data),
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { PROVIDER_PHOTO_BATCH, ProviderPhotoBatchError, postProviderPhotosInBatches } from './providerPhotoBatches'
|
||||
|
||||
describe('postProviderPhotosInBatches (#1587)', () => {
|
||||
it('FE-PPBATCH-001: cuts ids and media types at the same positions and sums the answers', async () => {
|
||||
const post = vi.fn(async (ids: string[]) => ({ photos: ids.map(id => ({ id })), added: ids.length - 1 }))
|
||||
const ids = ['a', 'b', 'c', 'd', 'e']
|
||||
const types = ['image', 'video', 'image', 'video', 'image']
|
||||
|
||||
const result = await postProviderPhotosInBatches(ids, types, post, 2)
|
||||
|
||||
expect(post.mock.calls).toEqual([
|
||||
[['a', 'b'], ['image', 'video']],
|
||||
[['c', 'd'], ['image', 'video']],
|
||||
[['e'], ['image']],
|
||||
])
|
||||
expect(result).toEqual({ photos: ids.map(id => ({ id })), added: 2 })
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-002: leaves media types out of every batch when none were given', async () => {
|
||||
const post = vi.fn(async () => ({ added: 1 }))
|
||||
|
||||
await postProviderPhotosInBatches(['a', 'b', 'c'], undefined, post, 2)
|
||||
|
||||
expect(post.mock.calls).toEqual([[['a', 'b'], undefined], [['c'], undefined]])
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-003: an empty selection still makes the one request it always made', async () => {
|
||||
const post = vi.fn(async () => undefined)
|
||||
|
||||
expect(await postProviderPhotosInBatches([], undefined, post)).toEqual({ photos: [], added: 0 })
|
||||
expect(post).toHaveBeenCalledTimes(1)
|
||||
expect(post).toHaveBeenCalledWith([], undefined)
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-004: a failing batch stops the run and rejects, the batches after it are never sent', async () => {
|
||||
const post = vi.fn()
|
||||
.mockResolvedValueOnce({ photos: [], added: 2 })
|
||||
.mockRejectedValueOnce(new Error('413'))
|
||||
const ids = Array.from({ length: 5 }, (_, i) => `id${i}`)
|
||||
|
||||
await expect(postProviderPhotosInBatches(ids, undefined, post, 2)).rejects.toThrow('413')
|
||||
expect(post).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-006: a later batch that fails still reports what the earlier batches saved', async () => {
|
||||
const cause = new Error('502')
|
||||
const post = vi.fn()
|
||||
.mockResolvedValueOnce({ photos: [{ id: 1 }, { id: 2 }], added: 2 })
|
||||
.mockResolvedValueOnce({ photos: [{ id: 3 }], added: 1 })
|
||||
.mockRejectedValueOnce(cause)
|
||||
const ids = Array.from({ length: 7 }, (_, i) => `id${i}`)
|
||||
|
||||
const err = await postProviderPhotosInBatches(ids, undefined, post, 2).catch((e: unknown) => e)
|
||||
|
||||
expect(err).toBeInstanceOf(ProviderPhotoBatchError)
|
||||
expect(err).toMatchObject({ added: 3, photos: [{ id: 1 }, { id: 2 }, { id: 3 }], message: '502', cause })
|
||||
expect(post).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-007: a first batch that fails rejects with the request error itself, nothing having been saved', async () => {
|
||||
const cause = { response: { status: 413 } }
|
||||
const post = vi.fn().mockRejectedValueOnce(cause)
|
||||
|
||||
await expect(postProviderPhotosInBatches(['a', 'b', 'c'], undefined, post, 2)).rejects.toBe(cause)
|
||||
expect(post).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-008: a cause that is not an Error still gets a message', () => {
|
||||
const err = new ProviderPhotoBatchError({ photos: [], added: 0 }, 'gone')
|
||||
|
||||
expect(err.message).toBe('Adding the photos failed part way')
|
||||
expect(err.name).toBe('ProviderPhotoBatchError')
|
||||
expect(err.cause).toBe('gone')
|
||||
})
|
||||
|
||||
it('FE-PPBATCH-005: batches of 500 by default, far under the 100 kB body limit', async () => {
|
||||
const post = vi.fn(async (ids: string[], _types?: string[]) => ({ added: ids.length }))
|
||||
const ids = Array.from({ length: 1200 }, (_, i) => `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`)
|
||||
|
||||
const result = await postProviderPhotosInBatches(ids, ids.map(() => 'image'), post)
|
||||
|
||||
expect(PROVIDER_PHOTO_BATCH).toBe(500)
|
||||
expect(post.mock.calls.map(([batch]) => batch.length)).toEqual([500, 500, 200])
|
||||
expect(result.added).toBe(1200)
|
||||
const largest = JSON.stringify({ provider: 'immich', asset_ids: post.mock.calls[0][0], media_types: post.mock.calls[0][1] })
|
||||
expect(largest.length).toBeLessThan(100 * 1024)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Most provider asset ids one add request carries (#1587).
|
||||
*
|
||||
* The server parses JSON bodies up to 100 kB, and an Immich id with its media
|
||||
* type costs about 47 bytes, so a single request stopped at roughly 2,180
|
||||
* photos with a 413 the moment "Select all" could reach a whole trip. 500 keeps
|
||||
* every request far under that for either provider.
|
||||
*/
|
||||
export const PROVIDER_PHOTO_BATCH = 500
|
||||
|
||||
/** What the two provider-photo add routes answer, summed over every batch. */
|
||||
export interface ProviderPhotosAdded {
|
||||
photos: unknown[]
|
||||
added: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A batched add that failed after earlier batches were stored.
|
||||
*
|
||||
* Those batches are on the journey whatever happens next, so the error carries
|
||||
* what they added: a caller can count them and reload, and still report the
|
||||
* failure for the rest. `cause` is what the failing batch rejected with.
|
||||
*/
|
||||
export class ProviderPhotoBatchError extends Error implements ProviderPhotosAdded {
|
||||
readonly photos: unknown[]
|
||||
readonly added: number
|
||||
readonly cause: unknown
|
||||
|
||||
constructor(saved: ProviderPhotosAdded, cause: unknown) {
|
||||
super(cause instanceof Error ? cause.message : 'Adding the photos failed part way')
|
||||
this.name = 'ProviderPhotoBatchError'
|
||||
this.photos = saved.photos
|
||||
this.added = saved.added
|
||||
this.cause = cause
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How many photos a failed add stored all the same: the count a
|
||||
* ProviderPhotoBatchError carries, 0 for any other failure.
|
||||
*/
|
||||
export function addedBeforeFailure(err: unknown): number {
|
||||
return err instanceof ProviderPhotoBatchError ? err.added : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a provider-photo add in batches the body limit lets through, and answer
|
||||
* as one request would have.
|
||||
*
|
||||
* `mediaTypes` is parallel to `assetIds` and is cut at the same positions, so
|
||||
* every id keeps its own type. The batches go one after the other: the server
|
||||
* numbers photos in the order it receives them, and the picker sends them in
|
||||
* capture order, which concurrent requests could interleave. A failing batch
|
||||
* stops the run. When it is the first, the request's own error comes through
|
||||
* unchanged; after that it is a ProviderPhotoBatchError carrying what the
|
||||
* earlier batches stored. Adding those again is harmless because the server
|
||||
* skips what is already there.
|
||||
*
|
||||
* An empty list still makes the one request it always made.
|
||||
*/
|
||||
export async function postProviderPhotosInBatches(
|
||||
assetIds: string[],
|
||||
mediaTypes: string[] | undefined,
|
||||
post: (assetIds: string[], mediaTypes: string[] | undefined) => Promise<Partial<ProviderPhotosAdded> | undefined>,
|
||||
batchSize: number = PROVIDER_PHOTO_BATCH,
|
||||
): Promise<ProviderPhotosAdded> {
|
||||
const photos: unknown[] = []
|
||||
let added = 0
|
||||
let start = 0
|
||||
do {
|
||||
const end = start + batchSize
|
||||
let result: Partial<ProviderPhotosAdded> | undefined
|
||||
try {
|
||||
result = await post(assetIds.slice(start, end), mediaTypes?.slice(start, end))
|
||||
} catch (err) {
|
||||
if (start === 0) throw err
|
||||
throw new ProviderPhotoBatchError({ photos, added }, err)
|
||||
}
|
||||
photos.push(...(result?.photos ?? []))
|
||||
added += result?.added ?? 0
|
||||
start = end
|
||||
} while (start < assetIds.length)
|
||||
return { photos, added }
|
||||
}
|
||||
@@ -73,6 +73,9 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
'journey:entry:deleted',
|
||||
'journey:entries:reordered',
|
||||
'journey:contributor:changed',
|
||||
// Capture times landed after a photo import (#1587); the same listener reloads
|
||||
// the journey so the gallery re-sorts.
|
||||
'journey:photos:updated',
|
||||
// Studio book — components/Studio/useBookStore (its own listener: a client
|
||||
// with nothing outstanding takes the new version, one with unsaved edits
|
||||
// deliberately does not and conflicts on its next save instead)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-GALLERY-001 to FE-JRN-GALLERY-019
|
||||
// FE-JRN-GALLERY-001 to FE-JRN-GALLERY-020
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { act, useRef, useState } from 'react'
|
||||
@@ -9,6 +9,9 @@ import { server } from '../../../tests/helpers/msw/server'
|
||||
import { useJourneyStore, type GalleryPhoto, type JourneyEntry, type JourneyTrip } from '../../store/journeyStore'
|
||||
import type { UploadProgress } from '../../utils/uploadQueue'
|
||||
import { GalleryView } from './JourneyDetailPageGalleryView'
|
||||
import { useProviderPhotoAdds } from '../../pages/journeyDetail/useProviderPhotoAdds'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { ProviderPhotoBatchError } from '../../api/providerPhotoBatches'
|
||||
|
||||
type ToastKind = 'success' | 'error' | 'warning' | 'info'
|
||||
|
||||
@@ -74,7 +77,8 @@ const entries: JourneyEntry[] = [
|
||||
]
|
||||
|
||||
/** Mirrors the page wiring: the gallery reports its connected providers up,
|
||||
and the host renders one button per provider next to Upload. */
|
||||
and the host renders one button per provider next to Upload. The picker's
|
||||
Add goes through the same hook the page takes from useJourneyDetail. */
|
||||
function GalleryHarness({ gallery, onPhotoClick, onRefresh, onRegisterUpload }: {
|
||||
gallery: GalleryPhoto[]
|
||||
onPhotoClick: (photos: GalleryPhoto[], index: number) => void
|
||||
@@ -83,6 +87,7 @@ function GalleryHarness({ gallery, onPhotoClick, onRefresh, onRegisterUpload }:
|
||||
}) {
|
||||
const [providers, setProviders] = useState<{ id: string; name: string }[]>([])
|
||||
const browseRef = useRef<((provider: string) => void) | null>(null)
|
||||
const { addPickedPhotos } = useProviderPhotoAdds(onRefresh)
|
||||
return (
|
||||
<>
|
||||
{providers.map(p => (
|
||||
@@ -96,6 +101,7 @@ function GalleryHarness({ gallery, onPhotoClick, onRefresh, onRegisterUpload }:
|
||||
trips={trips}
|
||||
onPhotoClick={onPhotoClick}
|
||||
onRefresh={onRefresh}
|
||||
onAddProviderPhotos={addPickedPhotos}
|
||||
onRegisterUpload={onRegisterUpload}
|
||||
onRegisterProviders={(p, browse) => { setProviders(p); browseRef.current = browse }}
|
||||
/>
|
||||
@@ -309,6 +315,26 @@ describe('GalleryView', () => {
|
||||
expect(onRefresh).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-JRN-GALLERY-020: an add that fails after earlier batches landed counts those, refreshes, and still reports the failure (#1587)', async () => {
|
||||
useConnectedImmich()
|
||||
const add = vi.spyOn(journeyApi, 'addProviderPhotosToGallery')
|
||||
.mockRejectedValueOnce(new ProviderPhotoBatchError({ photos: [], added: 500 }, new Error('502')))
|
||||
const user = userEvent.setup()
|
||||
const { onRefresh } = mountGallery([])
|
||||
|
||||
try {
|
||||
await user.click(await screen.findByRole('button', { name: 'Immich' }))
|
||||
await user.click(await screen.findByAltText(''))
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
|
||||
await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1))
|
||||
expect(toastSpy).toHaveBeenCalledWith('500 photos added', 'success', undefined)
|
||||
expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined)
|
||||
} finally {
|
||||
add.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-JRN-GALLERY-014: uploads picked files and refreshes on success', async () => {
|
||||
let registered: (() => void) | null = null
|
||||
const { container, onRefresh } = mountGallery([], fn => { registered = fn })
|
||||
|
||||
@@ -9,11 +9,11 @@ import { useToast } from '../shared/Toast'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { JourneyEntry, GalleryPhoto, JourneyTrip } from '../../store/journeyStore'
|
||||
import { photoUrl, posterlessVideo } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { ProviderPicker } from './JourneyDetailPageProviderPicker'
|
||||
import { ProviderPicker, type ProviderPhotoGroup } from './JourneyDetailPageProviderPicker'
|
||||
import { ScrollTrigger } from './JourneyDetailPageScrollTrigger'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhotoClick, onRefresh, onRegisterUpload, onRegisterProviders }: {
|
||||
export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhotoClick, onRefresh, onAddProviderPhotos, onRegisterUpload, onRegisterProviders }: {
|
||||
entries: JourneyEntry[]
|
||||
gallery: GalleryPhoto[]
|
||||
journeyId: number
|
||||
@@ -21,6 +21,8 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
trips: JourneyTrip[]
|
||||
onPhotoClick: (photos: GalleryPhoto[], index: number) => void
|
||||
onRefresh: () => void
|
||||
/** What the picker's Add does: the host's useProviderPhotoAdds, shared with the phone screen. */
|
||||
onAddProviderPhotos: (journeyId: number, provider: string, groups: ProviderPhotoGroup[], entryId: number | null) => Promise<void>
|
||||
onRegisterUpload?: (fn: () => void) => void
|
||||
onRegisterProviders?: (providers: { id: string; name: string }[], browse: (provider: string) => void) => void
|
||||
}) {
|
||||
@@ -208,27 +210,7 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
existingAssetIds={new Set(gallery.filter(p => p.asset_id).map(p => p.asset_id!))}
|
||||
onClose={() => setShowPicker(false)}
|
||||
onAdd={async (groups, entryId) => {
|
||||
let added = 0
|
||||
let anyFailed = false
|
||||
for (const group of groups) {
|
||||
try {
|
||||
if (entryId) {
|
||||
const result = await journeyApi.addProviderPhotos(entryId, pickerProvider!, group.assetIds, undefined, group.passphrase, group.mediaTypes)
|
||||
added += result.added || 0
|
||||
} else {
|
||||
const result = await journeyApi.addProviderPhotosToGallery(journeyId, pickerProvider!, group.assetIds, group.passphrase, group.mediaTypes)
|
||||
added += result.added || 0
|
||||
}
|
||||
} catch {
|
||||
anyFailed = true
|
||||
}
|
||||
}
|
||||
if (added > 0) {
|
||||
toast.success(t('journey.photosAdded', { count: added }))
|
||||
onRefresh()
|
||||
} else if (anyFailed) {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
await onAddProviderPhotos(journeyId, pickerProvider!, groups, entryId)
|
||||
setShowPicker(false)
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-PICKER-001 to FE-JRN-PICKER-023
|
||||
// FE-JRN-PICKER-001 to FE-JRN-PICKER-036
|
||||
|
||||
import { describe, it, expect, afterAll, beforeAll, beforeEach, vi } from 'vitest'
|
||||
import { http, HttpResponse, delay } from 'msw'
|
||||
@@ -6,6 +6,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import type { JourneyEntry, JourneyTrip } from '../../store/journeyStore'
|
||||
import { PROVIDER_SEARCH_LAST_PAGE } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { ProviderPicker } from './JourneyDetailPageProviderPicker'
|
||||
|
||||
const trips: JourneyTrip[] = [
|
||||
@@ -115,7 +116,7 @@ describe('ProviderPicker', () => {
|
||||
await waitFor(() => expect(ranges).toHaveLength(2))
|
||||
// utc_offset_minutes rides along on every search: the server cannot tell
|
||||
// which 24 hours a date-only bound means without it (#2336).
|
||||
expect(ranges[1]).toEqual({ from: '', to: '', page: 1, size: 50, utc_offset_minutes: 0 })
|
||||
expect(ranges[1]).toEqual({ from: '', to: '', page: 1, size: 200, utc_offset_minutes: 0 })
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-006: the album tab loads albums and reports when there are none', async () => {
|
||||
@@ -418,6 +419,339 @@ describe('ProviderPicker', () => {
|
||||
await waitFor(() => expect(order()).toEqual(['rome', 'helsinki']))
|
||||
})
|
||||
|
||||
describe('select all across pages (#1587)', () => {
|
||||
const SEARCH = '/api/integrations/memories/immich/search'
|
||||
/** The tile button of one asset, found by the thumbnail it shows. */
|
||||
const tile = (container: HTMLElement, id: string) =>
|
||||
container.querySelector(`img[src*="/assets/0/${id}/"]`)!.closest('button') as HTMLButtonElement
|
||||
|
||||
function pagedTrip(pages: Record<number, Record<string, unknown>[]>, bodies: Record<string, unknown>[] = []) {
|
||||
const last = Math.max(...Object.keys(pages).map(Number))
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
bodies.push(body)
|
||||
return HttpResponse.json({ assets: pages[body.page] ?? [], hasMore: body.page < last })
|
||||
}))
|
||||
return bodies
|
||||
}
|
||||
|
||||
it('FE-JRN-PICKER-024: on a trip, loads the pages still missing with the same search, then selects every photo', async () => {
|
||||
const bodies = pagedTrip({ 1: [asset('p1a'), asset('p1b')], 2: [asset('p2a')], 3: [asset('p3a')] })
|
||||
const user = userEvent.setup()
|
||||
mountPicker()
|
||||
|
||||
// Pages are still pending, so the count says it is a floor.
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(2\+\)/ }))
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Add (4)' })).toBeEnabled()
|
||||
expect(bodies.map((b) => b.page)).toEqual([1, 2, 3])
|
||||
expect(bodies[2]).toEqual({ from: '2026-03-14', to: '2026-03-20', page: 3, size: 200, utc_offset_minutes: 0 })
|
||||
// Everything is in now: the count is exact and the next press takes them back.
|
||||
expect(screen.getByRole('button', { name: /Deselect all \(4\)/ })).toBeInTheDocument()
|
||||
expect(await screen.findAllByAltText('')).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-025: the button is busy while the pages load', async () => {
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
if (body.page === 2) await gate
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
mountPicker()
|
||||
|
||||
const button = await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
await user.click(button)
|
||||
|
||||
await waitFor(() => expect(button).toHaveAttribute('aria-busy', 'true'))
|
||||
expect(button).toBeDisabled()
|
||||
release()
|
||||
await waitFor(() => expect(button).toHaveAttribute('aria-busy', 'false'))
|
||||
expect(button).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-026: on All Photos, selects what is loaded and never drains the library', async () => {
|
||||
const bodies: Record<string, unknown>[] = []
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { from: string }
|
||||
bodies.push(body)
|
||||
return body.from
|
||||
? HttpResponse.json({ assets: [asset('t1')], hasMore: false })
|
||||
: HttpResponse.json({ assets: [asset('lib1'), asset('lib2')], hasMore: true })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
mountPicker()
|
||||
await screen.findByRole('button', { name: /Select all \(1\)/ })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /All Photos/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(2\+\)/ }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: /Deselect all \(2\+\)/ })).toBeInTheDocument()
|
||||
// The trip search and the first library page, nothing after them.
|
||||
expect(bodies).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-027: adds to picks from another tab, and deselect all takes back only the photos in view', async () => {
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { from: string }
|
||||
return body.from
|
||||
? HttpResponse.json({ assets: [asset('t1'), asset('t2')], hasMore: false })
|
||||
: HttpResponse.json({ assets: [asset('lib1')], hasMore: false })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
const { container, onAdd } = mountPicker()
|
||||
await screen.findByRole('button', { name: /Select all \(2\)/ })
|
||||
|
||||
await user.click(tile(container, 't1'))
|
||||
await user.click(screen.getByRole('button', { name: /All Photos/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(1\)/ }))
|
||||
expect(screen.getByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Deselect all \(1\)/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['t1'], mediaTypes: ['image'], passphrase: undefined }], null)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-028: switching tab mid-run cancels it and selects nothing', async () => {
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
const pages: number[] = []
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
if (body.page === 2) await gate
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 3 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
mountPicker()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
await waitFor(() => expect(pages).toEqual([1, 2]))
|
||||
await user.click(screen.getByRole('button', { name: 'Date Range' }))
|
||||
release()
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
|
||||
expect(pages).toEqual([1, 2])
|
||||
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: /Select all \(1\+\)/ })).toHaveAttribute('aria-busy', 'false')
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-029: closing the picker mid-run stops it', async () => {
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
const pages: number[] = []
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
if (body.page === 2) await gate
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 3 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
const { unmount } = mountPicker()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
await waitFor(() => expect(pages).toEqual([1, 2]))
|
||||
unmount()
|
||||
release()
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
|
||||
expect(pages).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-030: a page that fails keeps what arrived selected, and pressing again carries on', async () => {
|
||||
let failPage2 = true
|
||||
const pages: number[] = []
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
if (body.page === 2 && failPage2) return new HttpResponse(null, { status: 502 })
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
mountPicker()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
expect(await screen.findByRole('button', { name: 'Add (1)' })).toBeEnabled()
|
||||
// Still pending, so still a floor, and still a select rather than a deselect.
|
||||
const again = await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
|
||||
failPage2 = false
|
||||
await user.click(again)
|
||||
expect(await screen.findByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
expect(pages).toEqual([1, 2, 2])
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-033: Add waits for a Select all that is still loading, so it never sends only the earlier picks', async () => {
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
if (body.page === 2) await gate
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
const { container, onAdd } = mountPicker()
|
||||
await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
|
||||
// A pick from before the run makes Add live on its own.
|
||||
await user.click(tile(container, 'p1'))
|
||||
const add = screen.getByRole('button', { name: 'Add (1)' })
|
||||
expect(add).toBeEnabled()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
await waitFor(() => expect(add).toBeDisabled())
|
||||
fireEvent.click(add)
|
||||
expect(onAdd).not.toHaveBeenCalled()
|
||||
|
||||
release()
|
||||
const full = await screen.findByRole('button', { name: 'Add (2)' })
|
||||
await waitFor(() => expect(full).toBeEnabled())
|
||||
await user.click(full)
|
||||
expect(onAdd).toHaveBeenCalledTimes(1)
|
||||
expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['p1', 'p2'], mediaTypes: ['image', 'image'], passphrase: undefined }], null)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-034: a Select all cancelled by a tab switch gives Add back, with only the earlier picks', async () => {
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
const pages: number[] = []
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
if (body.page === 2) await gate
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
const { container, onAdd } = mountPicker()
|
||||
await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
await user.click(tile(container, 'p1'))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
await waitFor(() => expect(pages).toEqual([1, 2]))
|
||||
expect(screen.getByRole('button', { name: 'Add (1)' })).toBeDisabled()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Date Range' }))
|
||||
const add = screen.getByRole('button', { name: 'Add (1)' })
|
||||
await waitFor(() => expect(add).toBeEnabled())
|
||||
release()
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
|
||||
// The page that arrived after the cancel selected nothing.
|
||||
expect(screen.getByRole('button', { name: 'Add (1)' })).toBeEnabled()
|
||||
await user.click(add)
|
||||
expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['p1'], mediaTypes: ['image'], passphrase: undefined }], null)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-035: offers Select all while every photo in view is already added but more pages are pending', async () => {
|
||||
// Say the trip's last day came in earlier from the Day tab: the newest page
|
||||
// is all greyed out, and the older days are still to load.
|
||||
const bodies = pagedTrip({ 1: [asset('old1'), asset('old2')], 2: [asset('new1')] })
|
||||
const user = userEvent.setup()
|
||||
const { onAdd } = mountPicker({ existingAssetIds: new Set(['old1', 'old2']) })
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(0\+\)/ }))
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Add (1)' })).toBeEnabled()
|
||||
expect(bodies.map((b) => b.page)).toEqual([1, 2])
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['new1'], mediaTypes: ['image'], passphrase: undefined }], null)
|
||||
})
|
||||
|
||||
/** A trip that never runs out: every page says there is more, only the first and the last hold a photo. */
|
||||
function endlessTrip(pages: number[]) {
|
||||
server.use(http.post(SEARCH, async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
const photos = body.page === 1 || body.page === PROVIDER_SEARCH_LAST_PAGE ? [asset(`p${body.page}`)] : []
|
||||
return HttpResponse.json({ assets: photos, hasMore: true })
|
||||
}))
|
||||
}
|
||||
|
||||
it('FE-JRN-PICKER-036: Select all stops at the last page and keeps the "+", and nothing past it is asked for, by a second press or by scrolling', async () => {
|
||||
const pages: number[] = []
|
||||
endlessTrip(pages)
|
||||
const user = userEvent.setup()
|
||||
const { container } = mountPicker()
|
||||
/** The scroll trigger at the foot of the grid, the spinner that loads the next page. */
|
||||
const scrollTrigger = () => container.querySelector('.mt-2.py-4 .animate-spin')
|
||||
const selectAll = await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
expect(scrollTrigger()).toBeInTheDocument()
|
||||
|
||||
await user.click(selectAll)
|
||||
|
||||
// The server's scan ceiling is sized for this page, so it is still
|
||||
// answered, and nothing past it is asked for.
|
||||
expect(await screen.findByRole('button', { name: 'Add (2)' }, { timeout: 10000 })).toBeEnabled()
|
||||
expect(pages).toHaveLength(PROVIDER_SEARCH_LAST_PAGE)
|
||||
expect(Math.max(...pages)).toBe(PROVIDER_SEARCH_LAST_PAGE)
|
||||
expect(scrollTrigger()).not.toBeInTheDocument()
|
||||
// Everything loaded is picked and there is more: a deselect, with the "+",
|
||||
// and selecting again takes what is loaded without asking any further.
|
||||
await user.click(screen.getByRole('button', { name: /Deselect all \(2\+\)/ }))
|
||||
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name: /Select all \(2\+\)/ }))
|
||||
expect(screen.getByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
expect(pages).toHaveLength(PROVIDER_SEARCH_LAST_PAGE)
|
||||
}, 20000)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-031: sends each group oldest first, by wall clock where the provider has one (#1587)', async () => {
|
||||
searchReturns([
|
||||
asset('late', { takenAt: '2026-03-15T12:00:00.000Z' }),
|
||||
asset('early', { takenAt: '2026-03-15T08:00:00.000Z', mediaType: 'video' }),
|
||||
// Later as an instant, earliest on the photographer's own clock.
|
||||
asset('wallclock', { takenAt: '2026-03-15T20:00:00.000Z', localTakenAt: '2026-03-15T06:00:00.000Z' }),
|
||||
asset('undated', { takenAt: null }),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
const { onAdd } = mountPicker()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(4\)/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Add (4)' }))
|
||||
|
||||
expect(onAdd).toHaveBeenCalledWith(
|
||||
[{
|
||||
assetIds: ['wallclock', 'early', 'late', 'undated'],
|
||||
mediaTypes: ['image', 'video', 'image', 'image'],
|
||||
passphrase: undefined,
|
||||
}],
|
||||
null,
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-032: a search after an album pages again and carries no album passphrase', async () => {
|
||||
const pages: number[] = []
|
||||
server.use(
|
||||
http.get('/api/integrations/memories/immich/albums', () => HttpResponse.json({
|
||||
albums: [{ id: 'alb1', albumName: 'Rome', assetCount: 1, passphrase: 'pw' }],
|
||||
})),
|
||||
http.get('/api/integrations/memories/immich/albums/alb1/photos', () => HttpResponse.json({ assets: [asset('alb-a1')] })),
|
||||
http.post('/api/integrations/memories/immich/search', async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const { onAdd } = mountPicker()
|
||||
await screen.findByRole('button', { name: /Select all \(1\+\)/ })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Albums' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Rome (1)' }))
|
||||
await screen.findByRole('button', { name: /Select all \(1\)/ })
|
||||
await user.click(screen.getByRole('button', { name: 'Trip Period' }))
|
||||
|
||||
// The trip is paged again: without the reset the album left behind hid the "+".
|
||||
await user.click(await screen.findByRole('button', { name: /Select all \(1\+\)/ }))
|
||||
expect(await screen.findByRole('button', { name: 'Add (2)' })).toBeEnabled()
|
||||
await user.click(screen.getByRole('button', { name: 'Add (2)' }))
|
||||
expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['p1', 'p2'], mediaTypes: ['image', 'image'], passphrase: undefined }], null)
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-020: closes through the header button and the backdrop', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { container, onClose } = mountPicker()
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { Calendar, Camera, Check, ChevronRight, Play, X } from 'lucide-react';
|
||||
import { Calendar, Camera, Check, ChevronRight, Loader2, Play, X } from 'lucide-react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { memoriesApi } from '../../api/client';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
fetchRemainingProviderPages,
|
||||
groupPhotosByDate,
|
||||
PROVIDER_SEARCH_LAST_PAGE,
|
||||
PROVIDER_SEARCH_PAGE_SIZE,
|
||||
sortByCaptureTimeAsc,
|
||||
sortProviderPhotos,
|
||||
utcOffsetMinutesForDay,
|
||||
type GeoPoint,
|
||||
type ProviderPhotoAsset,
|
||||
} from '../../pages/journeyDetail/JourneyDetailPage.helpers';
|
||||
import type { JourneyEntry, JourneyTrip } from '../../store/journeyStore';
|
||||
import { DatePicker } from './JourneyDetailPageDatePicker';
|
||||
@@ -14,6 +19,22 @@ import { ScrollTrigger } from './JourneyDetailPageScrollTrigger';
|
||||
|
||||
export type ProviderPhotoGroup = { assetIds: string[]; passphrase?: string; mediaTypes?: string[] };
|
||||
|
||||
/** A tile as the search and album routes answer it; only what a pick needs is spelled out. */
|
||||
type PickerAsset = ProviderPhotoAsset & { mediaType?: string };
|
||||
|
||||
/**
|
||||
* One picked asset. The capture times ride along only to order the ids at
|
||||
* submit (#1587): a pick survives tab and album switches, and by then the asset
|
||||
* may no longer be in the loaded list to look them up in.
|
||||
*/
|
||||
type SelectedAsset = {
|
||||
albumId?: string;
|
||||
passphrase?: string;
|
||||
mediaType?: string;
|
||||
takenAt?: string | null;
|
||||
localTakenAt?: string | null;
|
||||
};
|
||||
|
||||
export function ProviderPicker({
|
||||
provider,
|
||||
userId,
|
||||
@@ -53,9 +74,9 @@ export function ProviderPicker({
|
||||
const [searchPage, setSearchPage] = useState(1);
|
||||
const [searchFrom, setSearchFrom] = useState('');
|
||||
const [searchTo, setSearchTo] = useState('');
|
||||
const [selected, setSelected] = useState<Map<string, { albumId?: string; passphrase?: string; mediaType?: string }>>(
|
||||
new Map()
|
||||
);
|
||||
const [selected, setSelected] = useState<Map<string, SelectedAsset>>(new Map());
|
||||
// "Select all" is loading the pages that were still missing (#1587).
|
||||
const [draining, setDraining] = useState(false);
|
||||
const [customFrom, setCustomFrom] = useState('');
|
||||
const [customTo, setCustomTo] = useState('');
|
||||
const [targetEntryId, setTargetEntryId] = useState<number | null>(initialEntryId ?? null);
|
||||
@@ -83,11 +104,37 @@ export function ProviderPicker({
|
||||
return abortRef.current.signal;
|
||||
};
|
||||
|
||||
// Closing the picker cancels whatever it is still loading, a "Select all" that
|
||||
// is working through the remaining pages included.
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
// The body of one page of a search. Shared by the page a search opens with,
|
||||
// the pages scrolled into view and the ones "Select all" loads, so every page
|
||||
// asks for the same days in the same zone (#1587).
|
||||
//
|
||||
// The bounds are calendar days as this browser reads them, so the zone they
|
||||
// are meant in travels with them. Without it the server can only take them
|
||||
// as UTC days and a reader outside UTC gets somebody else's 24 hours
|
||||
// (#2336). A single offset leaves a one-hour sliver at the far end of a
|
||||
// multi-day range that crosses a DST change, and none at all for a single
|
||||
// day, which is the case this fixes.
|
||||
const searchRequest = (from: string, to: string, page: number) => ({
|
||||
from,
|
||||
to,
|
||||
page,
|
||||
size: PROVIDER_SEARCH_PAGE_SIZE,
|
||||
utc_offset_minutes: utcOffsetMinutesForDay(from || to),
|
||||
});
|
||||
|
||||
const searchPhotos = async (from: string, to: string, page: number = 1, append: boolean = false) => {
|
||||
const signal = cancelPending();
|
||||
if (page === 1) {
|
||||
setLoading(true);
|
||||
setPhotos([]);
|
||||
// A search shows no album, so none may colour its picks, its thumbnails or
|
||||
// its paging. Left set, a trip search after an album never paged again.
|
||||
setSelectedAlbum(null);
|
||||
setSelectedAlbumPassphrase(undefined);
|
||||
} else {
|
||||
setLoadingMore(true);
|
||||
}
|
||||
@@ -95,17 +142,7 @@ export function ProviderPicker({
|
||||
setSearchTo(to);
|
||||
setSearchPage(page);
|
||||
try {
|
||||
// The bounds are calendar days as this browser reads them, so the zone they
|
||||
// are meant in travels with them. Without it the server can only take them
|
||||
// as UTC days and a reader outside UTC gets somebody else's 24 hours
|
||||
// (#2336). A single offset leaves a one-hour sliver at the far end of a
|
||||
// multi-day range that crosses a DST change, and none at all for a single
|
||||
// day, which is the case this fixes.
|
||||
const data = await memoriesApi.search(
|
||||
provider,
|
||||
{ from, to, page, size: 50, utc_offset_minutes: utcOffsetMinutesForDay(from || to) },
|
||||
signal,
|
||||
);
|
||||
const data = await memoriesApi.search(provider, searchRequest(from, to, page), signal);
|
||||
const assets = data.assets || [];
|
||||
setPhotos((prev) => (append ? [...prev, ...assets] : assets));
|
||||
setHasMore(!!data.hasMore);
|
||||
@@ -120,11 +157,6 @@ export function ProviderPicker({
|
||||
}
|
||||
};
|
||||
|
||||
const loadMorePhotos = () => {
|
||||
if (loadingMore || !hasMore) return;
|
||||
searchPhotos(searchFrom, searchTo, searchPage + 1, true);
|
||||
};
|
||||
|
||||
const loadAlbumPhotos = async (album: { id: string; passphrase?: string }) => {
|
||||
const signal = cancelPending();
|
||||
setLoading(true);
|
||||
@@ -175,6 +207,29 @@ export function ProviderPicker({
|
||||
|
||||
// Albums come back whole, so they never page.
|
||||
const morePagesPending = hasMore && !selectedAlbum;
|
||||
const dateBounded = Boolean(searchFrom || searchTo);
|
||||
// A date-bounded search ends at PROVIDER_SEARCH_LAST_PAGE, scrolled or loaded
|
||||
// by "Select all" (#1587). Past it the server's scan ceiling could only answer
|
||||
// an empty page with no more to come, so the picker stops asking and keeps
|
||||
// what the server last said: the count keeps its "+".
|
||||
const canLoadMore = morePagesPending && !(dateBounded && searchPage >= PROVIDER_SEARCH_LAST_PAGE);
|
||||
// A date-bounded search is a trip or a day, so "Select all" loads the rest of
|
||||
// it first (#1587). The All Photos tab is the whole library: there it stays
|
||||
// "everything loaded so far", and the count says there is more.
|
||||
const selectAllLoadsRest = canLoadMore && dateBounded;
|
||||
|
||||
const loadMorePhotos = () => {
|
||||
if (loadingMore || !canLoadMore) return;
|
||||
searchPhotos(searchFrom, searchTo, searchPage + 1, true);
|
||||
};
|
||||
|
||||
const selectionEntry = (asset: PickerAsset | undefined): SelectedAsset => ({
|
||||
albumId: selectedAlbum ?? undefined,
|
||||
passphrase: selectedAlbumPassphrase,
|
||||
mediaType: asset?.mediaType,
|
||||
takenAt: asset?.takenAt ?? null,
|
||||
localTakenAt: asset?.localTakenAt ?? null,
|
||||
});
|
||||
|
||||
const toggleAsset = (id: string) => {
|
||||
setSelected((prev) => {
|
||||
@@ -182,13 +237,78 @@ export function ProviderPicker({
|
||||
if (next.has(id)) {
|
||||
next.delete(id);
|
||||
} else {
|
||||
const mediaType = (photos as any[]).find((p) => p.id === id)?.mediaType;
|
||||
next.set(id, { albumId: selectedAlbum ?? undefined, passphrase: selectedAlbumPassphrase, mediaType });
|
||||
next.set(id, selectionEntry(photos.find((p) => p.id === id)));
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// Adds to what is picked rather than replacing it: picks made on another tab
|
||||
// or in an album survive a "Select all" here.
|
||||
const addToSelection = (assets: PickerAsset[]) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const asset of assets) {
|
||||
if (existingAssetIds.has(asset.id) || next.has(asset.id)) continue;
|
||||
next.set(asset.id, selectionEntry(asset));
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const removeFromSelection = (assets: PickerAsset[]) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const asset of assets) next.delete(asset.id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const selectAll = async (inView: PickerAsset[]) => {
|
||||
const controller = abortRef.current;
|
||||
if (!selectAllLoadsRest || !controller) {
|
||||
addToSelection(inView);
|
||||
return;
|
||||
}
|
||||
// The search's own controller: a new search, a tab switch or closing the
|
||||
// picker aborts it, and with it this run.
|
||||
const signal = controller.signal;
|
||||
const loaded: PickerAsset[] = [];
|
||||
setDraining(true);
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
await fetchRemainingProviderPages<PickerAsset>(
|
||||
(page) => memoriesApi.search(provider, searchRequest(searchFrom, searchTo, page), signal),
|
||||
searchPage + 1,
|
||||
signal,
|
||||
(assets, page, more) => {
|
||||
loaded.push(...assets);
|
||||
setPhotos((prev) => [...prev, ...assets]);
|
||||
setSearchPage(page);
|
||||
setHasMore(more);
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
// A page that failed leaves the rest pending: what did arrive is still
|
||||
// selected below, the count keeps its "+", and pressing again carries on
|
||||
// from the page that failed.
|
||||
} finally {
|
||||
setDraining(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
if (!signal.aborted) addToSelection([...inView, ...loaded]);
|
||||
};
|
||||
|
||||
// Leaving a tab ends a "Select all" that is still loading its pages.
|
||||
const switchTab = (id: typeof filter) => {
|
||||
if (draining && id !== filter) cancelPending();
|
||||
setFilter(id);
|
||||
};
|
||||
|
||||
// While Select all is still loading pages, the selection holds only the picks
|
||||
// from before it: an Add then would send those and drop the rest (#1587).
|
||||
const addDisabled = selected.size === 0 || adding || draining;
|
||||
|
||||
const targetLabel = targetEntryId
|
||||
? entries.find((e) => e.id === targetEntryId)?.title ||
|
||||
entries.find((e) => e.id === targetEntryId)?.entry_date ||
|
||||
@@ -251,7 +371,7 @@ export function ProviderPicker({
|
||||
<button
|
||||
type="button"
|
||||
key={f.id}
|
||||
onClick={() => setFilter(f.id)}
|
||||
onClick={() => switchTab(f.id)}
|
||||
className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${
|
||||
filter === f.id
|
||||
? 'bg-zinc-900 text-white dark:bg-white dark:text-zinc-900'
|
||||
@@ -441,42 +561,42 @@ export function ProviderPicker({
|
||||
sortedPhotos.length > 0 &&
|
||||
(() => {
|
||||
const selectable = sortedPhotos.filter((a: any) => !existingAssetIds.has(a.id));
|
||||
const allSelected = selectable.length > 0 && selectable.every((a: any) => selected.has(a.id));
|
||||
if (selectable.length === 0) return null;
|
||||
// Pages still to load on a trip or a day mean not everything is picked yet.
|
||||
const allSelected =
|
||||
selectable.length > 0 && !selectAllLoadsRest && selectable.every((a) => selected.has(a.id));
|
||||
// Every photo in view may already be in the journey while the rest of
|
||||
// the trip is not: the button is what loads that rest, so it stays.
|
||||
if (selectable.length === 0 && !selectAllLoadsRest) return null;
|
||||
return (
|
||||
<div className="flex-shrink-0 border-b border-zinc-200 bg-white px-4 py-2 dark:border-zinc-700 dark:bg-zinc-900">
|
||||
<button
|
||||
type="button"
|
||||
disabled={loadingMore}
|
||||
aria-busy={draining}
|
||||
onClick={() => {
|
||||
if (allSelected) {
|
||||
setSelected(new Map());
|
||||
removeFromSelection(selectable);
|
||||
} else {
|
||||
setSelected(
|
||||
new Map(
|
||||
selectable.map((a: any) => [
|
||||
a.id,
|
||||
{
|
||||
albumId: selectedAlbum ?? undefined,
|
||||
passphrase: selectedAlbumPassphrase,
|
||||
mediaType: a.mediaType,
|
||||
},
|
||||
])
|
||||
)
|
||||
);
|
||||
void selectAll(selectable);
|
||||
}
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-2.5 py-1 text-[11px] font-medium text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-2.5 py-1 text-[11px] font-medium text-zinc-500 hover:bg-zinc-50 disabled:cursor-wait disabled:opacity-60 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<div
|
||||
className={`flex h-3.5 w-3.5 items-center justify-center rounded border ${
|
||||
allSelected
|
||||
? 'border-zinc-900 bg-zinc-900 dark:border-white dark:bg-white'
|
||||
: 'border-zinc-300 dark:border-zinc-600'
|
||||
}`}
|
||||
>
|
||||
{allSelected && <Check size={9} className="text-white dark:text-zinc-900" strokeWidth={3} />}
|
||||
</div>
|
||||
{allSelected ? t('journey.picker.deselectAll') : t('journey.picker.selectAll')} ({selectable.length})
|
||||
{draining ? (
|
||||
<Loader2 size={14} className="animate-spin text-content-muted" aria-hidden="true" />
|
||||
) : (
|
||||
<div
|
||||
className={`flex h-3.5 w-3.5 items-center justify-center rounded border ${
|
||||
allSelected
|
||||
? 'border-zinc-900 bg-zinc-900 dark:border-white dark:bg-white'
|
||||
: 'border-zinc-300 dark:border-zinc-600'
|
||||
}`}
|
||||
>
|
||||
{allSelected && <Check size={9} className="text-white dark:text-zinc-900" strokeWidth={3} />}
|
||||
</div>
|
||||
)}
|
||||
{allSelected ? t('journey.picker.deselectAll') : t('journey.picker.selectAll')} ({selectable.length}
|
||||
{morePagesPending ? '+' : ''})
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
@@ -572,7 +692,7 @@ export function ProviderPicker({
|
||||
belong to a neighbouring day leaves the grid empty, and a sentinel
|
||||
that only exists next to photos would never ask for the next page
|
||||
(#2336). */}
|
||||
{morePagesPending && <ScrollTrigger onVisible={loadMorePhotos} loading={loadingMore} />}
|
||||
{canLoadMore && <ScrollTrigger onVisible={loadMorePhotos} loading={loadingMore} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -596,24 +716,28 @@ export function ProviderPicker({
|
||||
if (adding) return;
|
||||
setAdding(true);
|
||||
try {
|
||||
const groupMap = new Map<string | undefined, { assetIds: string[]; mediaTypes: string[] }>();
|
||||
for (const [assetId, { passphrase, mediaType }] of selected.entries()) {
|
||||
const g = groupMap.get(passphrase) || { assetIds: [], mediaTypes: [] };
|
||||
g.assetIds.push(assetId);
|
||||
g.mediaTypes.push(mediaType === 'video' ? 'video' : 'image');
|
||||
groupMap.set(passphrase, g);
|
||||
const groupMap = new Map<string | undefined, Array<SelectedAsset & { assetId: string }>>();
|
||||
for (const [assetId, pick] of selected.entries()) {
|
||||
const g = groupMap.get(pick.passphrase) || [];
|
||||
g.push({ ...pick, assetId });
|
||||
groupMap.set(pick.passphrase, g);
|
||||
}
|
||||
const groups = [...groupMap.entries()].map(([passphrase, g]) => ({
|
||||
assetIds: g.assetIds,
|
||||
mediaTypes: g.mediaTypes,
|
||||
passphrase,
|
||||
}));
|
||||
// Oldest first, so an entry numbers its new photos in the order
|
||||
// they were taken rather than the grid's newest-first (#1587).
|
||||
const groups = [...groupMap.entries()].map(([passphrase, picks]) => {
|
||||
const ordered = sortByCaptureTimeAsc(picks);
|
||||
return {
|
||||
assetIds: ordered.map((p) => p.assetId),
|
||||
mediaTypes: ordered.map((p) => (p.mediaType === 'video' ? 'video' : 'image')),
|
||||
passphrase,
|
||||
};
|
||||
});
|
||||
await onAdd(groups, targetEntryId);
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
}}
|
||||
disabled={selected.size === 0 || adding}
|
||||
disabled={addDisabled}
|
||||
className="rounded-lg bg-zinc-900 px-3.5 py-2 text-[13px] font-medium text-white hover:bg-zinc-800 disabled:cursor-not-allowed disabled:opacity-40 dark:bg-white dark:text-zinc-900 dark:hover:bg-zinc-100"
|
||||
>
|
||||
{adding ? (
|
||||
|
||||
@@ -49,6 +49,7 @@ export default function MJourneyDetail() {
|
||||
sidebarMapItems, tracks,
|
||||
dismissSuggestion, restoreSuggestions, openAtEntryId,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos,
|
||||
addPickedProviderPhotos, addEntryProviderPhotos,
|
||||
} = useJourneyDetail()
|
||||
|
||||
// The dock's FAB is a sibling of this screen: on the Gallery it becomes the
|
||||
@@ -629,9 +630,7 @@ export default function MJourneyDetail() {
|
||||
return entryId
|
||||
}}
|
||||
onUploadPhotos={uploadPhotos}
|
||||
onAddProviderPhotos={async (entryId, group) => {
|
||||
await journeyApi.addProviderPhotos(entryId, group.provider, group.assetIds, undefined, group.passphrase, group.mediaTypes)
|
||||
}}
|
||||
onAddProviderPhotos={addEntryProviderPhotos}
|
||||
onDelete={editingEntry.id > 0 && canEditEntries
|
||||
? () => { const target = editingEntry; setEditingEntry(null); setDeleteTarget(target) }
|
||||
: undefined}
|
||||
@@ -674,24 +673,7 @@ export default function MJourneyDetail() {
|
||||
existingAssetIds={new Set(gallery.filter(p => p.asset_id).map(p => p.asset_id!))}
|
||||
onClose={() => setPickerProvider(null)}
|
||||
onAdd={async (groups, entryId) => {
|
||||
let added = 0
|
||||
let anyFailed = false
|
||||
for (const group of groups) {
|
||||
try {
|
||||
const result = entryId
|
||||
? await journeyApi.addProviderPhotos(entryId, pickerProvider, group.assetIds, undefined, group.passphrase, group.mediaTypes)
|
||||
: await journeyApi.addProviderPhotosToGallery(current.id, pickerProvider, group.assetIds, group.passphrase, group.mediaTypes)
|
||||
added += result.added || 0
|
||||
} catch {
|
||||
anyFailed = true
|
||||
}
|
||||
}
|
||||
if (added > 0) {
|
||||
toast.success(t('journey.photosAdded', { count: added }))
|
||||
loadJourney(Number(id))
|
||||
} else if (anyFailed) {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
await addPickedProviderPhotos(current.id, pickerProvider, groups, entryId)
|
||||
setPickerProvider(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -59,6 +59,7 @@ function JourneyDetailPageDesktop() {
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks,
|
||||
feedEdge, scrollFeedTo,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
addPickedProviderPhotos, addEntryProviderPhotos,
|
||||
} = useJourneyDetail()
|
||||
|
||||
if (loading || !current) {
|
||||
@@ -602,6 +603,7 @@ function JourneyDetailPageDesktop() {
|
||||
trips={current.trips}
|
||||
onPhotoClick={(photos, idx) => setLightbox({ photos: photos.map(p => ({ id: p.id, src: photoUrl(p, 'original'), caption: p.caption ?? null, provider: p.provider, asset_id: p.asset_id, owner_id: p.owner_id, mediaType: p.media_type })), index: idx })}
|
||||
onRefresh={() => loadJourney(Number(id))}
|
||||
onAddProviderPhotos={addPickedProviderPhotos}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -702,9 +704,7 @@ function JourneyDetailPageDesktop() {
|
||||
showVerdict={current.show_verdict !== 0}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
onAddProviderPhotos={async (entryId, group) => {
|
||||
await journeyApi.addProviderPhotos(entryId, group.provider, group.assetIds, undefined, group.passphrase, group.mediaTypes)
|
||||
}}
|
||||
onAddProviderPhotos={addEntryProviderPhotos}
|
||||
onDone={() => {
|
||||
setEditingEntry(null)
|
||||
loadJourney(Number(id))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-DETWIRE-001 to FE-JRN-DETWIRE-028
|
||||
// FE-JRN-DETWIRE-001 to FE-JRN-DETWIRE-041
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../tests/helpers/render';
|
||||
import { journeyApi } from '../api/client';
|
||||
@@ -112,6 +112,7 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
|
||||
loadJourney: vi.fn(), updateEntry: vi.fn(async () => {}), deleteEntry: vi.fn(async () => {}),
|
||||
reorderEntries: vi.fn(async () => {}), uploadPhotos: vi.fn(async () => ({ succeeded: [], failed: [] })),
|
||||
deletePhoto: vi.fn(async () => {}),
|
||||
addPickedProviderPhotos: vi.fn(async () => {}), addEntryProviderPhotos: vi.fn(async () => {}),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -300,6 +301,8 @@ describe('JourneyDetailPage wiring', () => {
|
||||
|
||||
(mocks.captured.gallery.onRefresh as () => void)();
|
||||
expect(hook.loadJourney).toHaveBeenCalledWith(7);
|
||||
// The picker's Add is the hook's, the one the phone screen uses too (#1587).
|
||||
expect(mocks.captured.gallery.onAddProviderPhotos).toBe(hook.addPickedProviderPhotos);
|
||||
});
|
||||
|
||||
it('FE-JRN-DETWIRE-016: the entry editor creates a new entry and updates an existing one', async () => {
|
||||
@@ -311,11 +314,9 @@ describe('JourneyDetailPage wiring', () => {
|
||||
await (mocks.captured.editor.onUploadPhotos as (id: number, f: File[]) => Promise<unknown>)(88, []);
|
||||
expect(hook.uploadPhotos).toHaveBeenCalledWith(88, [], undefined);
|
||||
|
||||
const addProvider = vi.spyOn(journeyApi, 'addProviderPhotos').mockResolvedValue({ added: 1 });
|
||||
await (mocks.captured.editor.onAddProviderPhotos as (id: number, g: Record<string, unknown>) => Promise<void>)(
|
||||
88, { provider: 'immich', assetIds: ['a1'], passphrase: 'pw', mediaTypes: ['image'] },
|
||||
);
|
||||
expect(addProvider).toHaveBeenCalledWith(88, 'immich', ['a1'], undefined, 'pw', ['image']);
|
||||
// Shared with the phone entry sheet, so a group that fails part way is
|
||||
// handled once for both shells (#1587).
|
||||
expect(mocks.captured.editor.onAddProviderPhotos).toBe(hook.addEntryProviderPhotos);
|
||||
|
||||
(mocks.captured.editor.onDone as () => void)();
|
||||
expect(hook.setEditingEntry).toHaveBeenCalledWith(null);
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
|
||||
import {
|
||||
createDraftJourneyEntry,
|
||||
distanceBetweenGeoPoints,
|
||||
fetchRemainingProviderPages,
|
||||
groupPhotosByDate,
|
||||
matchJourneyEntries,
|
||||
posterlessVideo,
|
||||
PROVIDER_SEARCH_LAST_PAGE,
|
||||
PROVIDER_SEARCH_PAGE_SIZE,
|
||||
sortByCaptureTimeAsc,
|
||||
sortProviderPhotos,
|
||||
utcOffsetMinutesForDay,
|
||||
} from './JourneyDetailPage.helpers';
|
||||
@@ -225,3 +230,133 @@ describe('posterlessVideo (#2341)', () => {
|
||||
expect(posterlessVideo({ media_type: 'video', provider: 'immich', thumbnail_path: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchRemainingProviderPages (#1587)', () => {
|
||||
it('asks for every page from the one given until the provider says there are no more', async () => {
|
||||
const fetchPage = vi.fn(async (page: number) => ({ assets: [`p${page}`], hasMore: page < 4 }));
|
||||
const onPage = vi.fn();
|
||||
|
||||
const result = await fetchRemainingProviderPages(fetchPage, 2, new AbortController().signal, onPage);
|
||||
|
||||
expect(fetchPage.mock.calls.map(([page]) => page)).toEqual([2, 3, 4]);
|
||||
expect(onPage.mock.calls).toEqual([
|
||||
[['p2'], 2, true],
|
||||
[['p3'], 3, true],
|
||||
[['p4'], 4, false],
|
||||
]);
|
||||
expect(result).toEqual({ assets: ['p2', 'p3', 'p4'], hasMore: false });
|
||||
});
|
||||
|
||||
it('keeps going over a page the filter emptied, and treats a missing list as empty', async () => {
|
||||
const fetchPage = vi.fn(async (page: number) => (page === 1 ? { hasMore: true } : { assets: ['x'], hasMore: false }));
|
||||
|
||||
const result = await fetchRemainingProviderPages(fetchPage, 1, new AbortController().signal, () => {});
|
||||
|
||||
expect(result).toEqual({ assets: ['x'], hasMore: false });
|
||||
});
|
||||
|
||||
it('stops at the last page and says there is still more', async () => {
|
||||
const fetchPage = vi.fn(async (page: number) => ({ assets: [page], hasMore: true }));
|
||||
|
||||
const result = await fetchRemainingProviderPages(fetchPage, 5, new AbortController().signal, () => {}, 7);
|
||||
|
||||
expect(fetchPage).toHaveBeenCalledTimes(3);
|
||||
expect(result).toEqual({ assets: [5, 6, 7], hasMore: true });
|
||||
});
|
||||
|
||||
it('never asks past page 251 by default, wherever the run starts', async () => {
|
||||
const endless = () => vi.fn(async (page: number) => ({ assets: [page], hasMore: true }));
|
||||
|
||||
// A run from the first page takes the 250 after it, and ends at photo 50,200.
|
||||
const fromStart = endless();
|
||||
await fetchRemainingProviderPages(fromStart, 2, new AbortController().signal, () => {});
|
||||
expect(fromStart).toHaveBeenCalledTimes(PROVIDER_SELECT_ALL_MAX_PAGES);
|
||||
expect(fromStart).toHaveBeenLastCalledWith(PROVIDER_SEARCH_LAST_PAGE);
|
||||
expect(PROVIDER_SEARCH_LAST_PAGE).toBe(251);
|
||||
expect(PROVIDER_SEARCH_LAST_PAGE * PROVIDER_SEARCH_PAGE_SIZE).toBe(50200);
|
||||
|
||||
// Pages scrolled into view first do not push it deeper.
|
||||
const scrolled = endless();
|
||||
await fetchRemainingProviderPages(scrolled, 12, new AbortController().signal, () => {});
|
||||
expect(scrolled).toHaveBeenLastCalledWith(PROVIDER_SEARCH_LAST_PAGE);
|
||||
|
||||
// A second press after the first stopped there asks for nothing, and the
|
||||
// search stays open: the count keeps its "+".
|
||||
const again = endless();
|
||||
const onPage = vi.fn();
|
||||
const result = await fetchRemainingProviderPages(again, PROVIDER_SEARCH_LAST_PAGE + 1, new AbortController().signal, onPage);
|
||||
expect(again).not.toHaveBeenCalled();
|
||||
expect(onPage).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({ assets: [], hasMore: true });
|
||||
});
|
||||
|
||||
it('stops quietly once aborted, before and between pages, and hands nothing on after the abort', async () => {
|
||||
const controller = new AbortController();
|
||||
const onPage = vi.fn();
|
||||
const fetchPage = vi.fn(async (page: number) => {
|
||||
if (page === 2) controller.abort();
|
||||
return { assets: [page], hasMore: true };
|
||||
});
|
||||
|
||||
const result = await fetchRemainingProviderPages(fetchPage, 1, controller.signal, onPage);
|
||||
|
||||
expect(fetchPage).toHaveBeenCalledTimes(2);
|
||||
expect(onPage).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ assets: [1], hasMore: true });
|
||||
|
||||
const never = vi.fn();
|
||||
await fetchRemainingProviderPages(never, 1, controller.signal, onPage);
|
||||
expect(never).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lets a failing page reject, so the caller can keep what arrived', async () => {
|
||||
const fetchPage = vi.fn(async (page: number) => {
|
||||
if (page === 2) throw new Error('502');
|
||||
return { assets: [page], hasMore: true };
|
||||
});
|
||||
const onPage = vi.fn();
|
||||
|
||||
await expect(fetchRemainingProviderPages(fetchPage, 1, new AbortController().signal, onPage)).rejects.toThrow('502');
|
||||
expect(onPage).toHaveBeenCalledWith([1], 1, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sortByCaptureTimeAsc (#1587)', () => {
|
||||
it('puts the oldest first, by the photographer\'s wall clock where there is one', () => {
|
||||
const items = [
|
||||
{ id: 'late', takenAt: '2026-03-15T12:00:00.000Z' },
|
||||
{ id: 'early', takenAt: '2026-03-15T08:00:00.000Z' },
|
||||
{ id: 'wallclock', takenAt: '2026-03-15T20:00:00.000Z', localTakenAt: '2026-03-15T06:00:00.000Z' },
|
||||
];
|
||||
|
||||
expect(sortByCaptureTimeAsc(items).map((i) => i.id)).toEqual(['wallclock', 'early', 'late']);
|
||||
});
|
||||
|
||||
it('breaks a wall-clock tie on the instant, then on the order the items came in', () => {
|
||||
const items = [
|
||||
{ id: 'b', localTakenAt: '2026-03-15T10:00:00.000Z', takenAt: '2026-03-15T09:00:00.000Z' },
|
||||
{ id: 'a', localTakenAt: '2026-03-15T10:00:00.000Z', takenAt: '2026-03-15T08:00:00.000Z' },
|
||||
{ id: 'c', takenAt: '2026-03-15T11:00:00.000Z' },
|
||||
{ id: 'd', takenAt: '2026-03-15T11:00:00.000Z' },
|
||||
];
|
||||
|
||||
expect(sortByCaptureTimeAsc(items).map((i) => i.id)).toEqual(['a', 'b', 'c', 'd']);
|
||||
});
|
||||
|
||||
it('keeps photos without a readable time at the end, in the order they came in', () => {
|
||||
const items = [
|
||||
{ id: 'none' },
|
||||
{ id: 'garbage', takenAt: 'not a date' },
|
||||
{ id: 'dated', takenAt: '2026-03-15T08:00:00.000Z' },
|
||||
{ id: 'blank', takenAt: '', localTakenAt: null },
|
||||
];
|
||||
|
||||
expect(sortByCaptureTimeAsc(items).map((i) => i.id)).toEqual(['dated', 'none', 'garbage', 'blank']);
|
||||
});
|
||||
|
||||
it('leaves the input alone', () => {
|
||||
const items = [{ id: 'b', takenAt: '2026-03-16T00:00:00Z' }, { id: 'a', takenAt: '2026-03-15T00:00:00Z' }];
|
||||
sortByCaptureTimeAsc(items);
|
||||
expect(items.map((i) => i.id)).toEqual(['b', 'a']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
|
||||
import { GeoOnceError } from '../../hooks/useGeolocation';
|
||||
import type { JourneyEntry } from '../../store/journeyStore';
|
||||
import { localIsoDate } from '../../utils/localDate';
|
||||
@@ -253,6 +254,110 @@ export function sortProviderPhotos<T extends ProviderPhotoAsset>(photos: T[], lo
|
||||
.map((item) => item.photo);
|
||||
}
|
||||
|
||||
/**
|
||||
* How many photos the picker asks a provider for per page (#1587).
|
||||
*
|
||||
* The search routes accept up to 200. Every date-filtered Immich page restarts
|
||||
* its scan at the first raw page on the server, so a smaller page makes loading
|
||||
* a whole trip cost quadratically more round trips; 200 is a quarter of what 50
|
||||
* cost, and still a grid the browser lays out without a stall.
|
||||
*/
|
||||
export const PROVIDER_SEARCH_PAGE_SIZE = 200;
|
||||
|
||||
/**
|
||||
* The deepest page the picker asks a date-bounded search for (#1587): its first
|
||||
* page and the PROVIDER_SELECT_ALL_MAX_PAGES after it, photos 50,001 to 50,200.
|
||||
*
|
||||
* Absolute, however the page would be reached: by "Select all", by pressing it
|
||||
* again after it stopped here, or by scrolling. Every such page restarts the
|
||||
* server's Immich scan at its first raw page, and the server stops that scan at
|
||||
* a ceiling sized for exactly this page. One past it could come back empty with
|
||||
* `hasMore: false`, and the picker would drop the "+" and call a cut-off search
|
||||
* complete. Stopping here keeps the "+".
|
||||
*/
|
||||
export const PROVIDER_SEARCH_LAST_PAGE = PROVIDER_SELECT_ALL_MAX_PAGES + 1;
|
||||
|
||||
export interface ProviderPhotoPage<T> {
|
||||
assets?: T[];
|
||||
hasMore?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the pages of a provider search that are still missing, one after the
|
||||
* other, until the provider says there are no more (#1587).
|
||||
*
|
||||
* "Select all" used to mean the pages already scrolled into view, so a trip of
|
||||
* a thousand photos selected fifty. Sequential on purpose: whether there is a
|
||||
* next page is only known once this one has answered. `onPage` hands each page
|
||||
* over as it lands so the grid can grow while the button is busy.
|
||||
*
|
||||
* Stops quietly once `signal` is aborted, which is how closing the picker or
|
||||
* switching its tab cancels the run: the caller then discards what came back.
|
||||
*
|
||||
* `lastPage` is the deepest page asked for, whichever page the run starts at, so
|
||||
* a provider that keeps answering `hasMore` cannot hold the button busy for
|
||||
* ever. Running into it leaves `hasMore` true, so the count keeps its "+", and a
|
||||
* run that starts past it asks for nothing.
|
||||
*/
|
||||
export async function fetchRemainingProviderPages<T>(
|
||||
fetchPage: (page: number) => Promise<ProviderPhotoPage<T>>,
|
||||
firstPage: number,
|
||||
signal: AbortSignal,
|
||||
onPage: (assets: T[], page: number, hasMore: boolean) => void,
|
||||
lastPage: number = PROVIDER_SEARCH_LAST_PAGE,
|
||||
): Promise<{ assets: T[]; hasMore: boolean }> {
|
||||
const assets: T[] = [];
|
||||
let hasMore = true;
|
||||
for (let page = firstPage; hasMore && page <= lastPage; page++) {
|
||||
if (signal.aborted) break;
|
||||
const data = await fetchPage(page);
|
||||
if (signal.aborted) break;
|
||||
const pageAssets = data.assets ?? [];
|
||||
hasMore = !!data.hasMore;
|
||||
assets.push(...pageAssets);
|
||||
onPage(pageAssets, page, hasMore);
|
||||
}
|
||||
return { assets, hasMore };
|
||||
}
|
||||
|
||||
/** A capture time as milliseconds, or null when it is missing or unreadable. */
|
||||
function captureMillis(value?: string | null): number | null {
|
||||
if (!value) return null;
|
||||
const ms = Date.parse(value);
|
||||
return Number.isNaN(ms) ? null : ms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Items in the order their photos were taken, oldest first (#1587).
|
||||
*
|
||||
* An entry keeps its photos in the order they were added, and the picker used
|
||||
* to add them in grid order, newest first, so a bulk import landed backwards.
|
||||
* The key is the photographer's wall clock (`localTakenAt`) where the provider
|
||||
* has it, the capture instant otherwise. Ties and photos without either keep
|
||||
* the order they came in, the undated ones after the rest.
|
||||
*
|
||||
* Only the order of the ids sent changes. The capture time itself is still
|
||||
* fetched by the server (#1614), never taken from here.
|
||||
*/
|
||||
export function sortByCaptureTimeAsc<T extends { takenAt?: string | null; localTakenAt?: string | null }>(
|
||||
items: T[],
|
||||
): T[] {
|
||||
return items
|
||||
.map((item, index) => ({
|
||||
item,
|
||||
index,
|
||||
key: captureMillis(item.localTakenAt) ?? captureMillis(item.takenAt),
|
||||
instant: captureMillis(item.takenAt),
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
if (a.key === null && b.key === null) return a.index - b.index;
|
||||
if (a.key === null) return 1;
|
||||
if (b.key === null) return -1;
|
||||
return a.key - b.key || (a.instant ?? 0) - (b.instant ?? 0) || a.index - b.index;
|
||||
})
|
||||
.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries a search box's text still lets through.
|
||||
*
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-029
|
||||
// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-031
|
||||
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
|
||||
import { useLocation } from 'react-router';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
|
||||
import { act, render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
|
||||
import { addListener, removeListener } from '../../api/websocket';
|
||||
import { useJourneyStore } from '../../store/journeyStore';
|
||||
import type { JourneyDetail, JourneyEntry } from '../../store/journeyStore';
|
||||
@@ -188,6 +188,34 @@ describe('useJourneyDetail', () => {
|
||||
await waitFor(() => expect(latest.current?.title).toBe('Japan renamed'));
|
||||
});
|
||||
|
||||
it('FE-JRN-DETHOOK-030: capture times landing after an import reload the journey so the gallery re-sorts (#1587)', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
const handler = vi.mocked(addListener).mock.calls[0][0] as (e: Record<string, unknown>) => void;
|
||||
|
||||
serveJourney(buildDetail({ gallery: [{ id: 3, photo_id: 30, taken_at: '2026-05-01T09:00:00Z' }] as never }));
|
||||
handler({ type: 'journey:photos:updated', journeyId: 7 });
|
||||
await waitFor(() => expect(latest.current?.gallery).toHaveLength(1));
|
||||
});
|
||||
|
||||
it('FE-JRN-DETHOOK-031: provider photos added from the picker or the editor reload this journey once some landed (#1587)', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
const toGallery = vi.fn(async () => ({ photos: [], added: 2 }));
|
||||
const toEntry = vi.fn(async () => ({ photos: [], added: 1 }));
|
||||
useJourneyStore.setState({ addProviderPhotosToGallery: toGallery, addProviderPhotos: toEntry } as never);
|
||||
|
||||
serveJourney(buildDetail({ title: 'After the import' }));
|
||||
await act(() => latest.addPickedProviderPhotos(7, 'immich', [{ assetIds: ['a1', 'a2'] }], null));
|
||||
expect(toGallery).toHaveBeenCalledWith(7, 'immich', { assetIds: ['a1', 'a2'] });
|
||||
expect(addToast).toHaveBeenCalledWith('2 photos added', 'success', undefined);
|
||||
await waitFor(() => expect(latest.current?.title).toBe('After the import'));
|
||||
|
||||
const group = { provider: 'immich', assetIds: ['b1'] };
|
||||
await act(() => latest.addEntryProviderPhotos(1, group));
|
||||
expect(toEntry).toHaveBeenCalledWith(1, 'immich', group);
|
||||
});
|
||||
|
||||
it('FE-JRN-DETHOOK-009: events of another type or another journey are ignored', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
|
||||
@@ -17,6 +17,7 @@ import { openStaysByDate } from '../../components/Dawarich/dawarichSuggestionMod
|
||||
import type { DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared'
|
||||
|
||||
import { useDawarichJournalTrail } from '../../hooks/useDawarichJournalTrail'
|
||||
import { useProviderPhotoAdds } from './useProviderPhotoAdds'
|
||||
|
||||
/** Stable identity for "this journey draws no trip tracks" (#2194). */
|
||||
const NO_TRACKS: JourneyTrack[] = []
|
||||
@@ -290,6 +291,10 @@ export function useJourneyDetail() {
|
||||
}
|
||||
}, [updateEntry, loadJourney, current, toast, t])
|
||||
|
||||
// Provider photos from the gallery picker and from the entry editor, the same
|
||||
// way on desktop and phone (#1587).
|
||||
const providerPhotos = useProviderPhotoAdds(() => { void loadJourney(Number(id)) })
|
||||
|
||||
const restoreSuggestions = useCallback(async () => {
|
||||
if (!current) return
|
||||
try {
|
||||
@@ -541,5 +546,7 @@ export function useJourneyDetail() {
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks: mapTracks, dawarichTrail,
|
||||
feedEdge, scrollFeedTo,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
addPickedProviderPhotos: providerPhotos.addPickedPhotos,
|
||||
addEntryProviderPhotos: providerPhotos.addEntryPhotos,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// FE-JRN-PPADD-001 to FE-JRN-PPADD-007
|
||||
import type { ReactNode } from 'react'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest'
|
||||
import { renderHook } from '../../../tests/helpers/render'
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext'
|
||||
import { ProviderPhotoBatchError } from '../../api/providerPhotoBatches'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
import { useProviderPhotoAdds } from './useProviderPhotoAdds'
|
||||
|
||||
type AddToast = NonNullable<typeof window.__addToast>
|
||||
|
||||
const journeyStoreInitial = useJourneyStore.getState()
|
||||
let addToast: Mock<AddToast>
|
||||
let toEntry: Mock
|
||||
let toGallery: Mock
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
return <TranslationProvider>{children}</TranslationProvider>
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const reload = vi.fn()
|
||||
const { result } = renderHook(() => useProviderPhotoAdds(reload), { wrapper })
|
||||
return { reload, ...result.current }
|
||||
}
|
||||
|
||||
/** A large add that failed after `added` photos of its earlier batches were stored. */
|
||||
const partial = (added: number) => new ProviderPhotoBatchError({ photos: [], added }, new Error('502'))
|
||||
|
||||
const toasts = () => addToast.mock.calls.map(([message, type]) => [message, type])
|
||||
|
||||
beforeEach(() => {
|
||||
addToast = vi.fn<AddToast>(() => 0)
|
||||
window.__addToast = addToast
|
||||
toEntry = vi.fn(async () => ({ photos: [], added: 1 }))
|
||||
toGallery = vi.fn(async () => ({ photos: [], added: 1 }))
|
||||
useJourneyStore.setState({ addProviderPhotos: toEntry, addProviderPhotosToGallery: toGallery } as never)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete window.__addToast
|
||||
useJourneyStore.setState(journeyStoreInitial, true)
|
||||
})
|
||||
|
||||
describe('useProviderPhotoAdds', () => {
|
||||
it('FE-JRN-PPADD-001: the picker sends every group to the gallery in turn, then counts and reloads once', async () => {
|
||||
toGallery.mockResolvedValueOnce({ photos: [], added: 2 }).mockResolvedValueOnce({ photos: [], added: 3 })
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
const first = { assetIds: ['a1', 'a2'], mediaTypes: ['image', 'video'] }
|
||||
const second = { assetIds: ['b1', 'b2', 'b3'], passphrase: 'pw' }
|
||||
|
||||
await addPickedPhotos(9, 'immich', [first, second], null)
|
||||
|
||||
expect(toGallery.mock.calls).toEqual([[9, 'immich', first], [9, 'immich', second]])
|
||||
expect(toEntry).not.toHaveBeenCalled()
|
||||
expect(toasts()).toEqual([['5 photos added', 'success']])
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-002: with an entry picked the groups go to that entry', async () => {
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
const group = { assetIds: ['a1'] }
|
||||
|
||||
await addPickedPhotos(9, 'synologyphotos', [group], 4)
|
||||
|
||||
expect(toEntry).toHaveBeenCalledWith(4, 'synologyphotos', group)
|
||||
expect(toGallery).not.toHaveBeenCalled()
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-003: a group that fails outright is reported, and the ones that landed still count', async () => {
|
||||
toGallery.mockResolvedValueOnce({ photos: [], added: 2 }).mockRejectedValueOnce(new Error('offline'))
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
|
||||
await addPickedPhotos(9, 'immich', [{ assetIds: ['a1', 'a2'] }, { assetIds: ['b1'] }], null)
|
||||
|
||||
expect(toasts()).toEqual([['2 photos added', 'success'], ['Error', 'error']])
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-004: nothing added and a failure: only the error, no reload', async () => {
|
||||
toGallery.mockRejectedValueOnce(new Error('offline'))
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
|
||||
await addPickedPhotos(9, 'immich', [{ assetIds: ['a1'] }], null)
|
||||
|
||||
expect(toasts()).toEqual([['Error', 'error']])
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-005: a group that fails part way counts the batches it stored, reloads, and still reports the failure (#1587)', async () => {
|
||||
toGallery.mockRejectedValueOnce(partial(500))
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
|
||||
await addPickedPhotos(9, 'immich', [{ assetIds: Array.from({ length: 700 }, (_, i) => `a${i}`) }], null)
|
||||
|
||||
expect(toasts()).toEqual([['500 photos added', 'success'], ['Error', 'error']])
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-006: an add that stored nothing new, every photo already there, says nothing and reloads nothing', async () => {
|
||||
toGallery.mockResolvedValueOnce({ photos: [], added: 0 })
|
||||
const { addPickedPhotos, reload } = setup()
|
||||
|
||||
await addPickedPhotos(9, 'immich', [{ assetIds: ['a1'] }], null)
|
||||
|
||||
expect(addToast).not.toHaveBeenCalled()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-JRN-PPADD-007: an entry-editor group rethrows every failure, and shows what a partial one stored', async () => {
|
||||
const { addEntryPhotos, reload } = setup()
|
||||
const group = { provider: 'immich', assetIds: ['a1'], passphrase: 'pw', mediaTypes: ['image'] }
|
||||
|
||||
// Success is quiet: the editor reloads the journey once it is done.
|
||||
await addEntryPhotos(4, group)
|
||||
expect(toEntry).toHaveBeenCalledWith(4, 'immich', group)
|
||||
expect(addToast).not.toHaveBeenCalled()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
|
||||
// Part way: the editor keeps the group queued off the rejection, so it has
|
||||
// to come through, and what did land is shown now rather than on Save.
|
||||
const err = partial(500)
|
||||
toEntry.mockRejectedValueOnce(err)
|
||||
await expect(addEntryPhotos(4, group)).rejects.toBe(err)
|
||||
expect(toasts()).toEqual([['500 photos added', 'success']])
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Nothing stored: nothing to show, just the failure.
|
||||
addToast.mockClear()
|
||||
reload.mockClear()
|
||||
toEntry.mockRejectedValueOnce(new Error('offline'))
|
||||
await expect(addEntryPhotos(4, group)).rejects.toThrow('offline')
|
||||
expect(addToast).not.toHaveBeenCalled()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { addedBeforeFailure } from '../../api/providerPhotoBatches'
|
||||
import type { ProviderPhotoGroup } from '../../components/Journey/JourneyDetailPageProviderPicker'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
|
||||
/** A group the entry editor queued: the picker's group plus the provider it came from. */
|
||||
export type ProviderEntryGroup = ProviderPhotoGroup & { provider: string }
|
||||
|
||||
/**
|
||||
* Adding provider photos (Immich, Synology Photos) to a journey, for both shells:
|
||||
* the desktop gallery and entry editor, the phone screen and its entry sheet.
|
||||
*
|
||||
* A large add goes out in batches, so it can fail after some of them were stored
|
||||
* (#1587). Those photos are on the journey whatever happens next, so both flows
|
||||
* here count them and reload, and still report the failure for the rest. Before,
|
||||
* such an add read as a plain failure while its photos sat hidden until the next
|
||||
* reload.
|
||||
*
|
||||
* `reload` is how the host fetches the journey again.
|
||||
*/
|
||||
export function useProviderPhotoAdds(reload: () => void) {
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const showAdded = (count: number) => {
|
||||
if (count <= 0) return
|
||||
toast.success(t('journey.photosAdded', { count }))
|
||||
reload()
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker's Add: every group onto the entry picked in it, or onto the
|
||||
* gallery, then one count, one reload and at most one error.
|
||||
*/
|
||||
const addPickedPhotos = async (
|
||||
journeyId: number,
|
||||
provider: string,
|
||||
groups: ProviderPhotoGroup[],
|
||||
entryId: number | null,
|
||||
): Promise<void> => {
|
||||
const { addProviderPhotos, addProviderPhotosToGallery } = useJourneyStore.getState()
|
||||
let added = 0
|
||||
let anyFailed = false
|
||||
// One group after the other: the server numbers photos in the order they
|
||||
// arrive, and each group is already sorted oldest first.
|
||||
for (const group of groups) {
|
||||
try {
|
||||
const result = entryId
|
||||
? await addProviderPhotos(entryId, provider, group)
|
||||
: await addProviderPhotosToGallery(journeyId, provider, group)
|
||||
added += result.added
|
||||
} catch (err) {
|
||||
added += addedBeforeFailure(err)
|
||||
anyFailed = true
|
||||
}
|
||||
}
|
||||
showAdded(added)
|
||||
if (anyFailed) toast.error(t('common.error'))
|
||||
}
|
||||
|
||||
/**
|
||||
* One group the entry editor queued, sent at Save. Rethrows, so the editor
|
||||
* still reports the group and keeps it queued: sending it again skips what
|
||||
* did land.
|
||||
*/
|
||||
const addEntryPhotos = async (entryId: number, group: ProviderEntryGroup): Promise<void> => {
|
||||
try {
|
||||
await useJourneyStore.getState().addProviderPhotos(entryId, group.provider, group)
|
||||
} catch (err) {
|
||||
showAdded(addedBeforeFailure(err))
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
return { addPickedPhotos, addEntryPhotos }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-STORE-JOURNEY-001 to FE-STORE-JOURNEY-015
|
||||
// FE-STORE-JOURNEY-001 to FE-STORE-JOURNEY-021
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { journeyApi } from '../api/client';
|
||||
@@ -414,6 +414,50 @@ describe('journeyStore', () => {
|
||||
expect(storedEntry?.photos[0].id).toBe(201);
|
||||
});
|
||||
|
||||
// ── provider photos (#1587) ──────────────────────────────────────────────
|
||||
|
||||
it('FE-STORE-JOURNEY-020: addProviderPhotos sends the group to the entry and answers what was added', async () => {
|
||||
const detail = buildJourneyDetail({ id: 50 });
|
||||
useJourneyStore.setState({ current: detail });
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/journeys/entries/100/provider-photos', async ({ request }) => {
|
||||
bodies.push(await request.json() as Record<string, unknown>);
|
||||
return HttpResponse.json({ photos: [{ id: 1 }], added: 1 });
|
||||
})
|
||||
);
|
||||
|
||||
const result = await useJourneyStore.getState().addProviderPhotos(100, 'immich', {
|
||||
assetIds: ['a1'], passphrase: 'pw', mediaTypes: ['video'],
|
||||
});
|
||||
|
||||
expect(result).toEqual({ photos: [{ id: 1 }], added: 1 });
|
||||
expect(bodies).toEqual([{ provider: 'immich', asset_ids: ['a1'], passphrase: 'pw', media_types: ['video'] }]);
|
||||
// The caller reloads: where the photo sorts is only known once the server
|
||||
// has its capture time.
|
||||
expect(useJourneyStore.getState().current).toBe(detail);
|
||||
});
|
||||
|
||||
it('FE-STORE-JOURNEY-021: addProviderPhotosToGallery sends the group to the gallery, and a failure comes through', async () => {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
server.use(
|
||||
http.post('/api/journeys/50/gallery/provider-photos', async ({ request }) => {
|
||||
bodies.push(await request.json() as Record<string, unknown>);
|
||||
return bodies.length === 1
|
||||
? HttpResponse.json({ photos: [], added: 2 })
|
||||
: new HttpResponse(null, { status: 500 });
|
||||
})
|
||||
);
|
||||
|
||||
const result = await useJourneyStore.getState().addProviderPhotosToGallery(50, 'synologyphotos', { assetIds: ['s1', 's2'] });
|
||||
|
||||
expect(result).toEqual({ photos: [], added: 2 });
|
||||
expect(bodies).toEqual([{ provider: 'synologyphotos', asset_ids: ['s1', 's2'] }]);
|
||||
await expect(
|
||||
useJourneyStore.getState().addProviderPhotosToGallery(50, 'synologyphotos', { assetIds: ['s3'] }),
|
||||
).rejects.toMatchObject({ response: { status: 500 } });
|
||||
});
|
||||
|
||||
// ── loadJourney silent refresh ───────────────────────────────────────────
|
||||
|
||||
it('FE-STORE-JOURNEY-016: loadJourney does not set loading when refreshing same journey', async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { create } from 'zustand'
|
||||
import { journeyApi } from '../api/client'
|
||||
import type { ProviderPhotosAdded } from '../api/providerPhotoBatches'
|
||||
import { uploadFilesResilient, type ResilientResult, type UploadProgress } from '../utils/uploadQueue'
|
||||
import { captureVideoPoster, isVideoFile } from '../utils/videoPoster'
|
||||
|
||||
@@ -142,6 +143,13 @@ export interface JourneyDetail extends Journey {
|
||||
my_role?: 'owner' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
/** Assets picked from one provider, with what the add needs besides their ids. */
|
||||
interface ProviderAssets {
|
||||
assetIds: string[]
|
||||
passphrase?: string
|
||||
mediaTypes?: string[]
|
||||
}
|
||||
|
||||
interface JourneyState {
|
||||
journeys: Journey[]
|
||||
current: JourneyDetail | null
|
||||
@@ -170,6 +178,16 @@ interface JourneyState {
|
||||
|
||||
uploadPhotos: (entryId: number, files: File[], cbs?: { onProgress?: (p: UploadProgress) => void }) => Promise<ResilientResult<JourneyPhoto>>
|
||||
uploadGalleryPhotos: (journeyId: number, files: File[], cbs?: { onProgress?: (p: UploadProgress) => void }) => Promise<ResilientResult<GalleryPhoto>>
|
||||
/**
|
||||
* Photos from a connected provider (Immich, Synology Photos) onto one entry,
|
||||
* or onto the gallery. They answer what was added and leave `current` alone:
|
||||
* the caller reloads the journey, because where a new photo sorts depends on
|
||||
* the capture time the server looks up after answering (#1587). A large add
|
||||
* goes out in batches, and one that fails part way rejects with a
|
||||
* ProviderPhotoBatchError that carries what the earlier batches stored.
|
||||
*/
|
||||
addProviderPhotos: (entryId: number, provider: string, group: ProviderAssets) => Promise<ProviderPhotosAdded>
|
||||
addProviderPhotosToGallery: (journeyId: number, provider: string, group: ProviderAssets) => Promise<ProviderPhotosAdded>
|
||||
unlinkPhoto: (entryId: number, journeyPhotoId: number) => Promise<void>
|
||||
deleteGalleryPhoto: (journeyId: number, journeyPhotoId: number) => Promise<void>
|
||||
deletePhoto: (photoId: number) => Promise<void>
|
||||
@@ -376,6 +394,12 @@ export const useJourneyStore = create<JourneyState>((set, get) => ({
|
||||
)
|
||||
},
|
||||
|
||||
addProviderPhotos: (entryId, provider, group) =>
|
||||
journeyApi.addProviderPhotos(entryId, provider, group.assetIds, undefined, group.passphrase, group.mediaTypes),
|
||||
|
||||
addProviderPhotosToGallery: (journeyId, provider, group) =>
|
||||
journeyApi.addProviderPhotosToGallery(journeyId, provider, group.assetIds, group.passphrase, group.mediaTypes),
|
||||
|
||||
unlinkPhoto: async (entryId, journeyPhotoId) => {
|
||||
await journeyApi.unlinkPhoto(entryId, journeyPhotoId)
|
||||
set(s => {
|
||||
|
||||
Reference in New Issue
Block a user