Move scroll memory into reusable action.

This commit is contained in:
Calum Dingwall 2024-09-04 15:25:16 -05:00
parent 8bf733ac57
commit c6a682e41e
7 changed files with 232 additions and 103 deletions

View File

@ -0,0 +1,87 @@
import { navigating } from '$app/stores';
import { AppRoute, SessionStorageKey } from '$lib/constants';
import { handlePromiseError } from '$lib/utils';
interface Options {
/**
* {@link AppRoute} for subpages that scroll state should be kept while visiting.
*
* This must be kept the same in all subpages of this route for the scroll memory clearer to work.
*/
routeStartsWith: AppRoute;
/**
* Function to clear additional data/state before scrolling (ex infinite scroll).
*/
beforeClear?: () => void;
}
interface PageOptions extends Options {
/**
* Function to save additional data/state before scrolling (ex infinite scroll).
*/
beforeSave?: () => void;
/**
* Function to load additional data/state before scrolling (ex infinite scroll).
*/
beforeScroll?: () => Promise<void>;
}
/**
* @param node The scroll slot element, typically from {@link UserPageLayout}
*/
export function scrollMemory(
node: HTMLElement,
{ routeStartsWith, beforeSave, beforeClear, beforeScroll }: PageOptions,
) {
const unsubscribeNavigating = navigating.subscribe((navigation) => {
const existingScroll = sessionStorage.getItem(SessionStorageKey.SCROLL_POSITION);
if (navigation?.to && !existingScroll) {
// Save current scroll information when going into a subpage.
if (navigation.to.url.pathname.startsWith(routeStartsWith)) {
beforeSave?.();
sessionStorage.setItem(SessionStorageKey.SCROLL_POSITION, node.scrollTop.toString());
} else {
beforeClear?.();
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
}
});
handlePromiseError(
(async () => {
await beforeScroll?.();
const newScroll = sessionStorage.getItem(SessionStorageKey.SCROLL_POSITION);
if (newScroll) {
node.scroll({
top: Number.parseFloat(newScroll),
behavior: 'instant',
});
}
beforeClear?.();
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
})(),
);
return {
destroy() {
unsubscribeNavigating();
},
};
}
export function scrollMemoryClearer(_node: HTMLElement, { routeStartsWith, beforeClear }: Options) {
const unsubscribeNavigating = navigating.subscribe((navigation) => {
// Forget scroll position from main page if going somewhere else.
if (navigation?.to && !navigation?.to.url.pathname.startsWith(routeStartsWith)) {
beforeClear?.();
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
});
return {
destroy() {
unsubscribeNavigating();
},
};
}

View File

@ -0,0 +1,67 @@
/**
* @license Apache-2.0
* https://github.com/hperrin/svelte-material-ui/blob/master/packages/common/src/internal/useActions.ts
*/
export type SvelteActionReturnType<P> = {
update?: (newParams?: P) => void;
destroy?: () => void;
} | void;
export type SvelteHTMLActionType<P> = (node: HTMLElement, params?: P) => SvelteActionReturnType<P>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type HTMLActionEntry<P = any> = SvelteHTMLActionType<P> | [SvelteHTMLActionType<P>, P];
export type HTMLActionArray = HTMLActionEntry[];
export type SvelteSVGActionType<P> = (node: SVGElement, params?: P) => SvelteActionReturnType<P>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type SVGActionEntry<P = any> = SvelteSVGActionType<P> | [SvelteSVGActionType<P>, P];
export type SVGActionArray = SVGActionEntry[];
export type ActionArray = HTMLActionArray | SVGActionArray;
export function useActions(node: HTMLElement | SVGElement, actions: ActionArray) {
const actionReturns: SvelteActionReturnType<unknown>[] = [];
if (actions) {
for (const actionEntry of actions) {
const action = Array.isArray(actionEntry) ? actionEntry[0] : actionEntry;
if (Array.isArray(actionEntry) && actionEntry.length > 1) {
actionReturns.push(action(node as HTMLElement & SVGElement, actionEntry[1]));
} else {
actionReturns.push(action(node as HTMLElement & SVGElement));
}
}
}
return {
update(actions: ActionArray) {
if ((actions?.length || 0) != actionReturns.length) {
throw new Error('You must not change the length of an actions array.');
}
if (actions) {
for (const [i, returnEntry] of actionReturns.entries()) {
if (returnEntry && returnEntry.update) {
const actionEntry = actions[i];
if (Array.isArray(actionEntry) && actionEntry.length > 1) {
returnEntry.update(actionEntry[1]);
} else {
returnEntry.update();
}
}
}
}
},
destroy() {
for (const returnEntry of actionReturns) {
returnEntry?.destroy?.();
}
},
};
}

View File

@ -3,6 +3,7 @@
import NavigationBar from '../shared-components/navigation-bar/navigation-bar.svelte';
import SideBar from '../shared-components/side-bar/side-bar.svelte';
import AdminSideBar from '../shared-components/side-bar/admin-side-bar.svelte';
import { useActions, type ActionArray } from '$lib/actions/use-actions';
export let hideNavbar = false;
export let showUploadButton = false;
@ -10,8 +11,7 @@
export let description: string | undefined = undefined;
export let scrollbar = true;
export let admin = false;
export let scrollSlot: HTMLDivElement | undefined = undefined;
export let use: ActionArray = [];
$: scrollbarClass = scrollbar ? 'immich-scrollbar p-2 pb-8' : 'scrollbar-hidden';
$: hasTitleClass = title ? 'top-16 h-[calc(100%-theme(spacing.16))]' : 'top-0 h-full';
@ -55,10 +55,7 @@
</div>
{/if}
<div
class="{scrollbarClass} scrollbar-stable absolute {hasTitleClass} w-full overflow-y-auto"
bind:this={scrollSlot}
>
<div class="{scrollbarClass} scrollbar-stable absolute {hasTitleClass} w-full overflow-y-auto" use:useActions={use}>
<slot />
</div>
</section>

View File

@ -1,6 +1,6 @@
<script lang="ts">
import type { PageData } from './$types';
import { beforeNavigate } from '$app/navigation';
import { scrollMemory } from '$lib/actions/scroll-memory';
import { AlbumFilter, albumViewSettings } from '$lib/stores/preferences.store';
import { createAlbumAndRedirect } from '$lib/utils/album-utils';
import UserPageLayout from '$lib/components/layouts/user-page-layout.svelte';
@ -9,37 +9,16 @@
import EmptyPlaceholder from '$lib/components/shared-components/empty-placeholder.svelte';
import GroupTab from '$lib/components/elements/group-tab.svelte';
import SearchBar from '$lib/components/elements/search-bar.svelte';
import { AppRoute, SessionStorageKey } from '$lib/constants';
import { onMount } from 'svelte';
import { AppRoute } from '$lib/constants';
import { t } from 'svelte-i18n';
export let data: PageData;
let scrollSlot: HTMLDivElement;
beforeNavigate(({ to }) => {
// Save current scroll information when going into a person page.
if (to && to.url.pathname.startsWith(AppRoute.ALBUMS)) {
sessionStorage.setItem(SessionStorageKey.SCROLL_POSITION, scrollSlot.scrollTop.toString());
} else {
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
});
onMount(() => {
let newScroll = sessionStorage.getItem(SessionStorageKey.SCROLL_POSITION);
if (newScroll) {
scrollSlot.scroll({
top: Number.parseFloat(newScroll),
behavior: 'instant',
});
}
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
});
let searchQuery = '';
let albumGroups: string[] = [];
</script>
<UserPageLayout title={data.meta.title} bind:scrollSlot>
<UserPageLayout title={data.meta.title} use={[[scrollMemory, { routeStartsWith: AppRoute.ALBUMS }]]}>
<div class="flex place-items-center gap-2" slot="buttons">
<AlbumsControls {albumGroups} bind:searchQuery />
</div>

View File

@ -1,5 +1,6 @@
<script lang="ts">
import { afterNavigate, beforeNavigate, goto, onNavigate } from '$app/navigation';
import { afterNavigate, goto, onNavigate } from '$app/navigation';
import { scrollMemoryClearer } from '$lib/actions/scroll-memory';
import AlbumDescription from '$lib/components/album-page/album-description.svelte';
import AlbumOptions from '$lib/components/album-page/album-options.svelte';
import AlbumSummary from '$lib/components/album-page/album-summary.svelte';
@ -32,7 +33,7 @@
notificationController,
} from '$lib/components/shared-components/notification/notification';
import UserAvatar from '$lib/components/shared-components/user-avatar.svelte';
import { AppRoute, SessionStorageKey } from '$lib/constants';
import { AppRoute } from '$lib/constants';
import { numberOfComments, setNumberOfComments, updateNumberOfComments } from '$lib/stores/activity.store';
import { createAssetInteractionStore } from '$lib/stores/asset-interaction.store';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
@ -148,13 +149,6 @@
$: albumHasViewers = album.albumUsers.some(({ role }) => role === AlbumUserRole.Viewer);
beforeNavigate(({ to }) => {
// Forget scroll position from albums page if going somewhere else.
if (to && !to.url.pathname.startsWith(AppRoute.ALBUMS)) {
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
});
afterNavigate(({ from }) => {
let url: string | undefined = from?.url?.pathname;
@ -439,7 +433,11 @@
});
</script>
<div class="flex overflow-hidden" bind:clientWidth={globalWidth}>
<div
class="flex overflow-hidden"
bind:clientWidth={globalWidth}
use:scrollMemoryClearer={{ routeStartsWith: AppRoute.ALBUMS }}
>
<div class="relative w-full shrink">
{#if $isMultiSelectState}
<AssetSelectControlBar assets={$selectedAssets} clearSelect={() => assetInteractionStore.clearMultiselect()}>

View File

@ -1,7 +1,8 @@
<script lang="ts">
import { beforeNavigate, goto } from '$app/navigation';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { focusTrap } from '$lib/actions/focus-trap';
import { scrollMemory } from '$lib/actions/scroll-memory';
import Button from '$lib/components/elements/buttons/button.svelte';
import LinkButton from '$lib/components/elements/buttons/link-button.svelte';
import Icon from '$lib/components/elements/icon.svelte';
@ -51,6 +52,7 @@
let showSetBirthDateModal = false;
let showMergeModal = false;
let personName = '';
let currentPage = 1;
let nextPage = data.people.hasNextPage ? 2 : null;
let personMerge1: PersonResponseDto;
let personMerge2: PersonResponseDto;
@ -61,31 +63,6 @@
let changeNameInputEl: HTMLInputElement | null;
let innerHeight: number;
let scrollSlot: HTMLDivElement;
beforeNavigate(({ to }) => {
// Save current scroll information when going into a person page.
if (to && to.url.pathname.startsWith(AppRoute.PEOPLE)) {
if (nextPage) {
sessionStorage.setItem(SessionStorageKey.INFINITE_SCROLL_PAGE, nextPage.toString());
}
sessionStorage.setItem(SessionStorageKey.SCROLL_POSITION, scrollSlot.scrollTop.toString());
} else {
sessionStorage.removeItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
});
const restoreScrollPosition = () => {
let newScroll = sessionStorage.getItem(SessionStorageKey.SCROLL_POSITION);
if (newScroll) {
scrollSlot.scroll({
top: Number.parseFloat(newScroll),
behavior: 'instant',
});
}
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
};
onMount(() => {
const getSearchedPeople = $page.url.searchParams.get(QueryParameter.SEARCHED_PEOPLE);
if (getSearchedPeople) {
@ -93,6 +70,20 @@
handlePromiseError(handleSearchPeople(true, searchName));
}
return websocketEvents.on('on_person_thumbnail', (personId: string) => {
for (const person of people) {
if (person.id === personId) {
person.updatedAt = new Date().toISOString();
}
}
// trigger reactivity
people = people;
});
});
const loadInitialScroll = () =>
new Promise<void>((resolve) => {
// Load up to previously loaded page when returning.
let newNextPage = sessionStorage.getItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
if (newNextPage && nextPage) {
@ -109,26 +100,16 @@
for (const page of pages) {
people = people.concat(page.people);
}
currentPage = startingPage + pagesToLoad - 1;
nextPage = pages.at(-1)?.hasNextPage ? startingPage + pagesToLoad : null;
restoreScrollPosition(); // wait until extra pages are loaded
resolve(); // wait until extra pages are loaded
}),
);
} else {
restoreScrollPosition();
resolve();
}
sessionStorage.removeItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
}
return websocketEvents.on('on_person_thumbnail', (personId: string) => {
for (const person of people) {
if (person.id === personId) {
person.updatedAt = new Date().toISOString();
}
}
// trigger reactivity
people = people;
});
});
const loadNextPage = async () => {
@ -139,6 +120,9 @@
try {
const { people: newPeople, hasNextPage } = await getAllPeople({ withHidden: true, page: nextPage });
people = people.concat(newPeople);
if (nextPage !== null) {
currentPage = nextPage;
}
nextPage = hasNextPage ? nextPage + 1 : null;
} catch (error) {
handleError(error, $t('errors.failed_to_load_people'));
@ -363,7 +347,23 @@
<UserPageLayout
title={$t('people')}
description={countVisiblePeople === 0 && !searchName ? undefined : `(${countVisiblePeople.toLocaleString($locale)})`}
bind:scrollSlot
use={[
[
scrollMemory,
{
routeStartsWith: AppRoute.PEOPLE,
beforeSave: () => {
if (currentPage) {
sessionStorage.setItem(SessionStorageKey.INFINITE_SCROLL_PAGE, currentPage.toString());
}
},
beforeClear: () => {
sessionStorage.removeItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
},
beforeLoad: loadInitialScroll,
},
],
]}
>
<svelte:fragment slot="buttons">
{#if people.length > 0}

View File

@ -1,6 +1,7 @@
<script lang="ts">
import { afterNavigate, beforeNavigate, goto } from '$app/navigation';
import { afterNavigate, goto } from '$app/navigation';
import { page } from '$app/stores';
import { scrollMemoryClearer } from '$lib/actions/scroll-memory';
import ImageThumbnail from '$lib/components/assets/thumbnail/image-thumbnail.svelte';
import EditNameInput from '$lib/components/faces-page/edit-name-input.svelte';
import MergeFaceSelector from '$lib/components/faces-page/merge-face-selector.svelte';
@ -126,14 +127,6 @@
});
});
beforeNavigate(({ to }) => {
// Forget scroll position from people page if going somewhere else.
if (to && !to.url.pathname.startsWith(AppRoute.PEOPLE)) {
sessionStorage.removeItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
sessionStorage.removeItem(SessionStorageKey.SCROLL_POSITION);
}
});
const handleEscape = async () => {
if ($showAssetViewer || viewMode === ViewMode.SUGGEST_MERGE) {
return;
@ -452,7 +445,15 @@
{/if}
</header>
<main class="relative h-screen overflow-hidden bg-immich-bg tall:ml-4 pt-[var(--navbar-height)] dark:bg-immich-dark-bg">
<main
class="relative h-screen overflow-hidden bg-immich-bg tall:ml-4 pt-[var(--navbar-height)] dark:bg-immich-dark-bg"
use:scrollMemoryClearer={{
routeStartsWith: AppRoute.PEOPLE,
beforeClear: () => {
sessionStorage.removeItem(SessionStorageKey.INFINITE_SCROLL_PAGE);
},
}}
>
{#key refreshAssetGrid}
<AssetGrid
enableRouting={true}