Compare commits

..

5 Commits

Author SHA1 Message Date
midzelis
592874208b feat: add spinner to SearchResults 2025-10-07 14:44:05 +00:00
midzelis
90ab75f968 refactor: push up layout() into PhotostreamSegment 2025-10-07 14:41:57 +00:00
midzelis
575eecfd97 refactor(web): convert timeline layout options to derived state
- Replace createLayoutOptions() method with derived layoutOptions property for better reactivity. 
- Remove duplicate refreshLayout() implementation 
- Simplify setLayoutOptions() by removing unnecessary change tracking.
2025-10-07 01:29:52 +00:00
midzelis
674def4088 refactor: remove scroll compensation logic from photostream components 2025-10-07 01:29:52 +00:00
midzelis
8943242b7f fix: reactivity warnings in searchbox 2025-10-07 01:29:52 +00:00
14 changed files with 148 additions and 195 deletions

View File

@@ -9,8 +9,10 @@
import StreamWithViewer from '$lib/components/timeline/StreamWithViewer.svelte';
import Skeleton from '$lib/elements/Skeleton.svelte';
import { SearchResultsManager } from '$lib/managers/searchresults-manager/SearchResultsManager.svelte';
import { SearchResultsSegment } from '$lib/managers/searchresults-manager/SearchResultsSegment.svelte';
import { AssetInteraction } from '$lib/stores/asset-interaction.svelte';
import { LoadingSpinner } from '@immich/ui';
import type { Snippet } from 'svelte';
interface Props {
@@ -58,10 +60,8 @@
<Skeleton height={segment.height - segment.timelineManager.headerHeight} {stylePaddingHorizontalPx} />
{/snippet}
{#snippet segment({ segment, onScrollCompensationMonthInDOM })}
{#snippet segment({ segment })}
<SelectableSegment
{segment}
{onScrollCompensationMonthInDOM}
timelineManager={searchResultsManager}
{assetInteraction}
isSelectionMode={false}
@@ -94,5 +94,12 @@
{/snippet}
</SelectableSegment>
{/snippet}
{#snippet segmentFooter({ segment })}
{#if (segment as SearchResultsSegment).hasNextPage}
<div class="w-full flex justify-center items-center h-50">
<LoadingSpinner size="giant" />
</div>
{/if}
{/snippet}
</Photostream>
</StreamWithViewer>

View File

@@ -33,9 +33,13 @@
let isFocus = $state(false);
let close: (() => Promise<void>) | undefined;
let navigating = false;
const listboxId = generateId();
onDestroy(() => {
if (navigating) {
return;
}
searchStore.isSearchEnabled = false;
});
@@ -44,6 +48,7 @@
closeDropdown();
searchStore.isSearchEnabled = false;
navigating = true;
await goto(`${AppRoute.SEARCH}?${params}`);
};
@@ -73,6 +78,9 @@
};
const onFocusOut = () => {
if (navigating) {
return;
}
searchStore.isSearchEnabled = false;
};
@@ -161,6 +169,9 @@
};
const closeDropdown = () => {
if (navigating) {
return;
}
showSuggestions = false;
isFocus = false;
searchHistoryBox?.clearSelection();

View File

@@ -15,7 +15,13 @@
{
segment: PhotostreamSegment;
scrollToFunction: (top: number) => void;
onScrollCompensationMonthInDOM: (compensation: { heightDelta?: number; scrollTop?: number }) => void;
},
]
>;
segmentFooter: Snippet<
[
{
segment: PhotostreamSegment;
},
]
>;
@@ -60,6 +66,8 @@
let {
segment,
segmentFooter,
skeleton,
enableRouting,
timelineManager = $bindable(),
@@ -73,7 +81,7 @@
isShowDeleteConfirmation = $bindable(false),
children,
skeleton,
empty,
header,
handleTimelineScroll = () => {},
@@ -90,7 +98,6 @@
let { gridScrollTarget } = assetViewingStore;
let element: HTMLElement | undefined = $state();
let timelineElement: HTMLElement | undefined = $state();
const maxMd = $derived(mobileDevice.maxMd);
const isEmpty = $derived(timelineManager.isInitialized && timelineManager.months.length === 0);
@@ -98,6 +105,9 @@
$effect(() => {
const layoutOptions = maxMd ? smallHeaderHeight : largeHeaderHeight;
timelineManager.setLayoutOptions(layoutOptions);
// this next line is important in order to ensure that the reactive signals of ViewerAsset.#intersecting
// are marked as dependencies of timeline.#scrollTop.
updateSlidingWindow();
});
const scrollTo = (top: number) => {
@@ -107,44 +117,13 @@
updateSlidingWindow();
};
const scrollBy = (y: number) => {
if (element) {
element.scrollBy(0, y);
}
updateSlidingWindow();
};
const handleTriggeredScrollCompensation = (compensation: { heightDelta?: number; scrollTop?: number }) => {
const { heightDelta, scrollTop } = compensation;
if (heightDelta !== undefined) {
scrollBy(heightDelta);
} else if (scrollTop !== undefined) {
scrollTo(scrollTop);
}
timelineManager.clearScrollCompensation();
};
const getAssetHeight = (assetId: string, monthGroup: PhotostreamSegment) => {
// the following method may trigger any layouts, so need to
// handle any scroll compensation that may have been set
const height = monthGroup.findAssetAbsolutePosition(assetId);
// this is in a while loop, since scrollCompensations invoke scrolls
// which may load months, triggering more scrollCompensations. Call
// this in a loop, until no more layouts occur.
while (timelineManager.scrollCompensation.monthGroup) {
handleTriggeredScrollCompensation(timelineManager.scrollCompensation);
}
return height;
};
export const scrollToAssetId = async (assetId: string) => {
const monthGroup = await timelineManager.findSegmentForAssetId(assetId);
if (!monthGroup) {
return false;
}
const height = getAssetHeight(assetId, monthGroup);
const height = monthGroup.findAssetAbsolutePosition(assetId);
scrollTo(height);
return true;
};
@@ -237,7 +216,6 @@
onscroll={() => (handleTimelineScroll(), updateSlidingWindow(), updateIsScrolling())}
>
<section
bind:this={timelineElement}
id="virtual-timeline"
class:relative={true}
class:invisible={showSkeleton}
@@ -262,7 +240,7 @@
<div
class="month-group"
style:margin-bottom={timelineManager.createLayoutOptions().spacing + 'px'}
style:margin-bottom={timelineManager.layoutOptions.spacing + 'px'}
style:position="absolute"
style:transform={`translate3d(0,${absoluteHeight}px,0)`}
style:height={`${monthGroup.height}px`}
@@ -274,10 +252,18 @@
{@render segment({
segment: monthGroup,
scrollToFunction: scrollTo,
onScrollCompensationMonthInDOM: handleTriggeredScrollCompensation,
})}
{/if}
</div>
{#if segmentFooter}
<div
style:position="absolute"
style:transform={`translate3d(0,${absoluteHeight + monthGroup.height}px,0)`}
style:width="100%"
>
{@render segmentFooter?.({ segment: monthGroup })}
</div>
{/if}
{/each}
<!-- spacer for lead-out -->
<div

View File

@@ -24,7 +24,6 @@
[
{
segment: PhotostreamSegment;
onScrollCompensationMonthInDOM: (compensation: { heightDelta?: number; scrollTop?: number }) => void;
},
]
>;

View File

@@ -5,7 +5,6 @@
import { navigate } from '$lib/utils/navigation';
import type { PhotostreamManager } from '$lib/managers/photostream-manager/PhotostreamManager.svelte';
import type { PhotostreamSegment } from '$lib/managers/photostream-manager/PhotostreamSegment.svelte';
import { TimelineManager } from '$lib/managers/timeline-manager/timeline-manager.svelte';
import { assetsSnapshot } from '$lib/managers/timeline-manager/utils.svelte';
import { searchStore } from '$lib/stores/search.svelte';
@@ -21,28 +20,17 @@
},
]
>;
segment: PhotostreamSegment;
isSelectionMode: boolean;
singleSelect: boolean;
timelineManager: PhotostreamManager;
assetInteraction: AssetInteraction;
onAssetOpen?: (asset: TimelineAsset, defaultAssetOpen: () => void) => void;
onAssetSelect?: (asset: TimelineAsset) => void;
onScrollCompensationMonthInDOM: (compensation: { heightDelta?: number; scrollTop?: number }) => void;
}
let {
segment,
content,
isSelectionMode,
singleSelect,
assetInteraction,
timelineManager,
onAssetOpen,
onAssetSelect,
onScrollCompensationMonthInDOM,
}: Props = $props();
let { content, isSelectionMode, singleSelect, assetInteraction, timelineManager, onAssetOpen, onAssetSelect }: Props =
$props();
let shiftKeyIsDown = $state(false);
let isEmpty = $derived(timelineManager.isInitialized && timelineManager.months.length === 0);
@@ -189,12 +177,6 @@
const assets = assetsSnapshot(timelineManager.retrieveLoadedRange(startAsset, endAsset));
assetInteraction.setAssetSelectionCandidates(assets);
};
$effect.root(() => {
if (timelineManager.scrollCompensation.monthGroup === segment) {
onScrollCompensationMonthInDOM(timelineManager.scrollCompensation);
}
});
</script>
<svelte:document onkeydown={onKeyDown} onkeyup={onKeyUp} />

View File

@@ -99,10 +99,8 @@
title={(segment as MonthGroup).monthGroupTitle}
/>
{/snippet}
{#snippet segment({ segment, onScrollCompensationMonthInDOM })}
{#snippet segment({ segment })}
<SelectableSegment
{segment}
{onScrollCompensationMonthInDOM}
{timelineManager}
{assetInteraction}
{isSelectionMode}

View File

@@ -1,7 +1,7 @@
import { updateIntersectionMonthGroup } from '$lib/managers/timeline-manager/internal/intersection-support.svelte';
import { updateGeometry } from '$lib/managers/timeline-manager/internal/layout-support.svelte';
import { CancellableTask } from '$lib/utils/cancellable-task';
import { clamp, debounce } from 'lodash-es';
import { debounce } from 'lodash-es';
import {
PhotostreamSegment,
@@ -21,21 +21,27 @@ import { setDifference } from '$lib/utils/timeline-util';
export abstract class PhotostreamManager {
isInitialized = $state(false);
topSectionHeight = $state(0);
bottomSectionHeight = $state(60);
abstract get months(): PhotostreamSegment[];
assetCount = $derived.by(() => this.months.reduce((accumulator, b) => accumulator + b.assetsCount, 0));
timelineHeight = $derived.by(
() => this.months.reduce((accumulator, b) => accumulator + b.height, 0) + this.topSectionHeight,
);
assetCount = $derived.by(() => this.months.reduce((accumulator, b) => accumulator + b.assetsCount, 0));
topIntersectingMonthGroup: PhotostreamSegment | undefined = $state();
visibleWindow = $derived.by(() => ({
top: this.#scrollTop,
bottom: this.#scrollTop + this.viewportHeight,
}));
layoutOptions = $derived({
spacing: 2,
heightTolerance: 0.15,
rowHeight: this.rowHeight,
rowWidth: Math.floor(this.viewportWidth),
});
protected initTask = new CancellableTask(
() => (this.isInitialized = true),
() => (this.isInitialized = false),
@@ -54,26 +60,14 @@ export abstract class PhotostreamManager {
#suspendTransitions = $state(false);
#resetScrolling = debounce(() => (this.#scrolling = false), 1000);
#resetSuspendTransitions = debounce(() => (this.suspendTransitions = false), 1000);
scrollCompensation: {
heightDelta: number | undefined;
scrollTop: number | undefined;
monthGroup: PhotostreamSegment | undefined;
} = $state({
heightDelta: 0,
scrollTop: 0,
monthGroup: undefined,
});
#updatingIntersections = false;
constructor() {}
abstract get months(): PhotostreamSegment[];
setLayoutOptions({ headerHeight = 48, rowHeight = 235, gap = 12 }: TimelineManagerLayoutOptions) {
let changed = false;
changed ||= this.#setHeaderHeight(headerHeight);
changed ||= this.#setGap(gap);
changed ||= this.#setRowHeight(rowHeight);
if (changed) {
this.refreshLayout();
}
this.#setHeaderHeight(headerHeight);
this.#setGap(gap);
this.#setRowHeight(rowHeight);
}
#setHeaderHeight(value: number) {
@@ -139,7 +133,7 @@ export abstract class PhotostreamManager {
const changed = value !== this.#viewportWidth;
this.#viewportWidth = value;
this.suspendTransitions = true;
void this.updateViewportGeometry(changed);
this.updateViewportGeometry(changed);
}
get viewportWidth() {
@@ -149,7 +143,7 @@ export abstract class PhotostreamManager {
set viewportHeight(value: number) {
this.#viewportHeight = value;
this.#suspendTransitions = true;
void this.updateViewportGeometry(false);
this.updateViewportGeometry(false);
}
get viewportHeight() {
@@ -157,45 +151,21 @@ export abstract class PhotostreamManager {
}
updateSlidingWindow(scrollTop: number) {
if (this.#scrollTop !== scrollTop) {
this.#scrollTop = scrollTop;
this.updateIntersections();
}
}
clearScrollCompensation() {
this.scrollCompensation = {
heightDelta: undefined,
scrollTop: undefined,
monthGroup: undefined,
};
this.#scrollTop = scrollTop;
this.updateIntersections();
}
updateIntersections() {
if (!this.isInitialized || this.visibleWindow.bottom === this.visibleWindow.top) {
if (this.#updatingIntersections || !this.isInitialized || this.visibleWindow.bottom === this.visibleWindow.top) {
return;
}
let topIntersectingMonthGroup = undefined;
this.#updatingIntersections = true;
for (const month of this.months) {
updateIntersectionMonthGroup(this, month);
if (!topIntersectingMonthGroup && month.actuallyIntersecting) {
topIntersectingMonthGroup = month;
}
}
if (topIntersectingMonthGroup !== undefined && this.topIntersectingMonthGroup !== topIntersectingMonthGroup) {
this.topIntersectingMonthGroup = topIntersectingMonthGroup;
}
for (const month of this.months) {
if (month === this.topIntersectingMonthGroup) {
this.topIntersectingMonthGroup.percent = clamp(
(this.visibleWindow.top - this.topIntersectingMonthGroup.top) / this.topIntersectingMonthGroup.height,
0,
1,
);
} else {
month.percent = 0;
}
}
this.#updatingIntersections = false;
}
async init() {
@@ -239,17 +209,6 @@ export abstract class PhotostreamManager {
this.updateIntersections();
}
createLayoutOptions() {
const viewportWidth = this.viewportWidth;
return {
spacing: 2,
heightTolerance: 0.15,
rowHeight: this.#rowHeight,
rowWidth: Math.floor(viewportWidth),
};
}
async loadSegment(identifier: SegmentIdentifier, options?: { cancelable: boolean }): Promise<void> {
let cancelable = true;
if (options) {
@@ -284,13 +243,6 @@ export abstract class PhotostreamManager {
return Promise.resolve(void 0);
}
refreshLayout() {
for (const month of this.months) {
updateGeometry(this, month, { invalidateHeight: true });
}
this.updateIntersections();
}
getMaxScrollPercent() {
const totalHeight = this.timelineHeight + this.bottomSectionHeight + this.topSectionHeight;
return (totalHeight - this.viewportHeight) / totalHeight;

View File

@@ -4,8 +4,10 @@ import { t } from 'svelte-i18n';
import { get } from 'svelte/store';
import type { PhotostreamManager } from '$lib/managers/photostream-manager/PhotostreamManager.svelte';
import { getTestHook } from '$lib/managers/photostream-manager/TestHooks.svelte';
import type { AssetOperation, MoveAsset, TimelineAsset } from '$lib/managers/timeline-manager/types';
import type { ViewerAsset } from '$lib/managers/timeline-manager/viewer-asset.svelte';
import { getJustifiedLayoutFromAssets, getPosition } from '$lib/utils/layout-utils';
export type SegmentIdentifier = {
matches(segment: PhotostreamSegment): boolean;
@@ -20,7 +22,6 @@ export abstract class PhotostreamSegment {
#assets = $derived.by(() => this.viewerAssets.map((viewerAsset) => viewerAsset.asset));
initialCount = $state(0);
percent = $state(0);
assetsCount = $derived.by(() => (this.isLoaded ? this.viewerAssets.length : this.initialCount));
loader = new CancellableTask(
@@ -30,6 +31,10 @@ export abstract class PhotostreamSegment {
);
isHeightActual = $state(false);
constructor() {
getTestHook()?.hookSegment(this);
}
abstract get timelineManager(): PhotostreamManager;
abstract get identifier(): SegmentIdentifier;
@@ -66,9 +71,13 @@ export abstract class PhotostreamSegment {
}
async load(cancelable: boolean): Promise<'DONE' | 'WAITED' | 'CANCELED' | 'LOADED' | 'ERRORED'> {
return await this.loader.execute(async (signal: AbortSignal) => {
const executionStatus = await this.loader.execute(async (signal: AbortSignal) => {
await this.fetch(signal);
}, cancelable);
if (executionStatus === 'LOADED') {
this.layout();
}
return executionStatus;
}
protected abstract fetch(signal: AbortSignal): Promise<void>;
@@ -88,42 +97,34 @@ export abstract class PhotostreamSegment {
if (this.#height === height) {
return;
}
const { timelineManager: store, percent } = this;
const index = store.months.indexOf(this);
let needsIntersectionUpdate = false;
const timelineManager = this.timelineManager;
const index = timelineManager.months.indexOf(this);
const heightDelta = height - this.#height;
this.#height = height;
const prevMonthGroup = store.months[index - 1];
const prevMonthGroup = timelineManager.months[index - 1];
if (prevMonthGroup) {
const newTop = prevMonthGroup.#top + prevMonthGroup.#height;
if (this.#top !== newTop) {
this.#top = newTop;
}
}
for (let cursor = index + 1; cursor < store.months.length; cursor++) {
const monthGroup = this.timelineManager.months[cursor];
if (heightDelta === 0) {
return;
}
for (let cursor = index + 1; cursor < timelineManager.months.length; cursor++) {
const monthGroup = timelineManager.months[cursor];
const newTop = monthGroup.#top + heightDelta;
if (monthGroup.#top !== newTop) {
monthGroup.#top = newTop;
needsIntersectionUpdate = true;
}
}
if (store.topIntersectingMonthGroup) {
const currentIndex = store.months.indexOf(store.topIntersectingMonthGroup);
if (currentIndex > 0) {
if (index < currentIndex) {
store.scrollCompensation = {
heightDelta,
scrollTop: undefined,
monthGroup: this,
};
} else if (percent > 0) {
const top = this.top + height * percent;
store.scrollCompensation = {
heightDelta: undefined,
scrollTop: top,
monthGroup: this,
};
}
}
if (needsIntersectionUpdate) {
timelineManager.updateIntersections();
}
}
@@ -144,7 +145,16 @@ export abstract class PhotostreamSegment {
this.loader?.cancel();
}
layout(_?: boolean) {}
layout(_?: boolean): void {
const timelineAssets = this.viewerAssets.map((viewerAsset) => viewerAsset.asset);
const layoutOptions = this.timelineManager.layoutOptions;
const geometry = getJustifiedLayoutFromAssets(timelineAssets, layoutOptions);
this.height = timelineAssets.length === 0 ? 0 : geometry.containerHeight + this.timelineManager.headerHeight;
for (let i = 0; i < this.viewerAssets.length; i++) {
const position = getPosition(geometry, i);
this.viewerAssets[i].position = position;
}
}
updateIntersection({ intersecting, actuallyIntersecting }: { intersecting: boolean; actuallyIntersecting: boolean }) {
this.intersecting = intersecting;

View File

@@ -0,0 +1,11 @@
import type { PhotostreamSegment } from '$lib/managers/photostream-manager/PhotostreamSegment.svelte';
let testHooks: { hookSegment: (segment: PhotostreamSegment) => void } | undefined = undefined;
export function setTestHook(hooks: { hookSegment: (segment: PhotostreamSegment) => void }) {
testHooks = hooks;
}
export function getTestHook() {
return testHooks;
}

View File

@@ -8,7 +8,6 @@ import type {
} from '$lib/managers/searchresults-manager/SearchResultsManager.svelte';
import type { TimelineAsset } from '$lib/managers/timeline-manager/types';
import { ViewerAsset } from '$lib/managers/timeline-manager/viewer-asset.svelte';
import { getJustifiedLayoutFromAssets, getPosition } from '$lib/utils/layout-utils';
import { toTimelineAsset } from '$lib/utils/timeline-util';
import { TUNABLES } from '$lib/utils/tunables';
import { searchAssets, searchSmart } from '@immich/sdk';
@@ -22,7 +21,7 @@ export class SearchResultsSegment extends PhotostreamSegment {
#id: string;
#searchTerms: SearchTerms;
#currentPage: string | null = null;
#nextPage: string | null = null;
#nextPage: string | null = $state(null);
#viewerAssets: ViewerAsset[] = $state([]);
@@ -73,22 +72,14 @@ export class SearchResultsSegment extends PhotostreamSegment {
this.layout();
}
layout(): void {
const timelineAssets = this.#viewerAssets.map((viewerAsset) => viewerAsset.asset);
const layoutOptions = this.timelineManager.createLayoutOptions();
const geometry = getJustifiedLayoutFromAssets(timelineAssets, layoutOptions);
this.height = timelineAssets.length === 0 ? 0 : geometry.containerHeight + this.timelineManager.headerHeight;
for (let i = 0; i < this.#viewerAssets.length; i++) {
const position = getPosition(geometry, i);
this.#viewerAssets[i].position = position;
}
}
get viewerAssets(): ViewerAsset[] {
return this.#viewerAssets;
}
get hasNextPage() {
return this.#nextPage !== null;
}
findAssetAbsolutePosition(assetId: string) {
const viewerAsset = this.#viewerAssets.find((viewAsset) => viewAsset.id === assetId);
if (viewerAsset) {

View File

@@ -51,7 +51,7 @@ export function calculateSegmentIntersecting(
}
/**
* Calculate intersection for viewer assets with additional parameters like header height and scroll compensation
* Calculate intersection for viewer assets with additional parameters like header height
*/
export function calculateViewerAssetIntersecting(
timelineManager: PhotostreamManager,
@@ -60,13 +60,8 @@ export function calculateViewerAssetIntersecting(
expandTop: number = INTERSECTION_EXPAND_TOP,
expandBottom: number = INTERSECTION_EXPAND_BOTTOM,
) {
const scrollCompensationHeightDelta = timelineManager.scrollCompensation?.heightDelta ?? 0;
const topWindow =
timelineManager.visibleWindow.top - timelineManager.headerHeight - expandTop + scrollCompensationHeightDelta;
const bottomWindow =
timelineManager.visibleWindow.bottom + timelineManager.headerHeight + expandBottom + scrollCompensationHeightDelta;
const topWindow = timelineManager.visibleWindow.top - timelineManager.headerHeight - expandTop;
const bottomWindow = timelineManager.visibleWindow.bottom + timelineManager.headerHeight + expandBottom;
const positionBottom = positionTop + positionHeight;
return isIntersecting(positionTop, positionBottom, topWindow, bottomWindow);

View File

@@ -34,7 +34,7 @@ export function layoutMonthGroup(timelineManager: TimelineManager, month: MonthG
let dayGroupRow = 0;
let dayGroupCol = 0;
const options = timelineManager.createLayoutOptions();
const options = timelineManager.layoutOptions;
for (const dayGroup of month.dayGroups) {
dayGroup.layout(options, noDefer);

View File

@@ -73,6 +73,10 @@ export class MonthGroup extends PhotostreamSegment {
return loadFromTimeBuckets(this.timelineManager, this, this.timelineManager.options, signal);
}
layout(noDefer?: boolean) {
layoutMonthGroup(this.timelineManager, this, noDefer);
}
get lastDayGroup() {
return this.dayGroups.at(-1);
}
@@ -306,10 +310,6 @@ export class MonthGroup extends PhotostreamSegment {
this.loader?.cancel();
}
layout(noDefer?: boolean) {
layoutMonthGroup(this.timelineManager, this, noDefer);
}
#clearDeferredLayout() {
const hasDeferred = this.dayGroups.some((group) => group.deferredLayout);
if (hasDeferred) {

View File

@@ -1,4 +1,6 @@
import { sdkMock } from '$lib/__mocks__/sdk.mock';
import type { PhotostreamSegment } from '$lib/managers/photostream-manager/PhotostreamSegment.svelte';
import { setTestHook } from '$lib/managers/photostream-manager/TestHooks.svelte';
import {
findMonthGroupForAsset,
getMonthGroupByDate,
@@ -7,6 +9,7 @@ import { AbortError } from '$lib/utils';
import { fromISODateTimeUTCToObject, getSegmentIdentifier } from '$lib/utils/timeline-util';
import { type AssetResponseDto, type TimeBucketAssetResponseDto } from '@immich/sdk';
import { timelineAssetFactory, toResponseDto } from '@test-data/factories/asset-factory';
import type { MockedFunction } from 'vitest';
import { TimelineManager } from './timeline-manager.svelte';
import type { TimelineAsset } from './types';
@@ -57,8 +60,16 @@ describe('TimelineManager', () => {
Object.entries(bucketAssets).map(([key, assets]) => [key, toResponseDto(...assets)]),
);
const spys: { segment: PhotostreamSegment; cancelSpy: MockedFunction<() => void> }[] = [];
beforeEach(async () => {
timelineManager = new TimelineManager();
setTestHook({
hookSegment: (segment) => {
spys.push({ segment, cancelSpy: vi.spyOn(segment, 'cancel') as MockedFunction<() => void> });
},
});
sdkMock.getTimeBuckets.mockResolvedValue([
{ count: 1, timeBucket: '2024-03-01' },
{ count: 100, timeBucket: '2024-02-01' },
@@ -71,7 +82,7 @@ describe('TimelineManager', () => {
it('should load months in viewport', () => {
expect(sdkMock.getTimeBuckets).toBeCalledTimes(1);
expect(sdkMock.getTimeBucket).toHaveBeenCalledTimes(2);
expect(spys[2].cancelSpy).toHaveBeenCalled();
});
it('calculates month height', () => {
@@ -85,13 +96,13 @@ describe('TimelineManager', () => {
expect.arrayContaining([
expect.objectContaining({ year: 2024, month: 3, height: 165.5 }),
expect.objectContaining({ year: 2024, month: 2, height: 11_996 }),
expect.objectContaining({ year: 2024, month: 1, height: 286 }),
expect.objectContaining({ year: 2024, month: 1, height: 48 }),
]),
);
});
it('calculates timeline height', () => {
expect(timelineManager.timelineHeight).toBe(12_447.5);
expect(timelineManager.timelineHeight).toBe(12_209.5);
});
});