Re-align the photo carousel when the list changes under it
CI / Lint (pull_request) Successful in 1m15s
CI / Test (pull_request) Successful in 1m46s
Release Drafter / Update release notes draft (pull_request) Successful in 18s

On a cold cache the gallery opened on the linked photo, but the large main
view showed the place's first photo. The gallery opens as soon as the linked
event is in the store, then the remaining photos stream in and
parsePlacePhotos promotes the first landscape to index 0, shifting the linked
photo's offset. scrollToNewPhoto only re-ran when the focused event changed,
so the track stayed at the old offset while the thumbnail highlight (driven by
the template, not the scroll position) looked correct.

Re-align to the focused slide when the photo set changes, keyed by the joined
event ids so it only fires on a genuine add/remove/reorder. The re-align is
deferred with requestAnimationFrame so the DOM has updated, and setupCarousel
re-observes the slides the same way so the intersection observer keeps
tracking them.
This commit is contained in:
raucao committed 2026-11-30 13:02:08 +04:00
1 parent a2bda44a65
commit bb05e7fa43
2 files changed
+157 -49

No files matched your search

+79 -48
View File
@@ -21,6 +21,14 @@ export default class PhotoCarousel extends Component {
return this.args.photos || [];
}
// A stable key that only changes when the photo set changes (add, remove or
// reorder). `parsePlacePhotos` rebuilds the list on every update, so the
// carousel uses this to re-align to the focused slide when the list shifts
// underneath it, not only when the focused photo changes.
get photoKey() {
return this.photos.map((photo) => photo.eventId).join(',');
}
get showChevrons() {
// Only show chevrons if there's more than one photo
return this.photos.length > 1;
@@ -58,58 +66,73 @@ export default class PhotoCarousel extends Component {
isProgrammaticScroll = false;
scrollToNewPhoto = modifier((element, [eventId]) => {
if (eventId && eventId !== this.lastEventId) {
const isInitial = !this.lastEventId;
this.lastEventId = eventId;
// Scrolls the track to the slide for `eventId`. `instant` jumps without
// animating (first paint, and re-aligning when the list shifts under us);
// otherwise it uses the CSS smooth scrolling.
scrollToSlide(element, eventId, instant) {
const targetSlide = element.querySelector(`[data-event-id="${eventId}"]`);
if (!targetSlide) {
this.isProgrammaticScroll = false;
return;
}
// Prevent feedback loop if this carousel initiated the change
if (this.internalEventId === eventId) {
return;
}
const originalScrollBehavior = element.style.scrollBehavior;
if (instant) {
element.style.scrollBehavior = 'auto';
}
element.scrollLeft = targetSlide.offsetLeft;
if (instant) {
// Restore smooth scrolling after the jump.
setTimeout(() => {
element.style.scrollBehavior = originalScrollBehavior;
}, 50);
}
setTimeout(
() => {
this.isProgrammaticScroll = false;
},
instant ? 50 : 500
);
}
this.internalEventId = eventId;
this.isProgrammaticScroll = true;
scrollToNewPhoto = modifier((element, [eventId, photoKey]) => {
if (!eventId) return;
const scrollAction = () => {
const targetSlide = element.querySelector(
`[data-event-id="${eventId}"]`
);
if (targetSlide) {
if (isInitial) {
const originalScrollBehavior = element.style.scrollBehavior;
element.style.scrollBehavior = 'auto';
element.scrollLeft = targetSlide.offsetLeft;
const eventChanged = eventId !== this.lastEventId;
const photosChanged = photoKey !== this.lastPhotoKey;
if (!eventChanged && !photosChanged) return;
// Restore smooth scroll after the jump
setTimeout(() => {
element.style.scrollBehavior = originalScrollBehavior;
this.isProgrammaticScroll = false;
}, 50);
} else {
// Use native CSS smooth scrolling for subsequent clicks
element.scrollLeft = targetSlide.offsetLeft;
// Clear programmatic scroll flag after a delay to let scroll finish
setTimeout(() => {
this.isProgrammaticScroll = false;
}, 500);
}
} else {
this.isProgrammaticScroll = false;
}
};
const isInitial = !this.lastEventId;
this.lastEventId = eventId;
this.lastPhotoKey = photoKey;
if (isInitial) {
// Execute immediately for the first render to prevent flash
scrollAction();
} else {
// Allow DOM to update first for subsequent clicks
setTimeout(scrollAction, 100);
}
// Prevent feedback loop if this carousel initiated the change. Skipped when
// only the list changed: we do need to re-align to the same event then.
if (eventChanged && this.internalEventId === eventId) {
return;
}
this.internalEventId = eventId;
this.isProgrammaticScroll = true;
if (isInitial) {
// Execute immediately for the first render to prevent flash
this.scrollToSlide(element, eventId, true);
} else if (eventChanged) {
// Allow DOM to update first for subsequent clicks
setTimeout(() => this.scrollToSlide(element, eventId, false), 100);
} else {
// The photo list changed without the focused event changing: a new photo
// was inserted before it, so its offset shifted. Re-align once the DOM
// has re-rendered, without animating.
requestAnimationFrame(() => {
if (this.isDestroyed) return;
this.scrollToSlide(element, eventId, true);
});
}
});
setupCarousel = modifier((element) => {
setupCarousel = modifier((element, [photoKey]) => {
this.carouselElement = element;
// Defer the initial calculation slightly to ensure CSS and images have applied
@@ -151,8 +174,16 @@ export default class PhotoCarousel extends Component {
}
);
const slides = element.querySelectorAll('.carousel-slide');
slides.forEach((slide) => intersectionObserver.observe(slide));
// `photoKey` is part of the modifier's args so this re-runs when the
// photo set changes; (re)observe after the DOM update so slides added by
// that change are tracked too. The key guard drops a stale frame from a
// superseded run.
this.observedPhotoKey = photoKey;
requestAnimationFrame(() => {
if (this.isDestroyed || this.observedPhotoKey !== photoKey) return;
const slides = element.querySelectorAll('.carousel-slide');
slides.forEach((slide) => intersectionObserver.observe(slide));
});
}
return () => {
@@ -205,9 +236,9 @@ export default class PhotoCarousel extends Component {
<div class="photo-carousel {{this.variantClass}}">
<div
class="photo-carousel-track"
{{this.setupCarousel}}
{{this.setupCarousel this.photoKey}}
{{this.resetScrollPosition @resetKey}}
{{this.scrollToNewPhoto @scrollToEventId}}
{{this.scrollToNewPhoto @scrollToEventId this.photoKey}}
{{on "scroll" this.updateScrollState}}
>
{{#each this.photos as |photo|}}
@@ -1,6 +1,6 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'marco/tests/helpers';
import { render, click } from '@ember/test-helpers';
import { render, click, settled, waitUntil } from '@ember/test-helpers';
import PhotoCarousel from 'marco/components/photo-carousel';
module('Integration | Component | photo-carousel', function (hooks) {
@@ -154,4 +154,81 @@ module('Integration | Component | photo-carousel', function (hooks) {
.dom('[data-event-id="event-3"]')
.doesNotHaveClass('active', 'other photos stay inactive');
});
test('it re-aligns to the focused photo when the list changes under it', async function (assert) {
const originalOffsetLeft = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'offsetLeft'
);
// Simulate the carousel layout: each slide is one track-width wide (100px),
// so its offset is its index among the current slides.
Object.defineProperty(HTMLElement.prototype, 'offsetLeft', {
configurable: true,
get() {
if (!this.dataset?.eventId) return 0;
const slides = [
...(this.parentElement?.querySelectorAll('.carousel-slide') ?? []),
];
return slides.indexOf(this) * 100;
},
});
try {
this.photos = [
{ eventId: 'event-a', url: 'a.jpg', isLandscape: true },
{ eventId: 'event-b', url: 'b.jpg', isLandscape: true },
];
this.focusEventId = 'event-b';
await render(
<template>
<div class="test-container">
<PhotoCarousel
@photos={{this.photos}}
@scrollToEventId={{this.focusEventId}}
/>
</div>
</template>
);
// Track scrollLeft directly; the real one would clamp without layout.
const track = document.querySelector('.photo-carousel-track');
let scrollLeft = 0;
Object.defineProperty(track, 'scrollLeft', {
configurable: true,
get: () => scrollLeft,
set: (value) => {
scrollLeft = value;
},
});
// A new photo is prepended, shifting the focused photo (event-b) from
// index 1 to index 2, without the focused event changing.
this.set('photos', [
{ eventId: 'event-c', url: 'c.jpg', isLandscape: true },
{ eventId: 'event-a', url: 'a.jpg', isLandscape: true },
{ eventId: 'event-b', url: 'b.jpg', isLandscape: true },
]);
await settled();
await waitUntil(() => scrollLeft === 200, { timeout: 1000 });
assert.strictEqual(
scrollLeft,
200,
'the track re-aligns to the shifted focused photo'
);
} finally {
if (originalOffsetLeft) {
Object.defineProperty(
HTMLElement.prototype,
'offsetLeft',
originalOffsetLeft
);
} else {
delete HTMLElement.prototype.offsetLeft;
}
}
});
});