Preserve product-list scroll when switching variants.

Append #product-card-{variantId} to index selection links so the browser restores the card after the full-page reload, matching add-to-cart.
This commit is contained in:
2026-11-21 23:34:44 +00:00
parent 3577c9dc16
commit ba0af1afd9
2 changed files with 50 additions and 2 deletions
@@ -1,4 +1,6 @@
import { DeliveryMode } from '../../product/types/DeliveryMode';
import type { CategoriesService } from '../../product/services/CategoriesService'; import type { CategoriesService } from '../../product/services/CategoriesService';
import type { StorefrontProduct } from '../types/StorefrontProduct';
import { StorefrontProductViewService } from './StorefrontProductViewService'; import { StorefrontProductViewService } from './StorefrontProductViewService';
describe('StorefrontProductViewService', () => { describe('StorefrontProductViewService', () => {
@@ -19,4 +21,46 @@ describe('StorefrontProductViewService', () => {
{ id: 'category-2', name: 'Physical', href: '/shop/categories/category-2' } { id: 'category-2', name: 'Physical', href: '/shop/categories/category-2' }
]); ]);
}); });
it('appends product-card anchors to index variant selection hrefs', () => {
const product: StorefrontProduct = {
id: 'product-1',
title: 'Widget',
deliveryMode: DeliveryMode.Auto,
descriptionHtml: null,
variants: [
{
id: 'variant-1',
productId: 'product-1',
productTitle: 'Widget',
title: 'Default',
price: 10,
deliveryMode: DeliveryMode.Auto,
stockAvailable: 1,
stockForSession: 1,
thumbnailUrl: null,
images: []
},
{
id: 'variant-2',
productId: 'product-1',
productTitle: 'Widget',
title: 'Alt',
price: 12,
deliveryMode: DeliveryMode.Auto,
stockAvailable: 1,
stockForSession: 1,
thumbnailUrl: null,
images: []
}
]
};
const [view] = service.toProductsIndexView([product], {});
expect(view.variants.map(variant => variant.selectionHref)).toEqual([
'/#product-card-variant-1',
'/?sel=product-1%3Avariant-2#product-card-variant-2'
]);
});
}); });
@@ -220,11 +220,15 @@ export class StorefrontProductViewService {
} }
private buildIndexUrl(basePath: string, product: StorefrontProduct, variantId: string): string { private buildIndexUrl(basePath: string, product: StorefrontProduct, variantId: string): string {
const anchor = `#product-card-${variantId}`;
if (variantId === product.variants[0].id) { if (variantId === product.variants[0].id) {
return basePath; return `${basePath}${anchor}`;
} }
return `${basePath}?${new URLSearchParams({ sel: `${product.id}:${variantId}` }).toString()}`; const params = new URLSearchParams({ sel: `${product.id}:${variantId}` });
return `${basePath}?${params.toString()}${anchor}`;
} }
async resolveProductBackLink(categoryId?: string): Promise<{ backHref: string; backLabel: string }> { async resolveProductBackLink(categoryId?: string): Promise<{ backHref: string; backLabel: string }> {