refactor(web): asset grid stores (#3464)

* Refactor asset grid stores

* Iterate over buckets with for..of loop

* Rebase on top of main branch changes
This commit is contained in:
Sergey Kondrikov
2023-08-01 04:27:56 +03:00
committed by GitHub
parent 13051c1e5a
commit 5f9dfa9493
15 changed files with 330 additions and 265 deletions

View File

@@ -1,49 +1,68 @@
import { AssetGridState, BucketPosition } from '$lib/models/asset-grid-state';
import { api, AssetResponseDto } from '@api';
import { derived, writable } from 'svelte/store';
import { assetGridState, assetStore } from './assets.store';
import type { AssetResponseDto } from '../../api/open-api';
// Asset Viewer
export const viewingAssetStoreState = writable<AssetResponseDto>();
export const isViewingAssetStoreState = writable<boolean>(false);
export interface AssetInteractionStore {
addAssetToMultiselectGroup: (asset: AssetResponseDto) => void;
removeAssetFromMultiselectGroup: (asset: AssetResponseDto) => void;
addGroupToMultiselectGroup: (group: string) => void;
removeGroupFromMultiselectGroup: (group: string) => void;
setAssetSelectionCandidates: (assets: AssetResponseDto[]) => void;
clearAssetSelectionCandidates: () => void;
setAssetSelectionStart: (asset: AssetResponseDto | null) => void;
clearMultiselect: () => void;
isMultiSelectState: {
subscribe: (run: (value: boolean) => void, invalidate?: (value?: boolean) => void) => () => void;
};
assetsInAlbumState: {
subscribe: (
run: (value: AssetResponseDto[]) => void,
invalidate?: (value?: AssetResponseDto[]) => void,
) => () => void;
set: (value: AssetResponseDto[]) => void;
};
selectedAssets: {
subscribe: (
run: (value: Set<AssetResponseDto>) => void,
invalidate?: (value?: Set<AssetResponseDto>) => void,
) => () => void;
};
selectedGroup: {
subscribe: (run: (value: Set<string>) => void, invalidate?: (value?: Set<string>) => void) => () => void;
};
assetSelectionCandidates: {
subscribe: (
run: (value: Set<AssetResponseDto>) => void,
invalidate?: (value?: Set<AssetResponseDto>) => void,
) => () => void;
};
assetSelectionStart: {
subscribe: (
run: (value: AssetResponseDto | null) => void,
invalidate?: (value?: AssetResponseDto | null) => void,
) => () => void;
};
}
/**
* Multi-selection mode
*/
export const assetsInAlbumStoreState = writable<AssetResponseDto[]>([]);
// Selected assets
export const selectedAssets = writable<Set<AssetResponseDto>>(new Set());
// Selected date groups
export const selectedGroup = writable<Set<string>>(new Set());
// If any asset selected
export const isMultiSelectStoreState = derived(selectedAssets, ($selectedAssets) => $selectedAssets.size > 0);
/**
* Range selection
*/
// Candidates for the range selection. This set includes only loaded assets, so it improves highlight
// performance. From the user's perspective, range is highlighted almost immediately
export const assetSelectionCandidates = writable<Set<AssetResponseDto>>(new Set());
// The beginning of the selection range
export const assetSelectionStart = writable<AssetResponseDto | null>(null);
function createAssetInteractionStore() {
let _assetGridState = new AssetGridState();
let _viewingAssetStoreState: AssetResponseDto;
export function createAssetInteractionStore(): AssetInteractionStore {
let _selectedAssets: Set<AssetResponseDto>;
let _selectedGroup: Set<string>;
let _assetsInAlbums: AssetResponseDto[];
let _assetSelectionCandidates: Set<AssetResponseDto>;
let _assetSelectionStart: AssetResponseDto | null;
// Subscriber
assetGridState.subscribe((state) => {
_assetGridState = state;
});
const assetsInAlbumStoreState = writable<AssetResponseDto[]>([]);
// Selected assets
const selectedAssets = writable<Set<AssetResponseDto>>(new Set());
// Selected date groups
const selectedGroup = writable<Set<string>>(new Set());
// If any asset selected
const isMultiSelectStoreState = derived(selectedAssets, ($selectedAssets) => $selectedAssets.size > 0);
viewingAssetStoreState.subscribe((asset) => {
_viewingAssetStoreState = asset;
});
// Candidates for the range selection. This set includes only loaded assets, so it improves highlight
// performance. From the user's perspective, range is highlighted almost immediately
const assetSelectionCandidates = writable<Set<AssetResponseDto>>(new Set());
// The beginning of the selection range
const assetSelectionStart = writable<AssetResponseDto | null>(null);
selectedAssets.subscribe((assets) => {
_selectedAssets = assets;
@@ -64,89 +83,7 @@ function createAssetInteractionStore() {
assetSelectionStart.subscribe((asset) => {
_assetSelectionStart = asset;
});
// Methods
/**
* Asset Viewer
*/
const setViewingAsset = async (asset: AssetResponseDto) => {
setViewingAssetId(asset.id);
};
const setViewingAssetId = async (id: string) => {
const { data } = await api.assetApi.getAssetById({ id });
viewingAssetStoreState.set(data);
isViewingAssetStoreState.set(true);
};
const setIsViewingAsset = (isViewing: boolean) => {
isViewingAssetStoreState.set(isViewing);
};
const getNextAsset = async (currentBucketIndex: number, assetId: string): Promise<AssetResponseDto | null> => {
const currentBucket = _assetGridState.buckets[currentBucketIndex];
const assetIndex = currentBucket.assets.findIndex(({ id }) => id == assetId);
if (assetIndex === -1) {
return null;
}
if (assetIndex + 1 < currentBucket.assets.length) {
return currentBucket.assets[assetIndex + 1];
}
const nextBucketIndex = currentBucketIndex + 1;
if (nextBucketIndex >= _assetGridState.buckets.length) {
return null;
}
const nextBucket = _assetGridState.buckets[nextBucketIndex];
await assetStore.getAssetsByBucket(nextBucket.bucketDate, BucketPosition.Unknown);
return nextBucket.assets[0] ?? null;
};
const getPrevAsset = async (currentBucketIndex: number, assetId: string): Promise<AssetResponseDto | null> => {
const currentBucket = _assetGridState.buckets[currentBucketIndex];
const assetIndex = currentBucket.assets.findIndex(({ id }) => id == assetId);
if (assetIndex === -1) {
return null;
}
if (assetIndex > 0) {
return currentBucket.assets[assetIndex - 1];
}
const prevBucketIndex = currentBucketIndex - 1;
if (prevBucketIndex < 0) {
return null;
}
const prevBucket = _assetGridState.buckets[prevBucketIndex];
await assetStore.getAssetsByBucket(prevBucket.bucketDate, BucketPosition.Unknown);
return prevBucket.assets[prevBucket.assets.length - 1] ?? null;
};
const navigateAsset = async (direction: 'next' | 'previous') => {
const currentAssetId = _viewingAssetStoreState.id;
const currentBucketIndex = _assetGridState.loadedAssets[currentAssetId];
if (currentBucketIndex < 0 || currentBucketIndex >= _assetGridState.buckets.length) {
return;
}
const asset =
direction === 'next'
? await getNextAsset(currentBucketIndex, currentAssetId)
: await getPrevAsset(currentBucketIndex, currentAssetId);
if (asset) {
setViewingAsset(asset);
}
};
/**
* Multiselect
*/
const addAssetToMultiselectGroup = (asset: AssetResponseDto) => {
// Not select if in album already
if (_assetsInAlbums.find((a) => a.id === asset.id)) {
@@ -205,10 +142,6 @@ function createAssetInteractionStore() {
};
return {
setViewingAsset,
setViewingAssetId,
setIsViewingAsset,
navigateAsset,
addAssetToMultiselectGroup,
removeAssetFromMultiselectGroup,
addGroupToMultiselectGroup,
@@ -217,7 +150,24 @@ function createAssetInteractionStore() {
clearAssetSelectionCandidates,
setAssetSelectionStart,
clearMultiselect,
isMultiSelectState: {
subscribe: isMultiSelectStoreState.subscribe,
},
assetsInAlbumState: {
subscribe: assetsInAlbumStoreState.subscribe,
set: assetsInAlbumStoreState.set,
},
selectedAssets: {
subscribe: selectedAssets.subscribe,
},
selectedGroup: {
subscribe: selectedGroup.subscribe,
},
assetSelectionCandidates: {
subscribe: assetSelectionCandidates.subscribe,
},
assetSelectionStart: {
subscribe: assetSelectionStart.subscribe,
},
};
}
export const assetInteractionStore = createAssetInteractionStore();

View File

@@ -0,0 +1,31 @@
import { writable } from 'svelte/store';
import { api, type AssetResponseDto } from '@api';
function createAssetViewingStore() {
const viewingAssetStoreState = writable<AssetResponseDto>();
const viewState = writable<boolean>(false);
const setAssetId = async (id: string) => {
const { data } = await api.assetApi.getAssetById({ id });
viewingAssetStoreState.set(data);
viewState.set(true);
};
const showAssetViewer = (show: boolean) => {
viewState.set(show);
};
return {
asset: {
subscribe: viewingAssetStoreState.subscribe,
},
isViewing: {
subscribe: viewState.subscribe,
set: viewState.set,
},
setAssetId,
showAssetViewer,
};
}
export const assetViewingStore = createAssetViewingStore();

View File

@@ -1,25 +1,34 @@
import { AssetGridState, BucketPosition } from '$lib/models/asset-grid-state';
import { api, AssetCountByTimeBucketResponseDto } from '@api';
import { api, AssetCountByTimeBucketResponseDto, AssetResponseDto } from '@api';
import { writable } from 'svelte/store';
/**
* The state that holds information about the asset grid
*/
export const assetGridState = writable<AssetGridState>(new AssetGridState());
export const loadingBucketState = writable<{ [key: string]: boolean }>({});
export interface AssetStore {
setInitialState: (
viewportHeight: number,
viewportWidth: number,
data: AssetCountByTimeBucketResponseDto,
userId: string | undefined,
) => void;
getAssetsByBucket: (bucket: string, position: BucketPosition) => Promise<void>;
updateBucketHeight: (bucket: string, actualBucketHeight: number) => number;
cancelBucketRequest: (token: AbortController, bucketDate: string) => Promise<void>;
getAdjacentAsset: (assetId: string, direction: 'next' | 'previous') => Promise<string | null>;
removeAsset: (assetId: string) => void;
updateAsset: (assetId: string, isFavorite: boolean) => void;
subscribe: (run: (value: AssetGridState) => void, invalidate?: (value?: AssetGridState) => void) => () => void;
}
function createAssetStore() {
export function createAssetStore(): AssetStore {
let _loadingBuckets: { [key: string]: boolean } = {};
let _assetGridState = new AssetGridState();
assetGridState.subscribe((state) => {
const { subscribe, set, update } = writable(new AssetGridState());
subscribe((state) => {
_assetGridState = state;
});
let _loadingBucketState: { [key: string]: boolean } = {};
loadingBucketState.subscribe((state) => {
_loadingBucketState = state;
});
const estimateViewportHeight = (assetCount: number, viewportWidth: number): number => {
const _estimateViewportHeight = (assetCount: number, viewportWidth: number): number => {
// Ideally we would use the average aspect ratio for the photoset, however assume
// a normal landscape aspect ratio of 3:2, then discount for the likelihood we
// will be scaling down and coalescing.
@@ -39,25 +48,19 @@ function createAssetStore() {
);
};
/**
* Set initial state
* @param viewportHeight
* @param viewportWidth
* @param data
*/
const setInitialState = (
viewportHeight: number,
viewportWidth: number,
data: AssetCountByTimeBucketResponseDto,
userId: string | undefined,
) => {
assetGridState.set({
set({
viewportHeight,
viewportWidth,
timelineHeight: 0,
buckets: data.buckets.map((bucket) => ({
bucketDate: bucket.timeBucket,
bucketHeight: estimateViewportHeight(bucket.count, viewportWidth),
bucketHeight: _estimateViewportHeight(bucket.count, viewportWidth),
assets: [],
cancelToken: new AbortController(),
position: BucketPosition.Unknown,
@@ -67,8 +70,7 @@ function createAssetStore() {
userId,
});
// Update timeline height based on calculated bucket height
assetGridState.update((state) => {
update((state) => {
state.timelineHeight = state.buckets.reduce((acc, b) => acc + b.bucketHeight, 0);
return state;
});
@@ -78,7 +80,7 @@ function createAssetStore() {
try {
const currentBucketData = _assetGridState.buckets.find((b) => b.bucketDate === bucket);
if (currentBucketData?.assets && currentBucketData.assets.length > 0) {
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.bucketDate === bucket);
state.buckets[bucketIndex].position = position;
return state;
@@ -86,10 +88,7 @@ function createAssetStore() {
return;
}
loadingBucketState.set({
..._loadingBucketState,
[bucket]: true,
});
_loadingBuckets = { ..._loadingBuckets, [bucket]: true };
const { data: assets } = await api.assetApi.getAssetByTimeBucket(
{
getAssetByTimeBucketDto: {
@@ -100,13 +99,9 @@ function createAssetStore() {
},
{ signal: currentBucketData?.cancelToken.signal },
);
loadingBucketState.set({
..._loadingBucketState,
[bucket]: false,
});
_loadingBuckets = { ..._loadingBuckets, [bucket]: false };
// Update assetGridState with assets by time bucket
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.bucketDate === bucket);
state.buckets[bucketIndex].assets = assets;
state.buckets[bucketIndex].position = position;
@@ -125,7 +120,7 @@ function createAssetStore() {
};
const removeAsset = (assetId: string) => {
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.assets.some((a) => a.id === assetId));
const assetIndex = state.buckets[bucketIndex].assets.findIndex((a) => a.id === assetId);
state.buckets[bucketIndex].assets.splice(assetIndex, 1);
@@ -140,7 +135,7 @@ function createAssetStore() {
};
const _removeBucket = (bucketDate: string) => {
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.bucketDate === bucketDate);
state.buckets.splice(bucketIndex, 1);
state.assets = state.buckets.flatMap((b) => b.assets);
@@ -153,7 +148,7 @@ function createAssetStore() {
let scrollTimeline = false;
let heightDelta = 0;
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.bucketDate === bucket);
// Update timeline height based on the new bucket height
const estimateBucketHeight = state.buckets[bucketIndex].bucketHeight;
@@ -177,9 +172,13 @@ function createAssetStore() {
};
const cancelBucketRequest = async (token: AbortController, bucketDate: string) => {
if (!_loadingBuckets[bucketDate]) {
return;
}
token.abort();
// set new abort controller for bucket
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.bucketDate === bucketDate);
state.buckets[bucketIndex].cancelToken = new AbortController();
return state;
@@ -187,7 +186,7 @@ function createAssetStore() {
};
const updateAsset = (assetId: string, isFavorite: boolean) => {
assetGridState.update((state) => {
update((state) => {
const bucketIndex = state.buckets.findIndex((b) => b.assets.some((a) => a.id === assetId));
const assetIndex = state.buckets[bucketIndex].assets.findIndex((a) => a.id === assetId);
state.buckets[bucketIndex].assets[assetIndex].isFavorite = isFavorite;
@@ -198,14 +197,72 @@ function createAssetStore() {
});
};
const _getNextAsset = async (currentBucketIndex: number, assetId: string): Promise<AssetResponseDto | null> => {
const currentBucket = _assetGridState.buckets[currentBucketIndex];
const assetIndex = currentBucket.assets.findIndex(({ id }) => id == assetId);
if (assetIndex === -1) {
return null;
}
if (assetIndex + 1 < currentBucket.assets.length) {
return currentBucket.assets[assetIndex + 1];
}
const nextBucketIndex = currentBucketIndex + 1;
if (nextBucketIndex >= _assetGridState.buckets.length) {
return null;
}
const nextBucket = _assetGridState.buckets[nextBucketIndex];
await getAssetsByBucket(nextBucket.bucketDate, BucketPosition.Unknown);
return nextBucket.assets[0] ?? null;
};
const _getPrevAsset = async (currentBucketIndex: number, assetId: string): Promise<AssetResponseDto | null> => {
const currentBucket = _assetGridState.buckets[currentBucketIndex];
const assetIndex = currentBucket.assets.findIndex(({ id }) => id == assetId);
if (assetIndex === -1) {
return null;
}
if (assetIndex > 0) {
return currentBucket.assets[assetIndex - 1];
}
const prevBucketIndex = currentBucketIndex - 1;
if (prevBucketIndex < 0) {
return null;
}
const prevBucket = _assetGridState.buckets[prevBucketIndex];
await getAssetsByBucket(prevBucket.bucketDate, BucketPosition.Unknown);
return prevBucket.assets[prevBucket.assets.length - 1] ?? null;
};
const getAdjacentAsset = async (assetId: string, direction: 'next' | 'previous'): Promise<string | null> => {
const currentBucketIndex = _assetGridState.loadedAssets[assetId];
if (currentBucketIndex < 0 || currentBucketIndex >= _assetGridState.buckets.length) {
return null;
}
const asset =
direction === 'next'
? await _getNextAsset(currentBucketIndex, assetId)
: await _getPrevAsset(currentBucketIndex, assetId);
return asset?.id ?? null;
};
return {
setInitialState,
getAssetsByBucket,
removeAsset,
updateBucketHeight,
cancelBucketRequest,
getAdjacentAsset,
updateAsset,
subscribe,
};
}
export const assetStore = createAssetStore();