Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Media added from the library showed a blank tile after saving the product (#14838)
Damian Legawiece4f071198a73
diff --git a/packages/dashboard/e2e/media-library.spec.ts b/packages/dashboard/e2e/media-library.spec.tsindex 30f1de64f9..8a9f330f93 100644--- a/packages/dashboard/e2e/media-library.spec.ts+++ b/packages/dashboard/e2e/media-library.spec.ts@@ -1,9 +1,9 @@import { readFileSync } from 'node:fs'import { resolve } from 'node:path'-import { expect, type Page, test } from '@playwright/test'+import { expect, type Page, type Route, test } from '@playwright/test'import { gotoIndex, login } from './helpers'import { E2E_DIR } from './paths'-import { mediaCard, PRODUCTS_PATH } from './products-helpers'+import { createProduct, mediaCard, PRODUCTS_PATH } from './products-helpers'const MEDIA_PATH = (storeId: string) => `/${storeId}/products/media`const FIXTURE_IMAGE = readFileSync(resolve(E2E_DIR, 'fixtures/test-image.png'))@@ -25,6 +25,46 @@ async function findTile(page: Page, text: string) {return tile}+/**+ * Holds GET requests for `ms`, to force the order in which reloads land. The+ * app may cancel a held request meanwhile (a newer refetch supersedes it); it+ * is already gone then, so letting it through is skipped.+ */+function holdGets(ms: number) {+ return async (route: Route) => {+ if (route.request().method() === 'GET') await new Promise((resolve) => setTimeout(resolve, ms))+ await route.continue().catch(() => {})+ }+}++/** A library image with a description of its own, for the product media card to show by name. */+async function uploadDescribedImage(page: Page, storeId: string) {+ await page.goto(MEDIA_PATH(storeId))+ await expect(page.getByRole('heading', { name: /^media$/i })).toBeVisible({ timeout: 15_000 })+ const stamp = Date.now()+ const name = `e2e-picked-${stamp}.png`+ const alt = `Library swatch ${stamp}`+ await uploadImage(page, name)+ await (await findTile(page, name)).click()+ const sheet = page.getByRole('dialog')+ await sheet.locator('#media-alt').fill(alt)+ await sheet.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByText(/^saved$/i).first()).toBeVisible({ timeout: 15_000 })+ await sheet.getByRole('button', { name: /^cancel$/i }).click()+ return { stamp, name, alt }+}++/** On a product's edit page, adds a library file through the picker. */+async function addFromLibrary(page: Page, name: string, alt: string) {+ await page.getByRole('button', { name: /add from library/i }).click()+ const picker = page.getByRole('dialog')+ await picker.getByPlaceholder(/search by name/i).fill(name)+ await picker.getByRole('button', { name: alt }).click()+ await picker.getByRole('button', { name: /^add selected$/i }).click()+ await expect(picker).toBeHidden()+ await expect(page.getByRole('img', { name: alt })).toBeVisible()+}+test.describe('media library', () => {test('uploads an image and describes it for screen readers', async ({ page }) => {const creds = await login(page)@@ -48,6 +88,71 @@ test.describe('media library', () => {await expect(page.getByRole('listitem').filter({ hasText: 'A red test swatch' })).toBeVisible()})+ test('a file added to a product from the library keeps its preview after saving', async ({+ page,+ }) => {+ // Uploads, picks and saves with reloads held back on purpose — longer+ // than the default budget, especially against a loaded CI runner.+ test.slow()+ const creds = await login(page)+ const { stamp, name, alt } = await uploadDescribedImage(page, creds.store_id)+ await createProduct(page, creds.store_id, `Library pick ${stamp}`)+ await addFromLibrary(page, name, alt)++ // After the save, the media list landing while the product is still+ // reloading is the ordering that blanked new tiles and refilled the form+ // from the pre-save product. Slowing both reloads makes it certain.+ const mediaReload = /\/api\/v3\/admin\/products\/prod_[^/?]+\/media(\?|$)/+ const productReload = /\/api\/v3\/admin\/products\/prod_[^/?]+\?/+ await page.route(mediaReload, holdGets(2_000))+ await page.route(productReload, holdGets(4_000))+ const renamed = `Library pick ${stamp} (renamed)`+ await page.getByLabel(/^name$/i).fill(renamed)+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByText(/product saved/i)).toBeVisible({ timeout: 30_000 })+ // Read once, without retrying: a form refilled from the pre-save product+ // shows the old name only until the slowed reload lands.+ expect(await page.getByLabel(/^name$/i).inputValue()).toBe(renamed)+ await expect(page.getByRole('img', { name: alt })).toBeVisible({ timeout: 15_000 })+ // A held request the app cancelled never completes, so drop the holds+ // without waiting on them before the reload below.+ await page.unrouteAll({ behavior: 'ignoreErrors' })++ await page.reload()+ await expect(page.getByRole('img', { name: alt })).toBeVisible({ timeout: 15_000 })+ })++ test('a new library file stays on the product when the media reload after saving fails', async ({+ page,+ }) => {+ // Uploads, picks and saves with reloads held back on purpose — longer+ // than the default budget, especially against a loaded CI runner.+ test.slow()+ const creds = await login(page)+ const { stamp, name, alt } = await uploadDescribedImage(page, creds.store_id)+ await createProduct(page, creds.store_id, `Library pick ${stamp}`)+ await addFromLibrary(page, name, alt)++ // The media reload fails, and the product reload lands after the save —+ // the order in which the form used to refill from the pre-save media.+ const mediaReload = /\/api\/v3\/admin\/products\/prod_[^/?]+\/media(\?|$)/+ const productReload = /\/api\/v3\/admin\/products\/prod_[^/?]+\?/+ await page.route(mediaReload, (route) =>+ route.request().method() === 'GET'+ ? route.fulfill({ status: 500, json: { error: { code: 'internal', message: 'boom' } } })+ : route.continue(),+ )+ await page.route(productReload, holdGets(3_000))+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByText(/product saved/i)).toBeVisible({ timeout: 30_000 })+ // A failed reload has nothing to show, so give the media retry and the+ // slowed product reload time to land before checking the form kept the+ // submitted tile.+ await page.waitForTimeout(5_000)+ await expect(page.getByRole('img', { name: alt })).toBeVisible()+ await page.unrouteAll({ behavior: 'ignoreErrors' })+ })+test('deletes a file from the grid after confirming', async ({ page }) => {const creds = await login(page)await page.goto(MEDIA_PATH(creds.store_id))diff --git a/packages/dashboard/src/hooks/use-product-media.test.ts b/packages/dashboard/src/hooks/use-product-media.test.tsnew file mode 100644index 0000000000..f9c4828fbf--- /dev/null+++ b/packages/dashboard/src/hooks/use-product-media.test.ts@@ -0,0 +1,37 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const list = vi.fn()++vi.mock('@spree/dashboard-core', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@spree/dashboard-core')>()),+ adminClient: { products: { media: { list: (...args: unknown[]) => list(...args) } } },+}))++const { listAllProductMedia } = await import('./use-product-media')++function page(ids: string[], pageNumber: number, pages: number) {+ return { data: ids.map((id) => ({ id })), meta: { page: pageNumber, pages } }+}++describe('listAllProductMedia', () => {+ beforeEach(() => list.mockReset())++ it('reads every page so the whole list reaches the form', async () => {+ list+ .mockResolvedValueOnce(page(['media_1', 'media_2'], 1, 2))+ .mockResolvedValueOnce(page(['media_3'], 2, 2))++ const result = await listAllProductMedia('prod_1')++ expect(result.data.map((media) => media.id)).toEqual(['media_1', 'media_2', 'media_3'])+ expect(list).toHaveBeenLastCalledWith('prod_1', { limit: 100, page: 2 })+ })++ it('stops after one request when there is a single page', async () => {+ list.mockResolvedValueOnce(page(['media_1'], 1, 1))++ await listAllProductMedia('prod_1')++ expect(list).toHaveBeenCalledTimes(1)+ })+})diff --git a/packages/dashboard/src/hooks/use-product-media.ts b/packages/dashboard/src/hooks/use-product-media.tsindex eb826904cc..efd956cdc4 100644--- a/packages/dashboard/src/hooks/use-product-media.ts+++ b/packages/dashboard/src/hooks/use-product-media.ts@@ -4,10 +4,24 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'type MediaListSnapshot = { data: Media[] }+/**+ * Every media item of a product, across pages. The media card edits the+ * whole list at once and a save re-baselines the form from it, so reading+ * one page would silently drop the rest from the form.+ */+export async function listAllProductMedia(productId: string) {+ const first = await adminClient.products.media.list(productId, { limit: 100 })+ const data = [...first.data]+ for (let page = 2; page <= first.meta.pages; page++) {+ data.push(...(await adminClient.products.media.list(productId, { limit: 100, page })).data)+ }+ return { ...first, data }+}+export function useProductMedia(productId: string) {return useQuery({queryKey: useResourceKey('products', productId, 'media'),- queryFn: () => adminClient.products.media.list(productId),+ queryFn: () => listAllProductMedia(productId),enabled: !!productId,})}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 1d0a17d137..f4e9c1ddde 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -91,7 +91,14 @@ function ProductForm({ product }: { product: Product }) {const router = useRouter()const updateProduct = useUpdateProduct()const deleteProduct = useDeleteProduct()- const { data: mediaResponse } = useProductMedia(productId)+ const {+ data: mediaResponse,+ refetch: refetchMedia,+ isFetching: mediaRefetching,+ isRefetchError: mediaRefetchFailed,+ } = useProductMedia(productId)+ // Same query as the page's, read here for its refetch state only.+ const { isFetching: productRefetching } = useProduct(productId)const mediaItems = mediaResponse?.data@@ -131,13 +138,24 @@ function ProductForm({ product }: { product: Product }) {// like deleting a media item) would otherwise overwrite the merchant's// unsaved edits. After the save round-trip itself, RHF's submission// already cleared isDirty, so the post-save refetch still re-hydrates.+ //+ // Also wait while the product or its media is refetching (a retry+ // included): after a save the media list can land first, and resetting+ // then would pair it with the pre-save product and put the old values+ // back. The effect re-runs once both queries settle.+ //+ // A failed media refetch leaves the pre-save list cached, and refilling+ // from it would drop new uploads and library picks — so the form keeps its+ // own media then, while the product's server-assigned values (variant ids,+ // slugs) still land.useEffect(() => {- if (form.formState.isDirty) return- form.reset({+ if (form.formState.isDirty || productRefetching || mediaRefetching) return+ const values = {...productToFormValues(product, mediaItems),...extensionFormValues('product', product),- })- }, [product, mediaItems, form])+ }+ form.reset(mediaRefetchFailed ? { ...values, media: form.getValues('media') } : values)+ }, [product, mediaItems, productRefetching, mediaRefetching, mediaRefetchFailed, form])// Media-only hydration that bypasses the isDirty guard for the// already-empty case. Scenario: page mounts with mediaResponse still@@ -197,32 +215,31 @@ function ProductForm({ product }: { product: Product }) {// hydration effect would otherwise keep isDirty true forever (since// we then skip the refetch's reset).//- // Strip the file-transport keys and the UI-only fields from baseline- // media so a subsequent save before the mediaResponse refetch lands- // can't re-ship them and create a duplicate Asset — `signed_id` would- // re-attach the upload, `source_media_id` would place the library file a- // second time. The persisted media ids hydrate on the next refetch.+ // Strip the file-transport keys from baseline media so a second save+ // can't re-ship them and create a duplicate — `signed_id` would+ // re-attach the upload, `source_media_id` would place the library file+ // a second time. Previews stay, so tiles keep their image meanwhile.const baseline: ProductFormValues = {...data,// `data` is the parsed (extension-stripped) shape — put extension// values back so the reset doesn't blank their inputs pre-refetch....extensionValues,media: (data.media ?? []).map(- ({- signed_id: _sid,- source_media_id: _smid,- poster_signed_id: _psid,- previewUrl: _p,- fullPreviewUrl: _fp,- posterUrl: _pu,- videoUrl: _vu,- downloadUrl: _du,- uploadId: _u,- ...rest- }) => rest,+ ({ signed_id: _sid, source_media_id: _smid, poster_signed_id: _psid, ...rest }) => rest,),}form.reset(baseline)++ // New uploads and library picks gain their ids only in the persisted+ // list. The save's own invalidation refetch can land while the form is+ // still dirty — the hydration effect skips it, and an identical later+ // refetch never re-runs that effect — so read it here. Applied only if+ // the merchant hasn't touched media since, and only from a successful+ // read: a failed refetch keeps the stale list in `data`.+ const mediaRefetch = await refetchMedia()+ if (mediaRefetch.status === 'success' && !form.formState.dirtyFields.media) {+ form.resetField('media', { defaultValue: mediaRefetch.data.data.map(mediaToFormValues) })+ }toastManager.add({ type: 'success', title: t('admin.messages.product_saved') })} catch (err) {if (mapSpreeErrorsToForm(err, form.setError)) return