Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add panzoom to image viewer #56

Merged
merged 5 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@commitlint/cli": "19.7.1",
"@commitlint/config-conventional": "19.7.1",
"@mozilla/readability": "0.5.0",
"@panzoom/panzoom": "^4.6.0",
"@playwright/test": "1.50.1",
"@semantic-release/git": "10.0.1",
"@skeletonlabs/floating-ui-svelte": "0.3.9",
Expand Down
158 changes: 109 additions & 49 deletions src/lib/components/news/story/content/StoryImageViewer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import XIcon from '$lib/components/shared/icons/outline/XIcon.svelte';
import type { StoryImage } from '$lib/models/story';
import { onDestroy, onMount } from 'svelte';

import type { PanzoomObject } from '@panzoom/panzoom';
import { Panzoom } from '$lib/utils/panzoomModule';
import { isMacOsPlatform, isTouchDevice } from '$lib/utils/support';
interface Props {
image: StoryImage;
images?: Array<StoryImage>;
Expand All @@ -13,22 +15,25 @@

let { image = $bindable(), images = [], onClose }: Props = $props();

const backropClass = 'flex justify-center items-center fixed top-0 bottom-0 left-0 right-0 z-50 bg-black';
const containerClass = 'flex justify-center items-center relative w-full h-full';
const imageContainerClass = '';
const imageClass = 'w-auto h-auto max-w-full max-h-screen bg-gray-100 dark:bg-gray-300 shadow-2xl';
const viewerButtonCircleClass =
'flex justify-center items-center w-12 h-12 md:w-16 md:h-16 text-gray-200 bg-gray-500/30 active:bg-gray-500/90 backdrop-blur-sm rounded-full transition-all ease-out';
const viewerButtonIconClass = 'w-8 h-8';

let showControls = $state(true);
let closeButtonRef: HTMLButtonElement | undefined = $state();
let oldOverflowValue: string | undefined;
let oldActiveElement: Element | null;
let imageRef = $state<HTMLImageElement | undefined>();
let panzoom: PanzoomObject | undefined;
let prevPanzoomPosition: { x: number; y: number } | undefined;
let prevPanzoomZoom: number | undefined;

let isNavigationEnabled = $derived(images.length > 1);
let viewerButtonClass = $derived(`${showControls ? 'visible' : 'invisible'}`);

const containerClass = 'flex justify-center items-center fixed top-0 bottom-0 left-0 right-0 z-50';
const imageContainerClass = 'w-full h-full bg-black';
const imageClass = 'object-scale-down w-full h-full bg-transparent';
const viewerButtonCircleClass =
'relative z-10 flex justify-center items-center w-12 h-12 md:w-16 md:h-16 text-gray-200 bg-gray-500/30 active:bg-gray-500/90 backdrop-blur-sm rounded-full transition-all ease-out';
const viewerButtonIconClass = 'w-8 h-8';

onMount(() => {
oldOverflowValue = document.documentElement.style.overflow;
document.documentElement.style.overflow = 'hidden';
Expand All @@ -45,13 +50,36 @@
}
});

$effect(() => {
if (imageRef) {
setupPanzoom(imageRef);
}
});

$effect(() => {
if (image) {
resetPanzoom();
}
});

function handleCloseButtonClick(event: Event): void {
event.stopPropagation();
closeViewer();
}

function handleBackdropClick(): void {
toggleControls();
function handleContainerPointerDown(): void {
prevPanzoomPosition = panzoom?.getPan();
prevPanzoomZoom = panzoom?.getScale();
}

function handleContainerClick(): void {
const { x: prevX, y: prevY } = prevPanzoomPosition ?? {};
const { x: currX, y: currY } = panzoom?.getPan() ?? {};
const currZoom = panzoom?.getScale();

if (deltaCompare(prevX, currX) && deltaCompare(prevY, currY) && deltaCompare(prevPanzoomZoom, currZoom)) {
toggleControls();
}
}

function handleKeyDown(event: KeyboardEvent): void {
Expand Down Expand Up @@ -107,51 +135,83 @@
image = prev;
}
}

async function setupPanzoom(imageRef: HTMLImageElement): Promise<void> {
const isTouch = isTouchDevice();
const isMacOs = isMacOsPlatform();

try {
panzoom = (await Panzoom.module)(imageRef, {
minScale: 1,
maxScale: 10,
step: isTouch ? 1 : isMacOs ? 0.075 : 0.5,
contain: 'outside',
handleStartEvent: (event: Event) => {
event.preventDefault();
},
});
imageRef.addEventListener('wheel', panzoom.zoomWithWheel);
} catch (error) {
console.error('Failed to setup panzoom!', error);
}
}

function resetPanzoom(): void {
if (panzoom) {
panzoom.reset({ animate: false });
}
}

function deltaCompare(a: number | undefined, b: number | undefined, delta = 0.01): boolean {
if (a === undefined || b === undefined) {
return false;
}

return Math.abs(a - b) < delta;
}
</script>

<svelte:document onkeydown={handleKeyDown} />

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<div class={backropClass} role="region" onclick={handleBackdropClick}>
<div class={containerClass}>
<button
class="viewer-button !top-2 right-2 {viewerButtonClass}"
title="Bild schließen"
bind:this={closeButtonRef}
onclick={handleCloseButtonClick}
>
<span class={viewerButtonCircleClass}>
<XIcon class={viewerButtonIconClass} />
</span>
</button>
{#if isNavigationEnabled}
{#if prevImage(image)}
<button
class="viewer-button left-2 {viewerButtonClass}"
title="Vorheriges Bild anzeigen"
onclick={handlePrevImageClick}
>
<span class={viewerButtonCircleClass}>
<ChevronLeftIcon class={viewerButtonIconClass} />
</span>
</button>
{/if}
{#if nextImage(image)}
<button
class="viewer-button right-2 {viewerButtonClass}"
title="Nächstes Bild anzeigen"
onclick={handleNextImageClick}
>
<span class={viewerButtonCircleClass}>
<ChevronRightIcon class={viewerButtonIconClass} />
</span>
</button>
{/if}
<div class={containerClass} role="region" onclick={handleContainerClick} onpointerdown={handleContainerPointerDown}>
<button
class="viewer-button z-10 !top-2 right-2 {viewerButtonClass}"
title="Bild schließen"
bind:this={closeButtonRef}
onclick={handleCloseButtonClick}
>
<span class={viewerButtonCircleClass}>
<XIcon class={viewerButtonIconClass} />
</span>
</button>
{#if isNavigationEnabled}
{#if prevImage(image)}
<button
class="viewer-button z-10 left-2 {viewerButtonClass}"
title="Vorheriges Bild anzeigen"
onclick={handlePrevImageClick}
>
<span class={viewerButtonCircleClass}>
<ChevronLeftIcon class={viewerButtonIconClass} />
</span>
</button>
{/if}
{#if nextImage(image)}
<button
class="viewer-button z-10 right-2 {viewerButtonClass}"
title="Nächstes Bild anzeigen"
onclick={handleNextImageClick}
>
<span class={viewerButtonCircleClass}>
<ChevronRightIcon class={viewerButtonIconClass} />
</span>
</button>
{/if}
<div class={imageContainerClass}>
<img class={imageClass} src={image.src} srcset={image.srcset} alt={image.alt} />
</div>
{/if}
<div class={imageContainerClass}>
<img class={imageClass} src={image.src} srcset={image.srcset} alt={image.alt} bind:this={imageRef} />
</div>
</div>

Expand Down
2 changes: 1 addition & 1 deletion src/lib/stores/runes/audio.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { browser } from '$app/environment';
import type { Story } from '$lib/models/story';
import { isMediaSessionAvailable } from '$lib/utils/web-api-support';
import { isMediaSessionAvailable } from '$lib/utils/support';
import EasySpeech from 'easy-speech';
import settings from '../settings';

Expand Down
18 changes: 18 additions & 0 deletions src/lib/utils/dynamicModuleLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function dynamicModuleLoader<T>(importFn: () => Promise<T>): { module: Promise<T> } {
let cache: Promise<T> | undefined;
return new Proxy(
{},
{
get(_target, prop) {
if (prop === 'module') {
if (!cache) {
cache = importFn();
}
return cache;
}

return undefined;
},
},
) as { module: Promise<T> };
}
3 changes: 3 additions & 0 deletions src/lib/utils/panzoomModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { dynamicModuleLoader } from './dynamicModuleLoader';

export const Panzoom = dynamicModuleLoader(() => import('@panzoom/panzoom').then((module) => module.default));
22 changes: 22 additions & 0 deletions src/lib/utils/support.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { browser } from '$app/environment';

export function isMediaSessionAvailable(): boolean {
return browser && 'MediaSession' in window;
}

export function isTouchDevice(): boolean {
return browser && 'matchMedia' in window && window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
}

export function isMacOsPlatform(): boolean {
return (
browser &&
'userAgentData' in window.navigator &&
!!window.navigator.userAgentData &&
typeof window.navigator.userAgentData === 'object' &&
'platform' in window.navigator.userAgentData &&
!!window.navigator.userAgentData.platform &&
typeof window.navigator.userAgentData.platform === 'string' &&
/^mac\s*os(?:x)?$/i.test(window.navigator.userAgentData.platform)
);
}
5 changes: 0 additions & 5 deletions src/lib/utils/web-api-support.ts

This file was deleted.