mirror of
https://github.com/immich-app/immich.git
synced 2026-05-18 03:10:24 +03:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fe63b70a6 |
@@ -1,13 +1,14 @@
|
|||||||
import { AssetMediaResponseDto, LoginResponseDto } from '@immich/sdk';
|
import { AssetMediaResponseDto, LoginResponseDto } from '@immich/sdk';
|
||||||
import { expect, test } from '@playwright/test';
|
import { Page, expect, test } from '@playwright/test';
|
||||||
import type { Socket } from 'socket.io-client';
|
|
||||||
import { utils } from 'src/utils';
|
import { utils } from 'src/utils';
|
||||||
|
|
||||||
|
function imageLocator(page: Page) {
|
||||||
|
return page.getByAltText('Image taken').locator('visible=true');
|
||||||
|
}
|
||||||
test.describe('Photo Viewer', () => {
|
test.describe('Photo Viewer', () => {
|
||||||
let admin: LoginResponseDto;
|
let admin: LoginResponseDto;
|
||||||
let asset: AssetMediaResponseDto;
|
let asset: AssetMediaResponseDto;
|
||||||
let rawAsset: AssetMediaResponseDto;
|
let rawAsset: AssetMediaResponseDto;
|
||||||
let websocket: Socket;
|
|
||||||
|
|
||||||
test.beforeAll(async () => {
|
test.beforeAll(async () => {
|
||||||
utils.initSdk();
|
utils.initSdk();
|
||||||
@@ -15,11 +16,6 @@ test.describe('Photo Viewer', () => {
|
|||||||
admin = await utils.adminSetup();
|
admin = await utils.adminSetup();
|
||||||
asset = await utils.createAsset(admin.accessToken);
|
asset = await utils.createAsset(admin.accessToken);
|
||||||
rawAsset = await utils.createAsset(admin.accessToken, { assetData: { filename: 'test.arw' } });
|
rawAsset = await utils.createAsset(admin.accessToken, { assetData: { filename: 'test.arw' } });
|
||||||
websocket = await utils.connectWebsocket(admin.accessToken);
|
|
||||||
});
|
|
||||||
|
|
||||||
test.afterAll(() => {
|
|
||||||
utils.disconnectWebsocket(websocket);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test.beforeEach(async ({ context, page }) => {
|
test.beforeEach(async ({ context, page }) => {
|
||||||
@@ -30,51 +26,31 @@ test.describe('Photo Viewer', () => {
|
|||||||
|
|
||||||
test('loads original photo when zoomed', async ({ page }) => {
|
test('loads original photo when zoomed', async ({ page }) => {
|
||||||
await page.goto(`/photos/${asset.id}`);
|
await page.goto(`/photos/${asset.id}`);
|
||||||
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).toContain('thumbnail');
|
||||||
const preview = page.getByTestId('preview').filter({ visible: true });
|
const box = await imageLocator(page).boundingBox();
|
||||||
await expect(preview).toHaveAttribute('src', /.+/);
|
expect(box).toBeTruthy();
|
||||||
|
const { x, y, width, height } = box!;
|
||||||
const originalResponse = page.waitForResponse((response) => response.url().includes('/original'));
|
await page.mouse.move(x + width / 2, y + height / 2);
|
||||||
|
|
||||||
const { width, height } = page.viewportSize()!;
|
|
||||||
await page.mouse.move(width / 2, height / 2);
|
|
||||||
await page.mouse.wheel(0, -1);
|
await page.mouse.wheel(0, -1);
|
||||||
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).toContain('original');
|
||||||
await originalResponse;
|
|
||||||
|
|
||||||
const original = page.getByTestId('original').filter({ visible: true });
|
|
||||||
await expect(original).toHaveAttribute('src', /original/);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('loads fullsize image when zoomed and original is web-incompatible', async ({ page }) => {
|
test('loads fullsize image when zoomed and original is web-incompatible', async ({ page }) => {
|
||||||
await page.goto(`/photos/${rawAsset.id}`);
|
await page.goto(`/photos/${rawAsset.id}`);
|
||||||
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).toContain('thumbnail');
|
||||||
const preview = page.getByTestId('preview').filter({ visible: true });
|
const box = await imageLocator(page).boundingBox();
|
||||||
await expect(preview).toHaveAttribute('src', /.+/);
|
expect(box).toBeTruthy();
|
||||||
|
const { x, y, width, height } = box!;
|
||||||
const fullsizeResponse = page.waitForResponse((response) => response.url().includes('fullsize'));
|
await page.mouse.move(x + width / 2, y + height / 2);
|
||||||
|
|
||||||
const { width, height } = page.viewportSize()!;
|
|
||||||
await page.mouse.move(width / 2, height / 2);
|
|
||||||
await page.mouse.wheel(0, -1);
|
await page.mouse.wheel(0, -1);
|
||||||
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).toContain('fullsize');
|
||||||
await fullsizeResponse;
|
|
||||||
|
|
||||||
const original = page.getByTestId('original').filter({ visible: true });
|
|
||||||
await expect(original).toHaveAttribute('src', /fullsize/);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('reloads photo when checksum changes', async ({ page }) => {
|
test('reloads photo when checksum changes', async ({ page }) => {
|
||||||
await page.goto(`/photos/${asset.id}`);
|
await page.goto(`/photos/${asset.id}`);
|
||||||
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).toContain('thumbnail');
|
||||||
const preview = page.getByTestId('preview').filter({ visible: true });
|
const initialSrc = await imageLocator(page).getAttribute('src');
|
||||||
await expect(preview).toHaveAttribute('src', /.+/);
|
|
||||||
const initialSrc = await preview.getAttribute('src');
|
|
||||||
|
|
||||||
const websocketEvent = utils.waitForWebsocketEvent({ event: 'assetUpdate', id: asset.id });
|
|
||||||
await utils.replaceAsset(admin.accessToken, asset.id);
|
await utils.replaceAsset(admin.accessToken, asset.id);
|
||||||
await websocketEvent;
|
await expect.poll(async () => await imageLocator(page).getAttribute('src')).not.toBe(initialSrc);
|
||||||
|
|
||||||
await expect(preview).not.toHaveAttribute('src', initialSrc!);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -99,13 +99,13 @@ export const setupTimelineMockApiRoutes = async (
|
|||||||
});
|
});
|
||||||
|
|
||||||
await context.route('**/api/assets/*/thumbnail?size=*', async (route, request) => {
|
await context.route('**/api/assets/*/thumbnail?size=*', async (route, request) => {
|
||||||
const pattern = /\/api\/assets\/(?<assetId>[^/]+)\/thumbnail\?size=(?<size>preview|thumbnail|fullsize)/;
|
const pattern = /\/api\/assets\/(?<assetId>[^/]+)\/thumbnail\?size=(?<size>preview|thumbnail)/;
|
||||||
const match = request.url().match(pattern);
|
const match = request.url().match(pattern);
|
||||||
if (!match?.groups) {
|
if (!match?.groups) {
|
||||||
throw new Error(`Invalid URL for thumbnail endpoint: ${request.url()}`);
|
throw new Error(`Invalid URL for thumbnail endpoint: ${request.url()}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (match.groups.size === 'preview' || match.groups.size === 'fullsize') {
|
if (match.groups.size === 'preview') {
|
||||||
if (!route.request().serviceWorker()) {
|
if (!route.request().serviceWorker()) {
|
||||||
return route.continue();
|
return route.continue();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ test.describe('broken-asset responsiveness', () => {
|
|||||||
await page.goto(`/photos/${fixture.primaryAsset.id}`);
|
await page.goto(`/photos/${fixture.primaryAsset.id}`);
|
||||||
await page.waitForSelector('#immich-asset-viewer');
|
await page.waitForSelector('#immich-asset-viewer');
|
||||||
|
|
||||||
const viewerBrokenAsset = page.locator('[data-viewer-content] [data-broken-asset]').first();
|
const viewerBrokenAsset = page.locator('#immich-asset-viewer #broken-asset [data-broken-asset]');
|
||||||
await expect(viewerBrokenAsset).toBeVisible();
|
await expect(viewerBrokenAsset).toBeVisible();
|
||||||
|
|
||||||
await expect(viewerBrokenAsset.locator('svg')).toBeVisible();
|
await expect(viewerBrokenAsset.locator('svg')).toBeVisible();
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import {
|
|||||||
generateTimelineData,
|
generateTimelineData,
|
||||||
TimelineAssetConfig,
|
TimelineAssetConfig,
|
||||||
TimelineData,
|
TimelineData,
|
||||||
toAssetResponseDto,
|
|
||||||
} from 'src/ui/generators/timeline';
|
} from 'src/ui/generators/timeline';
|
||||||
import { setupBaseMockApiRoutes } from 'src/ui/mock-network/base-network';
|
import { setupBaseMockApiRoutes } from 'src/ui/mock-network/base-network';
|
||||||
import { setupTimelineMockApiRoutes, TimelineTestContext } from 'src/ui/mock-network/timeline-network';
|
import { setupTimelineMockApiRoutes, TimelineTestContext } from 'src/ui/mock-network/timeline-network';
|
||||||
@@ -54,7 +53,7 @@ test.describe('search gallery-viewer', () => {
|
|||||||
assets: {
|
assets: {
|
||||||
total: searchAssets.length,
|
total: searchAssets.length,
|
||||||
count: searchAssets.length,
|
count: searchAssets.length,
|
||||||
items: searchAssets.map((asset) => toAssetResponseDto(asset)),
|
items: searchAssets,
|
||||||
facets: [],
|
facets: [],
|
||||||
nextPage: null,
|
nextPage: null,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -163,11 +163,13 @@ export const assetViewerUtils = {
|
|||||||
return page.locator('#immich-asset-viewer');
|
return page.locator('#immich-asset-viewer');
|
||||||
},
|
},
|
||||||
async waitForViewerLoad(page: Page, asset: TimelineAssetConfig) {
|
async waitForViewerLoad(page: Page, asset: TimelineAssetConfig) {
|
||||||
const previewUrl = `/api/assets/${asset.id}/thumbnail?size=preview&c=${asset.thumbhash}&edited=true`;
|
|
||||||
await page
|
await page
|
||||||
.getByTestId('preview')
|
.locator(
|
||||||
.and(page.locator(`[src="${previewUrl}"]`))
|
`img[draggable="false"][src="/api/assets/${asset.id}/thumbnail?size=preview&c=${asset.thumbhash}&edited=true"]`,
|
||||||
.or(page.locator(`video[poster="${previewUrl}"]`))
|
)
|
||||||
|
.or(
|
||||||
|
page.locator(`video[poster="/api/assets/${asset.id}/thumbnail?size=preview&c=${asset.thumbhash}&edited=true"]`),
|
||||||
|
)
|
||||||
.waitFor();
|
.waitFor();
|
||||||
},
|
},
|
||||||
async expectActiveAssetToBe(page: Page, assetId: string) {
|
async expectActiveAssetToBe(page: Page, assetId: string) {
|
||||||
@@ -213,9 +215,8 @@ export const pageUtils = {
|
|||||||
await page.getByText('Confirm').click();
|
await page.getByText('Confirm').click();
|
||||||
},
|
},
|
||||||
async selectDay(page: Page, day: string) {
|
async selectDay(page: Page, day: string) {
|
||||||
const section = page.getByTitle(day).locator('xpath=ancestor::section[@data-group]');
|
await page.getByTitle(day).hover();
|
||||||
await section.hover();
|
await page.locator('[data-group] .w-8').click();
|
||||||
await section.locator('.w-8').click();
|
|
||||||
},
|
},
|
||||||
async pauseTestDebug() {
|
async pauseTestDebug() {
|
||||||
console.log('NOTE: pausing test indefinately for debug');
|
console.log('NOTE: pausing test indefinately for debug');
|
||||||
|
|||||||
+8
-19
@@ -177,6 +177,7 @@ export const utils = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
resetDatabase: async (tables?: string[]) => {
|
resetDatabase: async (tables?: string[]) => {
|
||||||
|
try {
|
||||||
client = await utils.connectDatabase();
|
client = await utils.connectDatabase();
|
||||||
|
|
||||||
tables = tables || [
|
tables = tables || [
|
||||||
@@ -196,33 +197,21 @@ export const utils = {
|
|||||||
'tag',
|
'tag',
|
||||||
];
|
];
|
||||||
|
|
||||||
const truncateTables = tables.filter((table) => table !== 'system_metadata');
|
|
||||||
const sql: string[] = [];
|
const sql: string[] = [];
|
||||||
|
|
||||||
if (truncateTables.length > 0) {
|
for (const table of tables) {
|
||||||
sql.push(`TRUNCATE "${truncateTables.join('", "')}" CASCADE;`);
|
if (table === 'system_metadata') {
|
||||||
}
|
|
||||||
|
|
||||||
if (tables.includes('system_metadata')) {
|
|
||||||
sql.push(`DELETE FROM "system_metadata" where "key" NOT IN ('reverse-geocoding-state', 'system-flags');`);
|
sql.push(`DELETE FROM "system_metadata" where "key" NOT IN ('reverse-geocoding-state', 'system-flags');`);
|
||||||
|
} else {
|
||||||
|
sql.push(`DELETE FROM "${table}" CASCADE;`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = sql.join('\n');
|
await client.query(sql.join('\n'));
|
||||||
const maxRetries = 3;
|
} catch (error) {
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
||||||
try {
|
|
||||||
await client.query(query);
|
|
||||||
return;
|
|
||||||
} catch (error: any) {
|
|
||||||
if (error?.code === '40P01' && attempt < maxRetries) {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
console.error('Failed to reset database', error);
|
console.error('Failed to reset database', error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
unzip: async (input: string, output: string) => {
|
unzip: async (input: string, output: string) => {
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
import { cancelImageUrl } from '$lib/utils/sw-messaging';
|
|
||||||
|
|
||||||
export function loadImage(src: string, onLoad: () => void, onError: () => void, onStart?: () => void) {
|
|
||||||
let destroyed = false;
|
|
||||||
|
|
||||||
const handleLoad = () => !destroyed && onLoad();
|
|
||||||
const handleError = () => !destroyed && onError();
|
|
||||||
|
|
||||||
const img = document.createElement('img');
|
|
||||||
img.addEventListener('load', handleLoad);
|
|
||||||
img.addEventListener('error', handleError);
|
|
||||||
|
|
||||||
onStart?.();
|
|
||||||
img.src = src;
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
destroyed = true;
|
|
||||||
img.removeEventListener('load', handleLoad);
|
|
||||||
img.removeEventListener('error', handleError);
|
|
||||||
cancelImageUrl(src);
|
|
||||||
img.remove();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export type LoadImageFunction = typeof loadImage;
|
|
||||||
@@ -1,41 +1,35 @@
|
|||||||
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
||||||
import { createZoomImageWheel } from '@zoom-image/core';
|
import { createZoomImageWheel } from '@zoom-image/core';
|
||||||
|
|
||||||
export const zoomImageAction = (node: HTMLElement, options?: { disabled?: boolean; zoomTarget?: HTMLElement }) => {
|
export const zoomImageAction = (node: HTMLElement, options?: { disabled?: boolean }) => {
|
||||||
const zoomInstance = createZoomImageWheel(node, {
|
const zoomInstance = createZoomImageWheel(node, { maxZoom: 10, initialState: assetViewerManager.zoomState });
|
||||||
maxZoom: 10,
|
|
||||||
initialState: assetViewerManager.zoomState,
|
|
||||||
zoomTarget: options?.zoomTarget,
|
|
||||||
});
|
|
||||||
|
|
||||||
const unsubscribes = [
|
const unsubscribes = [
|
||||||
assetViewerManager.on({ ZoomChange: (state) => zoomInstance.setState(state) }),
|
assetViewerManager.on({ ZoomChange: (state) => zoomInstance.setState(state) }),
|
||||||
zoomInstance.subscribe(({ state }) => assetViewerManager.onZoomChange(state)),
|
zoomInstance.subscribe(({ state }) => assetViewerManager.onZoomChange(state)),
|
||||||
];
|
];
|
||||||
|
|
||||||
const stopIfDisabled = (event: Event) => {
|
const onInteractionStart = (event: Event) => {
|
||||||
if (options?.disabled) {
|
if (options?.disabled) {
|
||||||
event.stopImmediatePropagation();
|
event.stopImmediatePropagation();
|
||||||
}
|
}
|
||||||
|
assetViewerManager.cancelZoomAnimation();
|
||||||
};
|
};
|
||||||
|
|
||||||
node.addEventListener('wheel', stopIfDisabled, { capture: true });
|
node.addEventListener('wheel', onInteractionStart, { capture: true });
|
||||||
node.addEventListener('pointerdown', stopIfDisabled, { capture: true });
|
node.addEventListener('pointerdown', onInteractionStart, { capture: true });
|
||||||
|
|
||||||
node.style.overflow = 'visible';
|
node.style.overflow = 'visible';
|
||||||
return {
|
return {
|
||||||
update(newOptions?: { disabled?: boolean; zoomTarget?: HTMLElement }) {
|
update(newOptions?: { disabled?: boolean }) {
|
||||||
options = newOptions;
|
options = newOptions;
|
||||||
if (newOptions?.zoomTarget !== undefined) {
|
|
||||||
zoomInstance.setState({ zoomTarget: newOptions.zoomTarget });
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
destroy() {
|
destroy() {
|
||||||
for (const unsubscribe of unsubscribes) {
|
for (const unsubscribe of unsubscribes) {
|
||||||
unsubscribe();
|
unsubscribe();
|
||||||
}
|
}
|
||||||
node.removeEventListener('wheel', stopIfDisabled, { capture: true });
|
node.removeEventListener('wheel', onInteractionStart, { capture: true });
|
||||||
node.removeEventListener('pointerdown', stopIfDisabled, { capture: true });
|
node.removeEventListener('pointerdown', onInteractionStart, { capture: true });
|
||||||
zoomInstance.cleanup();
|
zoomInstance.cleanup();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,210 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { thumbhash } from '$lib/actions/thumbhash';
|
|
||||||
import AlphaBackground from '$lib/components/AlphaBackground.svelte';
|
|
||||||
import BrokenAsset from '$lib/components/assets/broken-asset.svelte';
|
|
||||||
import DelayedLoadingSpinner from '$lib/components/DelayedLoadingSpinner.svelte';
|
|
||||||
import ImageLayer from '$lib/components/ImageLayer.svelte';
|
|
||||||
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
|
||||||
import { getAssetUrls } from '$lib/utils';
|
|
||||||
import { AdaptiveImageLoader, type QualityList } from '$lib/utils/adaptive-image-loader.svelte';
|
|
||||||
import { scaleToCover, scaleToFit } from '$lib/utils/container-utils';
|
|
||||||
import { getAltText } from '$lib/utils/thumbnail-util';
|
|
||||||
import { toTimelineAsset } from '$lib/utils/timeline-util';
|
|
||||||
import type { AssetResponseDto, SharedLinkResponseDto } from '@immich/sdk';
|
|
||||||
import { untrack, type Snippet } from 'svelte';
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
asset: AssetResponseDto;
|
|
||||||
sharedLink?: SharedLinkResponseDto;
|
|
||||||
objectFit?: 'contain' | 'cover';
|
|
||||||
container: {
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
};
|
|
||||||
onUrlChange?: (url: string) => void;
|
|
||||||
onImageReady?: () => void;
|
|
||||||
onError?: () => void;
|
|
||||||
ref?: HTMLDivElement;
|
|
||||||
imgRef?: HTMLImageElement;
|
|
||||||
backdrop?: Snippet;
|
|
||||||
overlays?: Snippet;
|
|
||||||
};
|
|
||||||
|
|
||||||
let {
|
|
||||||
ref = $bindable(),
|
|
||||||
// eslint-disable-next-line no-useless-assignment
|
|
||||||
imgRef = $bindable(),
|
|
||||||
asset,
|
|
||||||
sharedLink,
|
|
||||||
objectFit = 'contain',
|
|
||||||
container,
|
|
||||||
onUrlChange,
|
|
||||||
onImageReady,
|
|
||||||
onError,
|
|
||||||
backdrop,
|
|
||||||
overlays,
|
|
||||||
}: Props = $props();
|
|
||||||
|
|
||||||
const afterThumbnail = (loader: AdaptiveImageLoader) => {
|
|
||||||
if (assetViewerManager.zoom > 1) {
|
|
||||||
loader.trigger('original');
|
|
||||||
} else {
|
|
||||||
loader.trigger('preview');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildQualityList = () => {
|
|
||||||
const assetUrls = getAssetUrls(asset, sharedLink);
|
|
||||||
const qualityList: QualityList = [
|
|
||||||
{
|
|
||||||
quality: 'thumbnail',
|
|
||||||
url: assetUrls.thumbnail,
|
|
||||||
onAfterLoad: afterThumbnail,
|
|
||||||
onAfterError: afterThumbnail,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
quality: 'preview',
|
|
||||||
url: assetUrls.preview,
|
|
||||||
onAfterError: (loader) => loader.trigger('original'),
|
|
||||||
},
|
|
||||||
{ quality: 'original', url: assetUrls.original },
|
|
||||||
];
|
|
||||||
return qualityList;
|
|
||||||
};
|
|
||||||
|
|
||||||
const loaderKey = $derived(`${asset.id}:${asset.thumbhash}:${sharedLink?.id}`);
|
|
||||||
|
|
||||||
const adaptiveImageLoader = $derived.by(() => {
|
|
||||||
void loaderKey;
|
|
||||||
|
|
||||||
return untrack(
|
|
||||||
() =>
|
|
||||||
new AdaptiveImageLoader(buildQualityList(), {
|
|
||||||
onImageReady,
|
|
||||||
onError,
|
|
||||||
onUrlChange,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
$effect.pre(() => {
|
|
||||||
const loader = adaptiveImageLoader;
|
|
||||||
untrack(() => assetViewerManager.resetZoomState());
|
|
||||||
return () => loader.destroy();
|
|
||||||
});
|
|
||||||
|
|
||||||
const imageDimensions = $derived.by(() => {
|
|
||||||
const { width, height } = asset;
|
|
||||||
if (width && width > 0 && height && height > 0) {
|
|
||||||
return { width, height };
|
|
||||||
}
|
|
||||||
return { width: 1, height: 1 };
|
|
||||||
});
|
|
||||||
|
|
||||||
const { width, height, left, top } = $derived.by(() => {
|
|
||||||
const scaleFn = objectFit === 'cover' ? scaleToCover : scaleToFit;
|
|
||||||
const { width, height } = scaleFn(imageDimensions, container);
|
|
||||||
return {
|
|
||||||
width: width + 'px',
|
|
||||||
height: height + 'px',
|
|
||||||
left: (container.width - width) / 2 + 'px',
|
|
||||||
top: (container.height - height) / 2 + 'px',
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const { status } = $derived(adaptiveImageLoader);
|
|
||||||
const alt = $derived(status.urls.preview ? $getAltText(toTimelineAsset(asset)) : '');
|
|
||||||
|
|
||||||
const show = $derived.by(() => {
|
|
||||||
const { quality, started, hasError, urls } = status;
|
|
||||||
return {
|
|
||||||
alphaBackground: !hasError && started,
|
|
||||||
spinner: !asset.thumbhash && !started,
|
|
||||||
brokenAsset: hasError,
|
|
||||||
thumbhash: quality.thumbnail !== 'success' && quality.preview !== 'success' && quality.original !== 'success',
|
|
||||||
thumbnail: quality.thumbnail !== 'error' && quality.preview !== 'success' && quality.original !== 'success',
|
|
||||||
preview: quality.preview !== 'error' && quality.original !== 'success',
|
|
||||||
original: quality.original !== 'error' && urls.original !== undefined,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (assetViewerManager.zoom > 1 && status.quality.original !== 'success') {
|
|
||||||
untrack(() => void adaptiveImageLoader.trigger('original'));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let thumbnailElement = $state<HTMLImageElement>();
|
|
||||||
let previewElement = $state<HTMLImageElement>();
|
|
||||||
let originalElement = $state<HTMLImageElement>();
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
const quality = status.quality;
|
|
||||||
imgRef =
|
|
||||||
(quality.original === 'success' ? originalElement : undefined) ??
|
|
||||||
(quality.preview === 'success' ? previewElement : undefined) ??
|
|
||||||
(quality.thumbnail === 'success' ? thumbnailElement : undefined);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="relative h-full w-full overflow-hidden will-change-transform" bind:this={ref}>
|
|
||||||
{@render backdrop?.()}
|
|
||||||
|
|
||||||
<div class="absolute" style:left style:top style:width style:height>
|
|
||||||
{#if show.alphaBackground}
|
|
||||||
<AlphaBackground />
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if show.thumbhash}
|
|
||||||
{#if asset.thumbhash}
|
|
||||||
<!-- Thumbhash / spinner layer -->
|
|
||||||
<canvas use:thumbhash={{ base64ThumbHash: asset.thumbhash }} class="h-full w-full absolute"></canvas>
|
|
||||||
{:else if show.spinner}
|
|
||||||
<DelayedLoadingSpinner />
|
|
||||||
{/if}
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if show.thumbnail}
|
|
||||||
<ImageLayer
|
|
||||||
{adaptiveImageLoader}
|
|
||||||
{width}
|
|
||||||
{height}
|
|
||||||
quality="thumbnail"
|
|
||||||
src={status.urls.thumbnail}
|
|
||||||
alt=""
|
|
||||||
role="presentation"
|
|
||||||
bind:ref={thumbnailElement}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if show.brokenAsset}
|
|
||||||
<BrokenAsset class="text-xl h-full w-full absolute" />
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if show.preview}
|
|
||||||
<ImageLayer
|
|
||||||
{adaptiveImageLoader}
|
|
||||||
{alt}
|
|
||||||
{width}
|
|
||||||
{height}
|
|
||||||
{overlays}
|
|
||||||
quality="preview"
|
|
||||||
src={status.urls.preview}
|
|
||||||
bind:ref={previewElement}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if show.original}
|
|
||||||
<ImageLayer
|
|
||||||
{adaptiveImageLoader}
|
|
||||||
{alt}
|
|
||||||
{width}
|
|
||||||
{height}
|
|
||||||
{overlays}
|
|
||||||
quality="original"
|
|
||||||
src={status.urls.original}
|
|
||||||
bind:ref={originalElement}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import type { ClassValue } from 'svelte/elements';
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
class?: ClassValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { class: className = '' }: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="absolute h-full w-full bg-gray-300 dark:bg-gray-700 {className}"></div>
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { LoadingSpinner } from '@immich/ui';
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="delayed-spinner absolute flex h-full items-center justify-center">
|
|
||||||
<LoadingSpinner />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
@keyframes delayedVisibility {
|
|
||||||
to {
|
|
||||||
visibility: visible;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.delayed-spinner {
|
|
||||||
visibility: hidden;
|
|
||||||
animation: 0s linear 0.4s forwards delayedVisibility;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import Image from '$lib/components/Image.svelte';
|
|
||||||
import type { AdaptiveImageLoader, ImageQuality } from '$lib/utils/adaptive-image-loader.svelte';
|
|
||||||
import type { Snippet } from 'svelte';
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
adaptiveImageLoader: AdaptiveImageLoader;
|
|
||||||
quality: ImageQuality;
|
|
||||||
src: string | undefined;
|
|
||||||
alt?: string;
|
|
||||||
role?: string;
|
|
||||||
ref?: HTMLImageElement;
|
|
||||||
width: string;
|
|
||||||
height: string;
|
|
||||||
overlays?: Snippet;
|
|
||||||
};
|
|
||||||
|
|
||||||
let {
|
|
||||||
adaptiveImageLoader,
|
|
||||||
quality,
|
|
||||||
src,
|
|
||||||
alt = '',
|
|
||||||
role,
|
|
||||||
ref = $bindable(),
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
overlays,
|
|
||||||
}: Props = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#key adaptiveImageLoader}
|
|
||||||
<div class="absolute top-0" style:width style:height>
|
|
||||||
<Image
|
|
||||||
{src}
|
|
||||||
onStart={() => adaptiveImageLoader.onStart(quality)}
|
|
||||||
onLoad={() => adaptiveImageLoader.onLoad(quality)}
|
|
||||||
onError={() => adaptiveImageLoader.onError(quality)}
|
|
||||||
bind:ref
|
|
||||||
class="h-full w-full"
|
|
||||||
{alt}
|
|
||||||
{role}
|
|
||||||
draggable={false}
|
|
||||||
data-testid={quality}
|
|
||||||
/>
|
|
||||||
{@render overlays?.()}
|
|
||||||
</div>
|
|
||||||
{/key}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
import { loadImage } from '$lib/actions/image-loader.svelte';
|
|
||||||
import { getAssetUrls } from '$lib/utils';
|
|
||||||
import { AdaptiveImageLoader, type QualityList } from '$lib/utils/adaptive-image-loader.svelte';
|
|
||||||
import type { AssetResponseDto } from '@immich/sdk';
|
|
||||||
|
|
||||||
type AssetCursor = {
|
|
||||||
current: AssetResponseDto;
|
|
||||||
nextAsset?: AssetResponseDto;
|
|
||||||
previousAsset?: AssetResponseDto;
|
|
||||||
};
|
|
||||||
|
|
||||||
export class PreloadManager {
|
|
||||||
private nextPreloader: AdaptiveImageLoader | undefined;
|
|
||||||
private previousPreloader: AdaptiveImageLoader | undefined;
|
|
||||||
|
|
||||||
private startPreloader(asset: AssetResponseDto | undefined): AdaptiveImageLoader | undefined {
|
|
||||||
if (!asset) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const urls = getAssetUrls(asset);
|
|
||||||
const afterThumbnail = (loader: AdaptiveImageLoader) => loader.trigger('preview');
|
|
||||||
const qualityList: QualityList = [
|
|
||||||
{
|
|
||||||
quality: 'thumbnail',
|
|
||||||
url: urls.thumbnail,
|
|
||||||
onAfterLoad: afterThumbnail,
|
|
||||||
onAfterError: afterThumbnail,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
quality: 'preview',
|
|
||||||
url: urls.preview,
|
|
||||||
onAfterError: (loader) => loader.trigger('original'),
|
|
||||||
},
|
|
||||||
{ quality: 'original', url: urls.original },
|
|
||||||
];
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList, undefined, loadImage);
|
|
||||||
loader.start();
|
|
||||||
return loader;
|
|
||||||
}
|
|
||||||
|
|
||||||
private destroyPreviousPreloader() {
|
|
||||||
this.previousPreloader?.destroy();
|
|
||||||
this.previousPreloader = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
private destroyNextPreloader() {
|
|
||||||
this.nextPreloader?.destroy();
|
|
||||||
this.nextPreloader = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
cancelBeforeNavigation(direction: 'previous' | 'next') {
|
|
||||||
switch (direction) {
|
|
||||||
case 'next': {
|
|
||||||
this.destroyPreviousPreloader();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'previous': {
|
|
||||||
this.destroyNextPreloader();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateAfterNavigation(oldCursor: AssetCursor, newCursor: AssetCursor) {
|
|
||||||
const movedForward = newCursor.current.id === oldCursor.nextAsset?.id;
|
|
||||||
const movedBackward = newCursor.current.id === oldCursor.previousAsset?.id;
|
|
||||||
|
|
||||||
if (!movedBackward) {
|
|
||||||
this.destroyPreviousPreloader();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!movedForward) {
|
|
||||||
this.destroyNextPreloader();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (movedForward) {
|
|
||||||
this.nextPreloader = this.startPreloader(newCursor.nextAsset);
|
|
||||||
} else if (movedBackward) {
|
|
||||||
this.previousPreloader = this.startPreloader(newCursor.previousAsset);
|
|
||||||
} else {
|
|
||||||
this.previousPreloader = this.startPreloader(newCursor.previousAsset);
|
|
||||||
this.nextPreloader = this.startPreloader(newCursor.nextAsset);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
initializePreloads(cursor: AssetCursor) {
|
|
||||||
if (cursor.nextAsset) {
|
|
||||||
this.nextPreloader = this.startPreloader(cursor.nextAsset);
|
|
||||||
}
|
|
||||||
if (cursor.previousAsset) {
|
|
||||||
this.previousPreloader = this.startPreloader(cursor.previousAsset);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy() {
|
|
||||||
this.destroyNextPreloader();
|
|
||||||
this.destroyPreviousPreloader();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const preloadManager = new PreloadManager();
|
|
||||||
@@ -5,17 +5,15 @@
|
|||||||
import NextAssetAction from '$lib/components/asset-viewer/actions/next-asset-action.svelte';
|
import NextAssetAction from '$lib/components/asset-viewer/actions/next-asset-action.svelte';
|
||||||
import PreviousAssetAction from '$lib/components/asset-viewer/actions/previous-asset-action.svelte';
|
import PreviousAssetAction from '$lib/components/asset-viewer/actions/previous-asset-action.svelte';
|
||||||
import AssetViewerNavBar from '$lib/components/asset-viewer/asset-viewer-nav-bar.svelte';
|
import AssetViewerNavBar from '$lib/components/asset-viewer/asset-viewer-nav-bar.svelte';
|
||||||
import { preloadManager } from '$lib/components/asset-viewer/PreloadManager.svelte';
|
|
||||||
import { AssetAction, ProjectionType } from '$lib/constants';
|
import { AssetAction, ProjectionType } from '$lib/constants';
|
||||||
import { activityManager } from '$lib/managers/activity-manager.svelte';
|
import { activityManager } from '$lib/managers/activity-manager.svelte';
|
||||||
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
||||||
import { assetCacheManager } from '$lib/managers/AssetCacheManager.svelte';
|
|
||||||
import { authManager } from '$lib/managers/auth-manager.svelte';
|
import { authManager } from '$lib/managers/auth-manager.svelte';
|
||||||
import { editManager, EditToolType } from '$lib/managers/edit/edit-manager.svelte';
|
import { editManager, EditToolType } from '$lib/managers/edit/edit-manager.svelte';
|
||||||
import { eventManager } from '$lib/managers/event-manager.svelte';
|
import { eventManager } from '$lib/managers/event-manager.svelte';
|
||||||
|
import { imageManager } from '$lib/managers/ImageManager.svelte';
|
||||||
import { getAssetActions } from '$lib/services/asset.service';
|
import { getAssetActions } from '$lib/services/asset.service';
|
||||||
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
|
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
|
||||||
import { isFaceEditMode } from '$lib/stores/face-edit.svelte';
|
|
||||||
import { ocrManager } from '$lib/stores/ocr.svelte';
|
import { ocrManager } from '$lib/stores/ocr.svelte';
|
||||||
import { alwaysLoadOriginalVideo } from '$lib/stores/preferences.store';
|
import { alwaysLoadOriginalVideo } from '$lib/stores/preferences.store';
|
||||||
import { SlideshowNavigation, SlideshowState, slideshowStore } from '$lib/stores/slideshow.store';
|
import { SlideshowNavigation, SlideshowState, slideshowStore } from '$lib/stores/slideshow.store';
|
||||||
@@ -38,7 +36,6 @@
|
|||||||
} from '@immich/sdk';
|
} from '@immich/sdk';
|
||||||
import { CommandPaletteDefaultProvider } from '@immich/ui';
|
import { CommandPaletteDefaultProvider } from '@immich/ui';
|
||||||
import { onDestroy, onMount, untrack } from 'svelte';
|
import { onDestroy, onMount, untrack } from 'svelte';
|
||||||
import type { SwipeCustomEvent } from 'svelte-gestures';
|
|
||||||
import { t } from 'svelte-i18n';
|
import { t } from 'svelte-i18n';
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition';
|
||||||
import Thumbnail from '../assets/thumbnail/thumbnail.svelte';
|
import Thumbnail from '../assets/thumbnail/thumbnail.svelte';
|
||||||
@@ -47,7 +44,6 @@
|
|||||||
import DetailPanel from './detail-panel.svelte';
|
import DetailPanel from './detail-panel.svelte';
|
||||||
import EditorPanel from './editor/editor-panel.svelte';
|
import EditorPanel from './editor/editor-panel.svelte';
|
||||||
import CropArea from './editor/transform-tool/crop-area.svelte';
|
import CropArea from './editor/transform-tool/crop-area.svelte';
|
||||||
import FaceEditor from './face-editor/face-editor.svelte';
|
|
||||||
import ImagePanoramaViewer from './image-panorama-viewer.svelte';
|
import ImagePanoramaViewer from './image-panorama-viewer.svelte';
|
||||||
import OcrButton from './ocr-button.svelte';
|
import OcrButton from './ocr-button.svelte';
|
||||||
import PhotoViewer from './photo-viewer.svelte';
|
import PhotoViewer from './photo-viewer.svelte';
|
||||||
@@ -96,20 +92,20 @@
|
|||||||
stopProgress: stopSlideshowProgress,
|
stopProgress: stopSlideshowProgress,
|
||||||
slideshowNavigation,
|
slideshowNavigation,
|
||||||
slideshowState,
|
slideshowState,
|
||||||
|
slideshowTransition,
|
||||||
slideshowRepeat,
|
slideshowRepeat,
|
||||||
} = slideshowStore;
|
} = slideshowStore;
|
||||||
const stackThumbnailSize = 60;
|
const stackThumbnailSize = 60;
|
||||||
const stackSelectedThumbnailSize = 65;
|
const stackSelectedThumbnailSize = 65;
|
||||||
|
|
||||||
let stack: StackResponseDto | undefined = $state();
|
const asset = $derived(cursor.current);
|
||||||
let selectedStackAsset: AssetResponseDto | undefined = $state();
|
|
||||||
let previewStackedAsset: AssetResponseDto | undefined = $state();
|
|
||||||
|
|
||||||
const asset = $derived(previewStackedAsset ?? selectedStackAsset ?? cursor.current);
|
|
||||||
const nextAsset = $derived(cursor.nextAsset);
|
const nextAsset = $derived(cursor.nextAsset);
|
||||||
const previousAsset = $derived(cursor.previousAsset);
|
const previousAsset = $derived(cursor.previousAsset);
|
||||||
let sharedLink = getSharedLink();
|
let sharedLink = getSharedLink();
|
||||||
|
let previewStackedAsset: AssetResponseDto | undefined = $state();
|
||||||
let fullscreenElement = $state<Element>();
|
let fullscreenElement = $state<Element>();
|
||||||
|
let unsubscribes: (() => void)[] = [];
|
||||||
|
let stack: StackResponseDto | null = $state(null);
|
||||||
|
|
||||||
let playOriginalVideo = $state($alwaysLoadOriginalVideo);
|
let playOriginalVideo = $state($alwaysLoadOriginalVideo);
|
||||||
let slideshowStartAssetId = $state<string>();
|
let slideshowStartAssetId = $state<string>();
|
||||||
@@ -118,43 +114,38 @@
|
|||||||
playOriginalVideo = value;
|
playOriginalVideo = value;
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectStackedAsset = async (id: string) => {
|
|
||||||
selectedStackAsset = await assetCacheManager.getAsset({ id });
|
|
||||||
};
|
|
||||||
|
|
||||||
const refreshStack = async () => {
|
const refreshStack = async () => {
|
||||||
if (authManager.isSharedLink || !withStacked) {
|
if (authManager.isSharedLink) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!cursor.current.stack) {
|
if (asset.stack) {
|
||||||
stack = undefined;
|
stack = await getStack({ id: asset.stack.id });
|
||||||
selectedStackAsset = undefined;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stack = await getStack({ id: cursor.current.stack.id });
|
if (!stack?.assets.some(({ id }) => id === asset.id)) {
|
||||||
const primaryAsset = stack?.assets.find(({ id }) => id === stack?.primaryAssetId);
|
stack = null;
|
||||||
if (primaryAsset) {
|
|
||||||
await selectStackedAsset(primaryAsset.id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
untrack(() => {
|
||||||
|
imageManager.preload(stack?.assets[1]);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleFavorite = async () => {
|
const handleFavorite = async () => {
|
||||||
if (!album || !album.isActivityEnabled) {
|
if (album && album.isActivityEnabled) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await activityManager.toggleLike();
|
await activityManager.toggleLike();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
handleError(error, $t('errors.unable_to_change_favorite'));
|
handleError(error, $t('errors.unable_to_change_favorite'));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
syncAssetViewerOpenClass(true);
|
syncAssetViewerOpenClass(true);
|
||||||
const slideshowStateUnsubscribe = slideshowState.subscribe((value) => {
|
unsubscribes.push(
|
||||||
|
slideshowState.subscribe((value) => {
|
||||||
if (value === SlideshowState.PlaySlideshow) {
|
if (value === SlideshowState.PlaySlideshow) {
|
||||||
slideshowHistory.reset();
|
slideshowHistory.reset();
|
||||||
slideshowHistory.queue(toTimelineAsset(asset));
|
slideshowHistory.queue(toTimelineAsset(asset));
|
||||||
@@ -162,53 +153,42 @@
|
|||||||
} else if (value === SlideshowState.StopSlideshow) {
|
} else if (value === SlideshowState.StopSlideshow) {
|
||||||
handlePromiseError(handleStopSlideshow());
|
handlePromiseError(handleStopSlideshow());
|
||||||
}
|
}
|
||||||
});
|
}),
|
||||||
|
slideshowNavigation.subscribe((value) => {
|
||||||
const slideshowNavigationUnsubscribe = slideshowNavigation.subscribe((value) => {
|
|
||||||
if (value === SlideshowNavigation.Shuffle) {
|
if (value === SlideshowNavigation.Shuffle) {
|
||||||
slideshowHistory.reset();
|
slideshowHistory.reset();
|
||||||
slideshowHistory.queue(toTimelineAsset(asset));
|
slideshowHistory.queue(toTimelineAsset(asset));
|
||||||
}
|
}
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
return () => {
|
|
||||||
slideshowStateUnsubscribe();
|
|
||||||
slideshowNavigationUnsubscribe();
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
|
for (const unsubscribe of unsubscribes) {
|
||||||
|
unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
activityManager.reset();
|
activityManager.reset();
|
||||||
assetViewerManager.closeEditor();
|
assetViewerManager.closeEditor();
|
||||||
syncAssetViewerOpenClass(false);
|
syncAssetViewerOpenClass(false);
|
||||||
preloadManager.destroy();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const closeViewer = () => {
|
const closeViewer = () => {
|
||||||
onClose?.(asset);
|
onClose?.(asset);
|
||||||
};
|
};
|
||||||
|
|
||||||
const refreshPreservingSelection = async () => {
|
|
||||||
const id = asset.id;
|
|
||||||
assetCacheManager.invalidateAsset(id);
|
|
||||||
if (selectedStackAsset) {
|
|
||||||
await selectStackedAsset(id);
|
|
||||||
} else {
|
|
||||||
const asset = await assetCacheManager.getAsset({ id });
|
|
||||||
assetViewingStore.setAsset(asset);
|
|
||||||
}
|
|
||||||
onAssetChange?.(asset);
|
|
||||||
};
|
|
||||||
|
|
||||||
const closeEditor = async () => {
|
const closeEditor = async () => {
|
||||||
if (editManager.hasAppliedEdits) {
|
if (editManager.hasAppliedEdits) {
|
||||||
await refreshPreservingSelection();
|
const refreshedAsset = await getAssetInfo({ id: asset.id });
|
||||||
|
onAssetChange?.(refreshedAsset);
|
||||||
|
assetViewingStore.setAsset(refreshedAsset);
|
||||||
}
|
}
|
||||||
assetViewerManager.closeEditor();
|
assetViewerManager.closeEditor();
|
||||||
};
|
};
|
||||||
|
|
||||||
const tracker = new InvocationTracker();
|
const tracker = new InvocationTracker();
|
||||||
const navigateAsset = (order?: 'previous' | 'next') => {
|
|
||||||
|
const navigateAsset = (order?: 'previous' | 'next', e?: Event) => {
|
||||||
if (!order) {
|
if (!order) {
|
||||||
if ($slideshowState === SlideshowState.PlaySlideshow) {
|
if ($slideshowState === SlideshowState.PlaySlideshow) {
|
||||||
order = $slideshowNavigation === SlideshowNavigation.AscendingOrder ? 'previous' : 'next';
|
order = $slideshowNavigation === SlideshowNavigation.AscendingOrder ? 'previous' : 'next';
|
||||||
@@ -217,19 +197,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
preloadManager.cancelBeforeNavigation(order);
|
e?.stopPropagation();
|
||||||
|
imageManager.cancel(asset);
|
||||||
if (tracker.isActive()) {
|
if (tracker.isActive()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
void tracker.invoke(async () => {
|
void tracker.invoke(async () => {
|
||||||
const isShuffle =
|
|
||||||
$slideshowState === SlideshowState.PlaySlideshow && $slideshowNavigation === SlideshowNavigation.Shuffle;
|
|
||||||
|
|
||||||
let hasNext: boolean;
|
let hasNext: boolean;
|
||||||
|
|
||||||
if (isShuffle) {
|
if ($slideshowState === SlideshowState.PlaySlideshow && $slideshowNavigation === SlideshowNavigation.Shuffle) {
|
||||||
hasNext = order === 'previous' ? slideshowHistory.previous() : slideshowHistory.next();
|
hasNext = order === 'previous' ? slideshowHistory.previous() : slideshowHistory.next();
|
||||||
if (!hasNext) {
|
if (!hasNext) {
|
||||||
const asset = await onRandom?.();
|
const asset = await onRandom?.();
|
||||||
@@ -243,22 +220,17 @@
|
|||||||
order === 'previous' ? await navigateToAsset(cursor.previousAsset) : await navigateToAsset(cursor.nextAsset);
|
order === 'previous' ? await navigateToAsset(cursor.previousAsset) : await navigateToAsset(cursor.nextAsset);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($slideshowState !== SlideshowState.PlaySlideshow) {
|
if ($slideshowState === SlideshowState.PlaySlideshow) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasNext) {
|
if (hasNext) {
|
||||||
$restartSlideshowProgress = true;
|
$restartSlideshowProgress = true;
|
||||||
return;
|
} else if ($slideshowRepeat && slideshowStartAssetId) {
|
||||||
}
|
// Loop back to starting asset
|
||||||
|
|
||||||
if ($slideshowRepeat && slideshowStartAssetId) {
|
|
||||||
await setAssetId(slideshowStartAssetId);
|
await setAssetId(slideshowStartAssetId);
|
||||||
$restartSlideshowProgress = true;
|
$restartSlideshowProgress = true;
|
||||||
return;
|
} else {
|
||||||
}
|
|
||||||
|
|
||||||
await handleStopSlideshow();
|
await handleStopSlideshow();
|
||||||
|
}
|
||||||
|
}
|
||||||
}, $t('error_while_navigating'));
|
}, $t('error_while_navigating'));
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -302,10 +274,12 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleStackedAssetMouseEvent = (isMouseOver: boolean, asset: AssetResponseDto) => {
|
||||||
|
previewStackedAsset = isMouseOver ? asset : undefined;
|
||||||
|
};
|
||||||
const handlePreAction = (action: Action) => {
|
const handlePreAction = (action: Action) => {
|
||||||
preAction?.(action);
|
preAction?.(action);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAction = async (action: Action) => {
|
const handleAction = async (action: Action) => {
|
||||||
switch (action.type) {
|
switch (action.type) {
|
||||||
case AssetAction.DELETE:
|
case AssetAction.DELETE:
|
||||||
@@ -314,7 +288,7 @@
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case AssetAction.REMOVE_ASSET_FROM_STACK: {
|
case AssetAction.REMOVE_ASSET_FROM_STACK: {
|
||||||
stack = action.stack ?? undefined;
|
stack = action.stack;
|
||||||
if (stack) {
|
if (stack) {
|
||||||
cursor.current = stack.assets[0];
|
cursor.current = stack.assets[0];
|
||||||
}
|
}
|
||||||
@@ -368,53 +342,27 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const refreshOcr = async () => {
|
|
||||||
ocrManager.clear();
|
|
||||||
if (sharedLink) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await ocrManager.getAssetOcr(asset.id);
|
|
||||||
};
|
|
||||||
|
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
await refreshStack();
|
await refreshStack();
|
||||||
await refreshOcr();
|
ocrManager.clear();
|
||||||
|
if (!sharedLink) {
|
||||||
|
if (previewStackedAsset) {
|
||||||
|
await ocrManager.getAssetOcr(previewStackedAsset.id);
|
||||||
|
}
|
||||||
|
await ocrManager.getAssetOcr(asset.id);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||||
cursor.current;
|
asset;
|
||||||
untrack(() => handlePromiseError(refresh()));
|
untrack(() => handlePromiseError(refresh()));
|
||||||
});
|
imageManager.preload(cursor.nextAsset);
|
||||||
|
imageManager.preload(cursor.previousAsset);
|
||||||
$effect(() => {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
|
||||||
previewStackedAsset;
|
|
||||||
untrack(() => handlePromiseError(refreshOcr()));
|
|
||||||
});
|
|
||||||
|
|
||||||
let lastCursor = $state<AssetCursor>();
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (cursor.current.id === lastCursor?.current.id) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (lastCursor) {
|
|
||||||
selectedStackAsset = undefined;
|
|
||||||
previewStackedAsset = undefined;
|
|
||||||
ocrManager.showOverlay = false;
|
|
||||||
preloadManager.updateAfterNavigation(lastCursor, cursor);
|
|
||||||
}
|
|
||||||
if (!lastCursor) {
|
|
||||||
preloadManager.initializePreloads(cursor);
|
|
||||||
}
|
|
||||||
lastCursor = cursor;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const viewerKind = $derived.by(() => {
|
const viewerKind = $derived.by(() => {
|
||||||
if (previewStackedAsset) {
|
if (previewStackedAsset) {
|
||||||
return previewStackedAsset.type === AssetTypeEnum.Image ? 'PhotoViewer' : 'StackVideoViewer';
|
return previewStackedAsset.type === AssetTypeEnum.Image ? 'StackPhotoViewer' : 'StackVideoViewer';
|
||||||
}
|
}
|
||||||
if (asset.type === AssetTypeEnum.Video) {
|
if (asset.type === AssetTypeEnum.Video) {
|
||||||
return 'VideoViewer';
|
return 'VideoViewer';
|
||||||
@@ -455,27 +403,6 @@
|
|||||||
assetViewerManager.isShowDetailPanel &&
|
assetViewerManager.isShowDetailPanel &&
|
||||||
!assetViewerManager.isShowEditor,
|
!assetViewerManager.isShowEditor,
|
||||||
);
|
);
|
||||||
|
|
||||||
const onSwipe = (event: SwipeCustomEvent) => {
|
|
||||||
if (assetViewerManager.zoom > 1) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ocrManager.showOverlay) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.detail.direction === 'left') {
|
|
||||||
navigateAsset('next');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.detail.direction === 'right') {
|
|
||||||
navigateAsset('previous');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let containerWidth = $state(0);
|
|
||||||
let containerHeight = $state(0);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<CommandPaletteDefaultProvider name={$t('assets')} actions={[Tag]} />
|
<CommandPaletteDefaultProvider name={$t('assets')} actions={[Tag]} />
|
||||||
@@ -521,20 +448,23 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
{#if $slideshowState === SlideshowState.None && showNavigation && !assetViewerManager.isShowEditor && !isFaceEditMode.value && previousAsset}
|
{#if $slideshowState === SlideshowState.None && showNavigation && !assetViewerManager.isShowEditor && previousAsset}
|
||||||
<div class="my-auto col-span-1 col-start-1 row-span-full row-start-1 justify-self-start">
|
<div class="my-auto col-span-1 col-start-1 row-span-full row-start-1 justify-self-start">
|
||||||
<PreviousAssetAction onPreviousAsset={() => navigateAsset('previous')} />
|
<PreviousAssetAction onPreviousAsset={() => navigateAsset('previous')} />
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<!-- Asset Viewer -->
|
<!-- Asset Viewer -->
|
||||||
<div
|
<div class="z-[-1] relative col-start-1 col-span-4 row-start-1 row-span-full">
|
||||||
data-viewer-content
|
{#if viewerKind === 'StackPhotoViewer'}
|
||||||
class="z-[-1] relative col-start-1 col-span-4 row-start-1 row-span-full"
|
<PhotoViewer
|
||||||
bind:clientWidth={containerWidth}
|
cursor={{ ...cursor, current: previewStackedAsset! }}
|
||||||
bind:clientHeight={containerHeight}
|
onPreviousAsset={() => navigateAsset('previous')}
|
||||||
>
|
onNextAsset={() => navigateAsset('next')}
|
||||||
{#if viewerKind === 'StackVideoViewer'}
|
haveFadeTransition={false}
|
||||||
|
{sharedLink}
|
||||||
|
/>
|
||||||
|
{:else if viewerKind === 'StackVideoViewer'}
|
||||||
<VideoViewer
|
<VideoViewer
|
||||||
asset={previewStackedAsset!}
|
asset={previewStackedAsset!}
|
||||||
cacheKey={previewStackedAsset!.thumbhash}
|
cacheKey={previewStackedAsset!.thumbhash}
|
||||||
@@ -564,7 +494,13 @@
|
|||||||
{:else if viewerKind === 'CropArea'}
|
{:else if viewerKind === 'CropArea'}
|
||||||
<CropArea {asset} />
|
<CropArea {asset} />
|
||||||
{:else if viewerKind === 'PhotoViewer'}
|
{:else if viewerKind === 'PhotoViewer'}
|
||||||
<PhotoViewer cursor={{ ...cursor, current: asset }} {sharedLink} {onSwipe} />
|
<PhotoViewer
|
||||||
|
{cursor}
|
||||||
|
onPreviousAsset={() => navigateAsset('previous')}
|
||||||
|
onNextAsset={() => navigateAsset('next')}
|
||||||
|
{sharedLink}
|
||||||
|
haveFadeTransition={$slideshowState !== SlideshowState.None && $slideshowTransition}
|
||||||
|
/>
|
||||||
{:else if viewerKind === 'VideoViewer'}
|
{:else if viewerKind === 'VideoViewer'}
|
||||||
<VideoViewer
|
<VideoViewer
|
||||||
{asset}
|
{asset}
|
||||||
@@ -597,65 +533,9 @@
|
|||||||
<OcrButton />
|
<OcrButton />
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
{#if stack && withStacked && !assetViewerManager.isShowEditor}
|
|
||||||
{@const stackedAssets = stack.assets}
|
|
||||||
<div
|
|
||||||
id="stack-slideshow"
|
|
||||||
class="absolute bottom-0 max-w-[calc(100%-5rem)] col-span-4 col-start-1 pointer-events-none"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
role="presentation"
|
|
||||||
class="relative inline-flex flex-row flex-nowrap max-w-full overflow-x-auto overflow-y-hidden horizontal-scrollbar pointer-events-auto"
|
|
||||||
onmouseleave={() => (previewStackedAsset = undefined)}
|
|
||||||
>
|
|
||||||
{#each stackedAssets as stackedAsset (stackedAsset.id)}
|
|
||||||
<div
|
|
||||||
class={['inline-block px-1 relative transition-all pb-2']}
|
|
||||||
style:bottom={stackedAsset.id === asset.id ? '0' : '-10px'}
|
|
||||||
>
|
|
||||||
<Thumbnail
|
|
||||||
imageClass={{ 'border-2 border-white': stackedAsset.id === asset.id }}
|
|
||||||
brokenAssetClass="text-xs"
|
|
||||||
dimmed={stackedAsset.id !== asset.id}
|
|
||||||
asset={toTimelineAsset(stackedAsset)}
|
|
||||||
onClick={async () => {
|
|
||||||
await selectStackedAsset(stackedAsset.id);
|
|
||||||
previewStackedAsset = undefined;
|
|
||||||
}}
|
|
||||||
onMouseEvent={async ({ isMouseOver }) => {
|
|
||||||
if (isMouseOver) {
|
|
||||||
previewStackedAsset = stackedAsset;
|
|
||||||
previewStackedAsset = await assetCacheManager.getAsset({ id: stackedAsset.id });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
readonly
|
|
||||||
thumbnailSize={stackedAsset.id === asset.id ? stackSelectedThumbnailSize : stackThumbnailSize}
|
|
||||||
showStackedIcon={false}
|
|
||||||
disableLinkMouseOver
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div class="w-full flex place-items-center place-content-center">
|
|
||||||
<div class={['w-2 h-2 rounded-full flex mt-0.5', { 'bg-white': stackedAsset.id === asset.id }]}></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if isFaceEditMode.value && assetViewerManager.imgRef}
|
|
||||||
<FaceEditor
|
|
||||||
htmlElement={assetViewerManager.imgRef}
|
|
||||||
{containerWidth}
|
|
||||||
{containerHeight}
|
|
||||||
assetId={asset.id}
|
|
||||||
onTagFace={refreshPreservingSelection}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if $slideshowState === SlideshowState.None && showNavigation && !assetViewerManager.isShowEditor && !isFaceEditMode.value && nextAsset}
|
{#if $slideshowState === SlideshowState.None && showNavigation && !assetViewerManager.isShowEditor && nextAsset}
|
||||||
<div class="my-auto col-span-1 col-start-4 row-span-full row-start-1 justify-self-end">
|
<div class="my-auto col-span-1 col-start-4 row-span-full row-start-1 justify-self-end">
|
||||||
<NextAssetAction onNextAsset={() => navigateAsset('next')} />
|
<NextAssetAction onNextAsset={() => navigateAsset('next')} />
|
||||||
</div>
|
</div>
|
||||||
@@ -670,7 +550,7 @@
|
|||||||
>
|
>
|
||||||
{#if showDetailPanel}
|
{#if showDetailPanel}
|
||||||
<div class="w-90 h-full">
|
<div class="w-90 h-full">
|
||||||
<DetailPanel {asset} currentAlbum={album} onRefreshPeople={refreshPreservingSelection} />
|
<DetailPanel {asset} currentAlbum={album} />
|
||||||
</div>
|
</div>
|
||||||
{:else if assetViewerManager.isShowEditor}
|
{:else if assetViewerManager.isShowEditor}
|
||||||
<div class="w-100 h-full">
|
<div class="w-100 h-full">
|
||||||
@@ -680,6 +560,42 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if stack && withStacked && !assetViewerManager.isShowEditor}
|
||||||
|
{@const stackedAssets = stack.assets}
|
||||||
|
<div id="stack-slideshow" class="absolute bottom-0 w-full col-span-4 col-start-1 pointer-events-none">
|
||||||
|
<div class="relative flex flex-row no-wrap overflow-x-auto overflow-y-hidden horizontal-scrollbar">
|
||||||
|
{#each stackedAssets as stackedAsset (stackedAsset.id)}
|
||||||
|
<div
|
||||||
|
class={['inline-block px-1 relative transition-all pb-2 pointer-events-auto']}
|
||||||
|
style:bottom={stackedAsset.id === asset.id ? '0' : '-10px'}
|
||||||
|
>
|
||||||
|
<Thumbnail
|
||||||
|
imageClass={{ 'border-2 border-white': stackedAsset.id === asset.id }}
|
||||||
|
brokenAssetClass="text-xs"
|
||||||
|
dimmed={stackedAsset.id !== asset.id}
|
||||||
|
asset={toTimelineAsset(stackedAsset)}
|
||||||
|
onClick={() => {
|
||||||
|
cursor.current = stackedAsset;
|
||||||
|
previewStackedAsset = undefined;
|
||||||
|
}}
|
||||||
|
onMouseEvent={({ isMouseOver }) => handleStackedAssetMouseEvent(isMouseOver, stackedAsset)}
|
||||||
|
readonly
|
||||||
|
thumbnailSize={stackedAsset.id === asset.id ? stackSelectedThumbnailSize : stackThumbnailSize}
|
||||||
|
showStackedIcon={false}
|
||||||
|
disableLinkMouseOver
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if stackedAsset.id === asset.id}
|
||||||
|
<div class="w-full flex place-items-center place-content-center">
|
||||||
|
<div class="w-2 h-2 bg-white rounded-full flex mt-0.5"></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if isShared && album && assetViewerManager.isShowActivityPanel && $user}
|
{#if isShared && album && assetViewerManager.isShowActivityPanel && $user}
|
||||||
<div
|
<div
|
||||||
transition:fly={{ duration: 150 }}
|
transition:fly={{ duration: 150 }}
|
||||||
@@ -726,15 +642,4 @@
|
|||||||
background: #adcbfa;
|
background: #adcbfa;
|
||||||
border-radius: 16px;
|
border-radius: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
#stack-slideshow .horizontal-scrollbar {
|
|
||||||
mask-image:
|
|
||||||
linear-gradient(to right, transparent, black 2rem, black calc(100% - 2rem), transparent),
|
|
||||||
linear-gradient(black, black);
|
|
||||||
mask-size:
|
|
||||||
100% calc(100% - 10px),
|
|
||||||
100% 10px;
|
|
||||||
mask-position: top, bottom;
|
|
||||||
mask-repeat: no-repeat;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -20,7 +20,13 @@
|
|||||||
import { handleError } from '$lib/utils/handle-error';
|
import { handleError } from '$lib/utils/handle-error';
|
||||||
import { fromISODateTime, fromISODateTimeUTC, toTimelineAsset } from '$lib/utils/timeline-util';
|
import { fromISODateTime, fromISODateTimeUTC, toTimelineAsset } from '$lib/utils/timeline-util';
|
||||||
import { getParentPath } from '$lib/utils/tree-utils';
|
import { getParentPath } from '$lib/utils/tree-utils';
|
||||||
import { AssetMediaSize, getAllAlbums, type AlbumResponseDto, type AssetResponseDto } from '@immich/sdk';
|
import {
|
||||||
|
AssetMediaSize,
|
||||||
|
getAllAlbums,
|
||||||
|
getAssetInfo,
|
||||||
|
type AlbumResponseDto,
|
||||||
|
type AssetResponseDto,
|
||||||
|
} from '@immich/sdk';
|
||||||
import { Icon, IconButton, LoadingSpinner, modalManager, Text } from '@immich/ui';
|
import { Icon, IconButton, LoadingSpinner, modalManager, Text } from '@immich/ui';
|
||||||
import {
|
import {
|
||||||
mdiCalendar,
|
mdiCalendar,
|
||||||
@@ -46,10 +52,9 @@
|
|||||||
interface Props {
|
interface Props {
|
||||||
asset: AssetResponseDto;
|
asset: AssetResponseDto;
|
||||||
currentAlbum?: AlbumResponseDto | null;
|
currentAlbum?: AlbumResponseDto | null;
|
||||||
onRefreshPeople?: () => Promise<void>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let { asset, currentAlbum = null, onRefreshPeople }: Props = $props();
|
let { asset, currentAlbum = null }: Props = $props();
|
||||||
|
|
||||||
let showAssetPath = $state(false);
|
let showAssetPath = $state(false);
|
||||||
let showEditFaces = $state(false);
|
let showEditFaces = $state(false);
|
||||||
@@ -115,6 +120,11 @@
|
|||||||
return undefined;
|
return undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleRefreshPeople = async () => {
|
||||||
|
asset = await getAssetInfo({ id: asset.id });
|
||||||
|
showEditFaces = false;
|
||||||
|
};
|
||||||
|
|
||||||
const getAssetFolderHref = (asset: AssetResponseDto) => {
|
const getAssetFolderHref = (asset: AssetResponseDto) => {
|
||||||
// Remove the last part of the path to get the parent path
|
// Remove the last part of the path to get the parent path
|
||||||
return Route.folders({ path: getParentPath(asset.originalPath) });
|
return Route.folders({ path: getParentPath(asset.originalPath) });
|
||||||
@@ -565,6 +575,6 @@
|
|||||||
assetId={asset.id}
|
assetId={asset.id}
|
||||||
assetType={asset.type}
|
assetType={asset.type}
|
||||||
onClose={() => (showEditFaces = false)}
|
onClose={() => (showEditFaces = false)}
|
||||||
onRefresh={() => void onRefreshPeople?.()}
|
onRefresh={handleRefreshPeople}
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import ImageThumbnail from '$lib/components/assets/thumbnail/image-thumbnail.svelte';
|
import ImageThumbnail from '$lib/components/assets/thumbnail/image-thumbnail.svelte';
|
||||||
|
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
|
||||||
import { isFaceEditMode } from '$lib/stores/face-edit.svelte';
|
import { isFaceEditMode } from '$lib/stores/face-edit.svelte';
|
||||||
import { getPeopleThumbnailUrl } from '$lib/utils';
|
import { getPeopleThumbnailUrl } from '$lib/utils';
|
||||||
import { getNaturalSize, scaleToFit } from '$lib/utils/container-utils';
|
import { getContentMetrics, getNaturalSize } from '$lib/utils/container-utils';
|
||||||
import { handleError } from '$lib/utils/handle-error';
|
import { handleError } from '$lib/utils/handle-error';
|
||||||
import { createFace, getAllPeople, type PersonResponseDto } from '@immich/sdk';
|
import { createFace, getAllPeople, type PersonResponseDto } from '@immich/sdk';
|
||||||
import { Button, Input, modalManager, toastManager } from '@immich/ui';
|
import { Button, Input, modalManager, toastManager } from '@immich/ui';
|
||||||
@@ -16,10 +17,9 @@
|
|||||||
containerWidth: number;
|
containerWidth: number;
|
||||||
containerHeight: number;
|
containerHeight: number;
|
||||||
assetId: string;
|
assetId: string;
|
||||||
onTagFace?: () => Promise<void>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let { htmlElement, containerWidth, containerHeight, assetId, onTagFace }: Props = $props();
|
let { htmlElement, containerWidth, containerHeight, assetId }: Props = $props();
|
||||||
|
|
||||||
let canvasEl: HTMLCanvasElement | undefined = $state();
|
let canvasEl: HTMLCanvasElement | undefined = $state();
|
||||||
let canvas: Canvas | undefined = $state();
|
let canvas: Canvas | undefined = $state();
|
||||||
@@ -31,10 +31,6 @@
|
|||||||
|
|
||||||
let searchTerm = $state('');
|
let searchTerm = $state('');
|
||||||
let faceBoxPosition = $state({ left: 0, top: 0, width: 0, height: 0 });
|
let faceBoxPosition = $state({ left: 0, top: 0, width: 0, height: 0 });
|
||||||
let initialized = false;
|
|
||||||
let previousContentWidth = 0;
|
|
||||||
let previousOffsetX = 0;
|
|
||||||
let previousOffsetY = 0;
|
|
||||||
|
|
||||||
let filteredCandidates = $derived(
|
let filteredCandidates = $derived(
|
||||||
searchTerm
|
searchTerm
|
||||||
@@ -85,62 +81,35 @@
|
|||||||
await getPeople();
|
await getPeople();
|
||||||
});
|
});
|
||||||
|
|
||||||
const imageContentMetrics = $derived.by(() => {
|
$effect(() => {
|
||||||
const natural = getNaturalSize(htmlElement);
|
const metrics = getContentMetrics(htmlElement);
|
||||||
const container = { width: containerWidth, height: containerHeight };
|
|
||||||
const { width: contentWidth, height: contentHeight } = scaleToFit(natural, container);
|
const imageBoundingBox = {
|
||||||
return {
|
top: metrics.offsetY,
|
||||||
contentWidth,
|
left: metrics.offsetX,
|
||||||
contentHeight,
|
width: metrics.contentWidth,
|
||||||
offsetX: (containerWidth - contentWidth) / 2,
|
height: metrics.contentHeight,
|
||||||
offsetY: (containerHeight - contentHeight) / 2,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (!canvas) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.setDimensions({
|
||||||
|
width: containerWidth,
|
||||||
|
height: containerHeight,
|
||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
if (!faceRect) {
|
||||||
const { offsetX, offsetY, contentWidth } = imageContentMetrics;
|
|
||||||
|
|
||||||
if (!canvas || contentWidth === 0) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!initialized) {
|
|
||||||
initialized = true;
|
|
||||||
canvas.setDimensions({ width: containerWidth, height: containerHeight });
|
|
||||||
|
|
||||||
if (faceRect) {
|
|
||||||
faceRect.set({ top: offsetY + 200, left: offsetX + 200 });
|
|
||||||
faceRect.setCoords();
|
|
||||||
}
|
|
||||||
|
|
||||||
previousContentWidth = contentWidth;
|
|
||||||
previousOffsetX = offsetX;
|
|
||||||
previousOffsetY = offsetY;
|
|
||||||
positionFaceSelector();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
canvas.setDimensions({ width: containerWidth, height: containerHeight });
|
|
||||||
|
|
||||||
if (faceRect && previousContentWidth > 0) {
|
|
||||||
const scale = contentWidth / previousContentWidth;
|
|
||||||
const imageRelLeft = (faceRect.left - previousOffsetX) * scale;
|
|
||||||
const imageRelTop = (faceRect.top - previousOffsetY) * scale;
|
|
||||||
|
|
||||||
faceRect.set({
|
faceRect.set({
|
||||||
left: offsetX + imageRelLeft,
|
top: imageBoundingBox.top + 200,
|
||||||
top: offsetY + imageRelTop,
|
left: imageBoundingBox.left + 200,
|
||||||
scaleX: faceRect.scaleX * scale,
|
|
||||||
scaleY: faceRect.scaleY * scale,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
faceRect.setCoords();
|
faceRect.setCoords();
|
||||||
}
|
|
||||||
|
|
||||||
previousContentWidth = contentWidth;
|
|
||||||
previousOffsetX = offsetX;
|
|
||||||
previousOffsetY = offsetY;
|
|
||||||
|
|
||||||
canvas.renderAll();
|
|
||||||
positionFaceSelector();
|
positionFaceSelector();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -245,13 +214,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { left, top, width, height } = faceRect.getBoundingRect();
|
const { left, top, width, height } = faceRect.getBoundingRect();
|
||||||
const { offsetX, offsetY, contentWidth, contentHeight } = imageContentMetrics;
|
const metrics = getContentMetrics(htmlElement);
|
||||||
const natural = getNaturalSize(htmlElement);
|
const natural = getNaturalSize(htmlElement);
|
||||||
|
|
||||||
const scaleX = natural.width / contentWidth;
|
const scaleX = natural.width / metrics.contentWidth;
|
||||||
const scaleY = natural.height / contentHeight;
|
const scaleY = natural.height / metrics.contentHeight;
|
||||||
const imageX = (left - offsetX) * scaleX;
|
const imageX = (left - metrics.offsetX) * scaleX;
|
||||||
const imageY = (top - offsetY) * scaleY;
|
const imageY = (top - metrics.offsetY) * scaleY;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
imageWidth: natural.width,
|
imageWidth: natural.width,
|
||||||
@@ -289,7 +258,7 @@
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await onTagFace?.();
|
await assetViewingStore.setAssetId(assetId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
handleError(error, 'Error tagging face');
|
handleError(error, 'Error tagging face');
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,55 +1,66 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { shortcuts } from '$lib/actions/shortcut';
|
import { shortcuts } from '$lib/actions/shortcut';
|
||||||
import { thumbhash } from '$lib/actions/thumbhash';
|
|
||||||
import { zoomImageAction } from '$lib/actions/zoom-image';
|
import { zoomImageAction } from '$lib/actions/zoom-image';
|
||||||
import AdaptiveImage from '$lib/components/AdaptiveImage.svelte';
|
import FaceEditor from '$lib/components/asset-viewer/face-editor/face-editor.svelte';
|
||||||
import OcrBoundingBox from '$lib/components/asset-viewer/ocr-bounding-box.svelte';
|
import OcrBoundingBox from '$lib/components/asset-viewer/ocr-bounding-box.svelte';
|
||||||
|
import BrokenAsset from '$lib/components/assets/broken-asset.svelte';
|
||||||
import AssetViewerEvents from '$lib/components/AssetViewerEvents.svelte';
|
import AssetViewerEvents from '$lib/components/AssetViewerEvents.svelte';
|
||||||
|
import { assetViewerFadeDuration } from '$lib/constants';
|
||||||
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
||||||
import { castManager } from '$lib/managers/cast-manager.svelte';
|
import { castManager } from '$lib/managers/cast-manager.svelte';
|
||||||
|
import { imageManager } from '$lib/managers/ImageManager.svelte';
|
||||||
import { isFaceEditMode } from '$lib/stores/face-edit.svelte';
|
import { isFaceEditMode } from '$lib/stores/face-edit.svelte';
|
||||||
import { ocrManager } from '$lib/stores/ocr.svelte';
|
import { ocrManager } from '$lib/stores/ocr.svelte';
|
||||||
import { boundingBoxesArray, type Faces } from '$lib/stores/people.store';
|
import { boundingBoxesArray, type Faces } from '$lib/stores/people.store';
|
||||||
import { SlideshowLook, SlideshowState, slideshowStore } from '$lib/stores/slideshow.store';
|
import { SlideshowLook, SlideshowState, slideshowLookCssMapping, slideshowStore } from '$lib/stores/slideshow.store';
|
||||||
import { handlePromiseError } from '$lib/utils';
|
import { getAssetUrl, targetImageSize as getTargetImageSize, handlePromiseError } from '$lib/utils';
|
||||||
import { canCopyImageToClipboard, copyImageToClipboard } from '$lib/utils/asset-utils';
|
import { canCopyImageToClipboard, copyImageToClipboard } from '$lib/utils/asset-utils';
|
||||||
import { getNaturalSize, scaleToFit, type ContentMetrics } from '$lib/utils/container-utils';
|
import { type ContentMetrics, getContentMetrics } from '$lib/utils/container-utils';
|
||||||
import { handleError } from '$lib/utils/handle-error';
|
import { handleError } from '$lib/utils/handle-error';
|
||||||
import { getOcrBoundingBoxes } from '$lib/utils/ocr-utils';
|
import { getOcrBoundingBoxes } from '$lib/utils/ocr-utils';
|
||||||
import { getBoundingBox } from '$lib/utils/people-utils';
|
import { getBoundingBox } from '$lib/utils/people-utils';
|
||||||
import { type SharedLinkResponseDto } from '@immich/sdk';
|
import { getAltText } from '$lib/utils/thumbnail-util';
|
||||||
import { toastManager } from '@immich/ui';
|
import { toTimelineAsset } from '$lib/utils/timeline-util';
|
||||||
|
import { AssetMediaSize, type SharedLinkResponseDto } from '@immich/sdk';
|
||||||
|
import { LoadingSpinner, toastManager } from '@immich/ui';
|
||||||
import { onDestroy, untrack } from 'svelte';
|
import { onDestroy, untrack } from 'svelte';
|
||||||
import { useSwipe, type SwipeCustomEvent } from 'svelte-gestures';
|
import { useSwipe, type SwipeCustomEvent } from 'svelte-gestures';
|
||||||
import { t } from 'svelte-i18n';
|
import { t } from 'svelte-i18n';
|
||||||
|
import { fade } from 'svelte/transition';
|
||||||
import type { AssetCursor } from './asset-viewer.svelte';
|
import type { AssetCursor } from './asset-viewer.svelte';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
cursor: AssetCursor;
|
cursor: AssetCursor;
|
||||||
element?: HTMLDivElement;
|
element?: HTMLDivElement | undefined;
|
||||||
sharedLink?: SharedLinkResponseDto;
|
haveFadeTransition?: boolean;
|
||||||
onReady?: () => void;
|
sharedLink?: SharedLinkResponseDto | undefined;
|
||||||
onError?: () => void;
|
onPreviousAsset?: (() => void) | null;
|
||||||
onSwipe?: (event: SwipeCustomEvent) => void;
|
onNextAsset?: (() => void) | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
let { cursor, element = $bindable(), sharedLink, onReady, onError, onSwipe }: Props = $props();
|
let {
|
||||||
|
cursor,
|
||||||
|
element = $bindable(),
|
||||||
|
haveFadeTransition = true,
|
||||||
|
sharedLink = undefined,
|
||||||
|
onPreviousAsset = null,
|
||||||
|
onNextAsset = null,
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
const { slideshowState, slideshowLook } = slideshowStore;
|
const { slideshowState, slideshowLook } = slideshowStore;
|
||||||
const asset = $derived(cursor.current);
|
const asset = $derived(cursor.current);
|
||||||
|
|
||||||
|
let imageLoaded: boolean = $state(false);
|
||||||
|
let originalImageLoaded: boolean = $state(false);
|
||||||
|
let imageError: boolean = $state(false);
|
||||||
let visibleImageReady: boolean = $state(false);
|
let visibleImageReady: boolean = $state(false);
|
||||||
|
|
||||||
let previousAssetId: string | undefined;
|
let loader = $state<HTMLImageElement>();
|
||||||
|
|
||||||
$effect.pre(() => {
|
$effect.pre(() => {
|
||||||
const id = asset.id;
|
void asset.id;
|
||||||
if (id === previousAssetId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
previousAssetId = id;
|
|
||||||
untrack(() => {
|
untrack(() => {
|
||||||
assetViewerManager.resetZoomState();
|
assetViewerManager.resetZoomState();
|
||||||
visibleImageReady = false;
|
|
||||||
$boundingBoxesArray = [];
|
$boundingBoxesArray = [];
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -58,30 +69,25 @@
|
|||||||
$boundingBoxesArray = [];
|
$boundingBoxesArray = [];
|
||||||
});
|
});
|
||||||
|
|
||||||
let containerWidth = $state(0);
|
|
||||||
let containerHeight = $state(0);
|
|
||||||
|
|
||||||
const container = $derived({
|
|
||||||
width: containerWidth,
|
|
||||||
height: containerHeight,
|
|
||||||
});
|
|
||||||
|
|
||||||
const overlayMetrics = $derived.by((): ContentMetrics => {
|
const overlayMetrics = $derived.by((): ContentMetrics => {
|
||||||
if (!assetViewerManager.imgRef || !visibleImageReady) {
|
if (!assetViewerManager.imgRef || !visibleImageReady) {
|
||||||
return { contentWidth: 0, contentHeight: 0, offsetX: 0, offsetY: 0 };
|
return { contentWidth: 0, contentHeight: 0, offsetX: 0, offsetY: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const natural = getNaturalSize(assetViewerManager.imgRef);
|
const { contentWidth, contentHeight, offsetX, offsetY } = getContentMetrics(assetViewerManager.imgRef);
|
||||||
const scaled = scaleToFit(natural, container);
|
const { currentZoom, currentPositionX, currentPositionY } = assetViewerManager.zoomState;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
contentWidth: scaled.width,
|
contentWidth: contentWidth * currentZoom,
|
||||||
contentHeight: scaled.height,
|
contentHeight: contentHeight * currentZoom,
|
||||||
offsetX: 0,
|
offsetX: offsetX * currentZoom + currentPositionX,
|
||||||
offsetY: 0,
|
offsetY: offsetY * currentZoom + currentPositionY,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
const ocrBoxes = $derived(ocrManager.showOverlay ? getOcrBoundingBoxes(ocrManager.data, overlayMetrics) : []);
|
let ocrBoxes = $derived(ocrManager.showOverlay ? getOcrBoundingBoxes(ocrManager.data, overlayMetrics) : []);
|
||||||
|
|
||||||
|
let isOcrActive = $derived(ocrManager.showOverlay);
|
||||||
|
|
||||||
const onCopy = async () => {
|
const onCopy = async () => {
|
||||||
if (!canCopyImageToClipboard() || !assetViewerManager.imgRef) {
|
if (!canCopyImageToClipboard() || !assetViewerManager.imgRef) {
|
||||||
@@ -97,7 +103,8 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onZoom = () => {
|
const onZoom = () => {
|
||||||
assetViewerManager.zoom = assetViewerManager.zoom > 1 ? 1 : 2;
|
const targetZoom = assetViewerManager.zoom > 1 ? 1 : 2;
|
||||||
|
assetViewerManager.animatedZoom(targetZoom);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onPlaySlideshow = () => ($slideshowState = SlideshowState.PlaySlideshow);
|
const onPlaySlideshow = () => ($slideshowState = SlideshowState.PlaySlideshow);
|
||||||
@@ -118,15 +125,29 @@
|
|||||||
handlePromiseError(onCopy());
|
handlePromiseError(onCopy());
|
||||||
};
|
};
|
||||||
|
|
||||||
let currentPreviewUrl = $state<string>();
|
const onSwipe = (event: SwipeCustomEvent) => {
|
||||||
|
if (assetViewerManager.zoom > 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const onUrlChange = (url: string) => {
|
if (ocrManager.showOverlay) {
|
||||||
currentPreviewUrl = url;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (onNextAsset && event.detail.direction === 'left') {
|
||||||
|
onNextAsset();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (onPreviousAsset && event.detail.direction === 'right') {
|
||||||
|
onPreviousAsset();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const targetImageSize = $derived(getTargetImageSize(asset, originalImageLoaded || assetViewerManager.zoom > 1));
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (currentPreviewUrl) {
|
if (imageLoaderUrl) {
|
||||||
void cast(currentPreviewUrl);
|
void cast(imageLoaderUrl);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -144,11 +165,37 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const blurredSlideshow = $derived(
|
const onload = () => {
|
||||||
$slideshowState !== SlideshowState.None && $slideshowLook === SlideshowLook.BlurredBackground && !!asset.thumbhash,
|
imageLoaded = true;
|
||||||
|
originalImageLoaded = targetImageSize === AssetMediaSize.Fullsize || targetImageSize === 'original';
|
||||||
|
};
|
||||||
|
|
||||||
|
const onerror = () => {
|
||||||
|
imageError = imageLoaded = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
onDestroy(() => imageManager.cancel(asset, targetImageSize));
|
||||||
|
|
||||||
|
let imageLoaderUrl = $derived(
|
||||||
|
getAssetUrl({ asset, sharedLink, forceOriginal: originalImageLoaded || assetViewerManager.zoom > 1 }),
|
||||||
);
|
);
|
||||||
|
|
||||||
let adaptiveImage = $state<HTMLDivElement | undefined>();
|
let containerWidth = $state(0);
|
||||||
|
let containerHeight = $state(0);
|
||||||
|
|
||||||
|
let lastUrl: string | undefined;
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (lastUrl && lastUrl !== imageLoaderUrl) {
|
||||||
|
untrack(() => {
|
||||||
|
imageLoaded = false;
|
||||||
|
originalImageLoaded = false;
|
||||||
|
imageError = false;
|
||||||
|
visibleImageReady = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
lastUrl = imageLoaderUrl;
|
||||||
|
});
|
||||||
|
|
||||||
const faceToNameMap = $derived.by(() => {
|
const faceToNameMap = $derived.by(() => {
|
||||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity
|
// eslint-disable-next-line svelte/prefer-svelte-reactivity
|
||||||
@@ -162,6 +209,29 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
const faces = $derived(Array.from(faceToNameMap.keys()));
|
const faces = $derived(Array.from(faceToNameMap.keys()));
|
||||||
|
|
||||||
|
const handleImageMouseMove = (event: MouseEvent) => {
|
||||||
|
$boundingBoxesArray = [];
|
||||||
|
if (!assetViewerManager.imgRef || !element || isFaceEditMode.value || ocrManager.showOverlay) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const containerRect = element.getBoundingClientRect();
|
||||||
|
const mouseX = event.clientX - containerRect.left;
|
||||||
|
const mouseY = event.clientY - containerRect.top;
|
||||||
|
|
||||||
|
const faceBoxes = getBoundingBox(faces, overlayMetrics);
|
||||||
|
|
||||||
|
for (const [index, box] of faceBoxes.entries()) {
|
||||||
|
if (mouseX >= box.left && mouseX <= box.left + box.width && mouseY >= box.top && mouseY <= box.top + box.height) {
|
||||||
|
$boundingBoxesArray.push(faces[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImageMouseLeave = () => {
|
||||||
|
$boundingBoxesArray = [];
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<AssetViewerEvents {onCopy} {onZoom} />
|
<AssetViewerEvents {onCopy} {onZoom} />
|
||||||
@@ -174,7 +244,12 @@
|
|||||||
{ shortcut: { key: 'c', meta: true }, onShortcut: onCopyShortcut, preventDefault: false },
|
{ shortcut: { key: 'c', meta: true }, onShortcut: onCopyShortcut, preventDefault: false },
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
{#if imageError}
|
||||||
|
<div id="broken-asset" class="h-full w-full">
|
||||||
|
<BrokenAsset class="text-xl h-full w-full" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<img bind:this={loader} style="display:none" src={imageLoaderUrl} alt="" aria-hidden="true" {onload} {onerror} />
|
||||||
<div
|
<div
|
||||||
bind:this={element}
|
bind:this={element}
|
||||||
class="relative h-full w-full select-none"
|
class="relative h-full w-full select-none"
|
||||||
@@ -182,67 +257,74 @@
|
|||||||
bind:clientHeight={containerHeight}
|
bind:clientHeight={containerHeight}
|
||||||
role="presentation"
|
role="presentation"
|
||||||
ondblclick={onZoom}
|
ondblclick={onZoom}
|
||||||
use:zoomImageAction={{ disabled: isFaceEditMode.value, zoomTarget: adaptiveImage }}
|
onmousemove={handleImageMouseMove}
|
||||||
{...useSwipe((event) => onSwipe?.(event))}
|
onmouseleave={handleImageMouseLeave}
|
||||||
>
|
>
|
||||||
<AdaptiveImage
|
{#if !imageLoaded}
|
||||||
{asset}
|
<div id="spinner" class="flex h-full items-center justify-center">
|
||||||
{sharedLink}
|
<LoadingSpinner />
|
||||||
{container}
|
</div>
|
||||||
objectFit={$slideshowState !== SlideshowState.None && $slideshowLook === SlideshowLook.Cover ? 'cover' : 'contain'}
|
{:else if !imageError}
|
||||||
{onUrlChange}
|
|
||||||
onImageReady={() => {
|
|
||||||
visibleImageReady = true;
|
|
||||||
onReady?.();
|
|
||||||
}}
|
|
||||||
onError={() => {
|
|
||||||
onError?.();
|
|
||||||
onReady?.();
|
|
||||||
}}
|
|
||||||
bind:imgRef={assetViewerManager.imgRef}
|
|
||||||
bind:ref={adaptiveImage}
|
|
||||||
>
|
|
||||||
{#snippet backdrop()}
|
|
||||||
{#if blurredSlideshow}
|
|
||||||
<canvas
|
|
||||||
use:thumbhash={{ base64ThumbHash: asset.thumbhash! }}
|
|
||||||
class="absolute top-0 left-0 inset-s-0 h-dvh w-dvw"
|
|
||||||
></canvas>
|
|
||||||
{/if}
|
|
||||||
{/snippet}
|
|
||||||
{#snippet overlays()}
|
|
||||||
{#if !isFaceEditMode.value && !ocrManager.showOverlay}
|
|
||||||
{#each getBoundingBox(faces, overlayMetrics) as boundingbox, index (boundingbox.id)}
|
|
||||||
{@const face = faces[index]}
|
|
||||||
{@const name = faceToNameMap.get(face)}
|
|
||||||
{@const isActive = $boundingBoxesArray.includes(face)}
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
|
||||||
<div
|
<div
|
||||||
class={[
|
use:zoomImageAction={{ disabled: isOcrActive }}
|
||||||
'absolute pointer-events-auto outline-none rounded-lg',
|
{...useSwipe(onSwipe)}
|
||||||
isActive && 'border-solid border-white border-3',
|
class="h-full w-full"
|
||||||
]}
|
transition:fade={{ duration: haveFadeTransition ? assetViewerFadeDuration : 0 }}
|
||||||
|
>
|
||||||
|
{#if $slideshowState !== SlideshowState.None && $slideshowLook === SlideshowLook.BlurredBackground}
|
||||||
|
<img
|
||||||
|
src={imageLoaderUrl}
|
||||||
|
alt=""
|
||||||
|
class="-z-1 absolute top-0 start-0 object-cover h-full w-full blur-lg"
|
||||||
|
draggable="false"
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
<img
|
||||||
|
bind:this={assetViewerManager.imgRef}
|
||||||
|
src={imageLoaderUrl}
|
||||||
|
onload={() => (visibleImageReady = true)}
|
||||||
|
alt={$getAltText(toTimelineAsset(asset))}
|
||||||
|
class="h-full w-full {$slideshowState === SlideshowState.None
|
||||||
|
? 'object-contain'
|
||||||
|
: slideshowLookCssMapping[$slideshowLook]}"
|
||||||
|
draggable="false"
|
||||||
|
/>
|
||||||
|
{#each getBoundingBox($boundingBoxesArray, overlayMetrics) as boundingbox, index (boundingbox.id)}
|
||||||
|
<div
|
||||||
|
class="absolute border-solid border-white border-3 rounded-lg"
|
||||||
style="top: {boundingbox.top}px; left: {boundingbox.left}px; height: {boundingbox.height}px; width: {boundingbox.width}px;"
|
style="top: {boundingbox.top}px; left: {boundingbox.left}px; height: {boundingbox.height}px; width: {boundingbox.width}px;"
|
||||||
aria-label="{$t('person')}: {name || $t('unknown')}"
|
></div>
|
||||||
onmouseenter={() => ($boundingBoxesArray = [face])}
|
{#if faceToNameMap.get($boundingBoxesArray[index])}
|
||||||
onmouseleave={() => ($boundingBoxesArray = [])}
|
|
||||||
>
|
|
||||||
{#if isActive && name}
|
|
||||||
<div
|
<div
|
||||||
aria-hidden="true"
|
|
||||||
class="absolute bg-white/90 text-black px-2 py-1 rounded text-sm font-medium whitespace-nowrap pointer-events-none shadow-lg"
|
class="absolute bg-white/90 text-black px-2 py-1 rounded text-sm font-medium whitespace-nowrap pointer-events-none shadow-lg"
|
||||||
style="top: {boundingbox.height + 4}px; right: 0;"
|
style="top: {boundingbox.top + boundingbox.height + 4}px; left: {boundingbox.left +
|
||||||
|
boundingbox.width}px; transform: translateX(-100%);"
|
||||||
>
|
>
|
||||||
{name}
|
{faceToNameMap.get($boundingBoxesArray[index])}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
|
||||||
{/each}
|
{/each}
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#each ocrBoxes as ocrBox (ocrBox.id)}
|
{#each ocrBoxes as ocrBox (ocrBox.id)}
|
||||||
<OcrBoundingBox {ocrBox} />
|
<OcrBoundingBox {ocrBox} />
|
||||||
{/each}
|
{/each}
|
||||||
{/snippet}
|
</div>
|
||||||
</AdaptiveImage>
|
|
||||||
|
{#if isFaceEditMode.value}
|
||||||
|
<FaceEditor htmlElement={assetViewerManager.imgRef} {containerWidth} {containerHeight} assetId={asset.id} />
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
@keyframes delayedVisibility {
|
||||||
|
to {
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#broken-asset,
|
||||||
|
#spinner {
|
||||||
|
visibility: hidden;
|
||||||
|
animation: 0s linear 0.4s forwards delayedVisibility;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import OnEvents from '$lib/components/OnEvents.svelte';
|
import OnEvents from '$lib/components/OnEvents.svelte';
|
||||||
import { timeBeforeShowLoadingSpinner } from '$lib/constants';
|
import { timeBeforeShowLoadingSpinner } from '$lib/constants';
|
||||||
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
|
||||||
import { eventManager } from '$lib/managers/event-manager.svelte';
|
import { eventManager } from '$lib/managers/event-manager.svelte';
|
||||||
|
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
|
||||||
import { boundingBoxesArray } from '$lib/stores/people.store';
|
import { boundingBoxesArray } from '$lib/stores/people.store';
|
||||||
import { getPeopleThumbnailUrl, handlePromiseError } from '$lib/utils';
|
import { getPeopleThumbnailUrl, handlePromiseError } from '$lib/utils';
|
||||||
import { handleError } from '$lib/utils/handle-error';
|
import { handleError } from '$lib/utils/handle-error';
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition';
|
||||||
import ImageThumbnail from '../assets/thumbnail/image-thumbnail.svelte';
|
import ImageThumbnail from '../assets/thumbnail/image-thumbnail.svelte';
|
||||||
import AssignFaceSidePanel from './assign-face-side-panel.svelte';
|
import AssignFaceSidePanel from './assign-face-side-panel.svelte';
|
||||||
|
import { assetViewerManager } from '$lib/managers/asset-viewer-manager.svelte';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
assetId: string;
|
assetId: string;
|
||||||
@@ -178,10 +179,7 @@
|
|||||||
|
|
||||||
peopleWithFaces = peopleWithFaces.filter((f) => f.id !== face.id);
|
peopleWithFaces = peopleWithFaces.filter((f) => f.id !== face.id);
|
||||||
|
|
||||||
onRefresh();
|
await assetViewingStore.setAssetId(assetId);
|
||||||
if (peopleWithFaces.length === 0) {
|
|
||||||
onClose();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
handleError(error, $t('error_delete_face'));
|
handleError(error, $t('error_delete_face'));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
import { getAssetMediaUrl } from '$lib/utils';
|
import { getAssetMediaUrl } from '$lib/utils';
|
||||||
import { getAltText } from '$lib/utils/thumbnail-util';
|
import { getAltText } from '$lib/utils/thumbnail-util';
|
||||||
import { AssetMediaSize } from '@immich/sdk';
|
import { AssetMediaSize } from '@immich/sdk';
|
||||||
import DelayedLoadingSpinner from '$lib/components/DelayedLoadingSpinner.svelte';
|
import { LoadingSpinner } from '@immich/ui';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { fade } from 'svelte/transition';
|
import { fade } from 'svelte/transition';
|
||||||
|
|
||||||
@@ -44,7 +44,9 @@
|
|||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
{#if !imageLoaded}
|
{#if !imageLoaded}
|
||||||
<DelayedLoadingSpinner />
|
<div id="spinner" class="flex h-full items-center justify-center">
|
||||||
|
<LoadingSpinner />
|
||||||
|
</div>
|
||||||
{:else if imageLoaded}
|
{:else if imageLoaded}
|
||||||
<div transition:fade={{ duration: assetViewerFadeDuration }} class="h-full w-full">
|
<div transition:fade={{ duration: assetViewerFadeDuration }} class="h-full w-full">
|
||||||
<img
|
<img
|
||||||
@@ -55,3 +57,15 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
@keyframes delayedVisibility {
|
||||||
|
to {
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#spinner {
|
||||||
|
visibility: hidden;
|
||||||
|
animation: 0s linear 0.4s forwards delayedVisibility;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { imageManager } from '$lib/managers/ImageManager.svelte';
|
||||||
|
import { getAssetMediaUrl } from '$lib/utils';
|
||||||
|
import { cancelImageUrl } from '$lib/utils/sw-messaging';
|
||||||
|
import { AssetMediaSize } from '@immich/sdk';
|
||||||
|
import { assetFactory } from '@test-data/factories/asset-factory';
|
||||||
|
|
||||||
|
vi.mock('$lib/utils/sw-messaging', () => ({
|
||||||
|
cancelImageUrl: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('$lib/utils', () => ({
|
||||||
|
getAssetMediaUrl: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('ImageManager', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('preload', () => {
|
||||||
|
it('creates an Image with the correct URL', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockReturnValue('/api/assets/123/media');
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.preload(asset);
|
||||||
|
|
||||||
|
expect(getAssetMediaUrl).toHaveBeenCalledWith({
|
||||||
|
id: asset.id,
|
||||||
|
size: AssetMediaSize.Preview,
|
||||||
|
cacheKey: asset.thumbhash,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing for undefined asset', () => {
|
||||||
|
imageManager.preload(undefined);
|
||||||
|
expect(getAssetMediaUrl).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when getAssetMediaUrl returns falsy', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockReturnValue('');
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.preload(asset);
|
||||||
|
|
||||||
|
expect(getAssetMediaUrl).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the specified size', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockReturnValue('/api/assets/123/media');
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.preload(asset, AssetMediaSize.Thumbnail);
|
||||||
|
|
||||||
|
expect(getAssetMediaUrl).toHaveBeenCalledWith({
|
||||||
|
id: asset.id,
|
||||||
|
size: AssetMediaSize.Thumbnail,
|
||||||
|
cacheKey: asset.thumbhash,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cancel', () => {
|
||||||
|
it('calls cancelImageUrl with the correct URL', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockReturnValue('/api/assets/123/media');
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.cancel(asset, AssetMediaSize.Preview);
|
||||||
|
|
||||||
|
expect(cancelImageUrl).toHaveBeenCalledWith('/api/assets/123/media');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing for undefined asset', () => {
|
||||||
|
imageManager.cancel(undefined);
|
||||||
|
expect(getAssetMediaUrl).not.toHaveBeenCalled();
|
||||||
|
expect(cancelImageUrl).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels all sizes when size is "all"', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockImplementation(({ size }) => `/api/assets/123/${size}`);
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.cancel(asset, 'all');
|
||||||
|
|
||||||
|
expect(getAssetMediaUrl).toHaveBeenCalledTimes(Object.values(AssetMediaSize).length);
|
||||||
|
for (const size of Object.values(AssetMediaSize)) {
|
||||||
|
expect(cancelImageUrl).toHaveBeenCalledWith(`/api/assets/123/${size}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not call cancelImageUrl when URL is falsy', () => {
|
||||||
|
vi.mocked(getAssetMediaUrl).mockReturnValue('');
|
||||||
|
const asset = assetFactory.build();
|
||||||
|
|
||||||
|
imageManager.cancel(asset, AssetMediaSize.Preview);
|
||||||
|
|
||||||
|
expect(cancelImageUrl).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { getAssetMediaUrl } from '$lib/utils';
|
||||||
|
import { cancelImageUrl } from '$lib/utils/sw-messaging';
|
||||||
|
import { AssetMediaSize, type AssetResponseDto } from '@immich/sdk';
|
||||||
|
|
||||||
|
type AllAssetMediaSize = AssetMediaSize | 'all';
|
||||||
|
|
||||||
|
class ImageManager {
|
||||||
|
preload(asset: AssetResponseDto | undefined, size: AssetMediaSize = AssetMediaSize.Preview) {
|
||||||
|
if (!asset) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = getAssetMediaUrl({ id: asset.id, size, cacheKey: asset.thumbhash });
|
||||||
|
if (!url) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const img = new Image();
|
||||||
|
img.src = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(asset: AssetResponseDto | undefined, size: AllAssetMediaSize = AssetMediaSize.Preview) {
|
||||||
|
if (!asset) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizes = size === 'all' ? Object.values(AssetMediaSize) : [size];
|
||||||
|
for (const size of sizes) {
|
||||||
|
const url = getAssetMediaUrl({ id: asset.id, size, cacheKey: asset.thumbhash });
|
||||||
|
if (url) {
|
||||||
|
cancelImageUrl(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const imageManager = new ImageManager();
|
||||||
@@ -2,6 +2,7 @@ import { canCopyImageToClipboard } from '$lib/utils/asset-utils';
|
|||||||
import { BaseEventManager } from '$lib/utils/base-event-manager.svelte';
|
import { BaseEventManager } from '$lib/utils/base-event-manager.svelte';
|
||||||
import { PersistedLocalStorage } from '$lib/utils/persisted';
|
import { PersistedLocalStorage } from '$lib/utils/persisted';
|
||||||
import type { ZoomImageWheelState } from '@zoom-image/core';
|
import type { ZoomImageWheelState } from '@zoom-image/core';
|
||||||
|
import { cubicOut } from 'svelte/easing';
|
||||||
|
|
||||||
const isShowDetailPanel = new PersistedLocalStorage<boolean>('asset-viewer-state', false);
|
const isShowDetailPanel = new PersistedLocalStorage<boolean>('asset-viewer-state', false);
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ export type Events = {
|
|||||||
|
|
||||||
export class AssetViewerManager extends BaseEventManager<Events> {
|
export class AssetViewerManager extends BaseEventManager<Events> {
|
||||||
#zoomState = $state(createDefaultZoomState());
|
#zoomState = $state(createDefaultZoomState());
|
||||||
|
#animationFrameId: number | null = null;
|
||||||
|
|
||||||
imgRef = $state<HTMLImageElement | undefined>();
|
imgRef = $state<HTMLImageElement | undefined>();
|
||||||
isShowActivityPanel = $state(false);
|
isShowActivityPanel = $state(false);
|
||||||
@@ -45,6 +47,7 @@ export class AssetViewerManager extends BaseEventManager<Events> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
set zoom(zoom: number) {
|
set zoom(zoom: number) {
|
||||||
|
this.cancelZoomAnimation();
|
||||||
this.zoomState = { ...this.zoomState, currentZoom: zoom };
|
this.zoomState = { ...this.zoomState, currentZoom: zoom };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +72,35 @@ export class AssetViewerManager extends BaseEventManager<Events> {
|
|||||||
this.#zoomState = state;
|
this.#zoomState = state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cancelZoomAnimation() {
|
||||||
|
if (this.#animationFrameId !== null) {
|
||||||
|
cancelAnimationFrame(this.#animationFrameId);
|
||||||
|
this.#animationFrameId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
animatedZoom(targetZoom: number, duration = 300) {
|
||||||
|
this.cancelZoomAnimation();
|
||||||
|
|
||||||
|
const startZoom = this.#zoomState.currentZoom;
|
||||||
|
const startTime = performance.now();
|
||||||
|
|
||||||
|
const frame = (currentTime: number) => {
|
||||||
|
const elapsed = currentTime - startTime;
|
||||||
|
const linearProgress = Math.min(elapsed / duration, 1);
|
||||||
|
const easedProgress = cubicOut(linearProgress);
|
||||||
|
const interpolatedZoom = startZoom + (targetZoom - startZoom) * easedProgress;
|
||||||
|
|
||||||
|
this.zoomState = { ...this.#zoomState, currentZoom: interpolatedZoom };
|
||||||
|
|
||||||
|
this.#animationFrameId = linearProgress < 1 ? requestAnimationFrame(frame) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.#animationFrameId = requestAnimationFrame(frame);
|
||||||
|
}
|
||||||
|
|
||||||
resetZoomState() {
|
resetZoomState() {
|
||||||
|
this.cancelZoomAnimation();
|
||||||
this.zoomState = createDefaultZoomState();
|
this.zoomState = createDefaultZoomState();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ describe('OcrManager', () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
// Reset the singleton state before each test
|
// Reset the singleton state before each test
|
||||||
ocrManager.clear();
|
ocrManager.clear();
|
||||||
ocrManager.showOverlay = false;
|
|
||||||
assetCacheManager.clearOcrCache();
|
assetCacheManager.clearOcrCache();
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
});
|
});
|
||||||
@@ -133,12 +132,12 @@ describe('OcrManager', () => {
|
|||||||
expect(ocrManager.hasOcrData).toBe(false);
|
expect(ocrManager.hasOcrData).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not reset showOverlay', () => {
|
it('should reset showOverlay to false', () => {
|
||||||
ocrManager.showOverlay = true;
|
ocrManager.showOverlay = true;
|
||||||
|
|
||||||
ocrManager.clear();
|
ocrManager.clear();
|
||||||
|
|
||||||
expect(ocrManager.showOverlay).toBe(true);
|
expect(ocrManager.showOverlay).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should mark as cleared for next load', async () => {
|
it('should mark as cleared for next load', async () => {
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ class OcrManager {
|
|||||||
clear() {
|
clear() {
|
||||||
this.#cleared = true;
|
this.#cleared = true;
|
||||||
this.#data = [];
|
this.#data = [];
|
||||||
|
this.showOverlay = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleOcrBoundingBox() {
|
toggleOcrBoundingBox() {
|
||||||
|
|||||||
@@ -186,14 +186,6 @@ export const getAssetUrl = ({
|
|||||||
return getAssetMediaUrl({ id, size, cacheKey });
|
return getAssetMediaUrl({ id, size, cacheKey });
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getAssetUrls(asset: AssetResponseDto, sharedLink?: SharedLinkResponseDto) {
|
|
||||||
return {
|
|
||||||
thumbnail: getAssetMediaUrl({ id: asset.id, cacheKey: asset.thumbhash, size: AssetMediaSize.Thumbnail }),
|
|
||||||
preview: getAssetUrl({ asset, sharedLink })!,
|
|
||||||
original: getAssetUrl({ asset, sharedLink, forceOriginal: true })!,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const forceUseOriginal = (asset: AssetResponseDto) => {
|
const forceUseOriginal = (asset: AssetResponseDto) => {
|
||||||
return asset.type === AssetTypeEnum.Image && asset.duration && !asset.duration.includes('0:00:00.000');
|
return asset.type === AssetTypeEnum.Image && asset.duration && !asset.duration.includes('0:00:00.000');
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,304 +0,0 @@
|
|||||||
import { AdaptiveImageLoader, type QualityList } from '$lib/utils/adaptive-image-loader.svelte';
|
|
||||||
import { cancelImageUrl } from '$lib/utils/sw-messaging';
|
|
||||||
|
|
||||||
vi.mock('$lib/utils/sw-messaging', () => ({
|
|
||||||
cancelImageUrl: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
function createQualityList(overrides?: {
|
|
||||||
onAfterLoad?: Record<string, (loader: AdaptiveImageLoader) => void>;
|
|
||||||
onAfterError?: Record<string, (loader: AdaptiveImageLoader) => void>;
|
|
||||||
}): QualityList {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
quality: 'thumbnail',
|
|
||||||
url: '/thumbnail.jpg',
|
|
||||||
onAfterLoad: overrides?.onAfterLoad?.thumbnail,
|
|
||||||
onAfterError: overrides?.onAfterError?.thumbnail,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
quality: 'preview',
|
|
||||||
url: '/preview.jpg',
|
|
||||||
onAfterLoad: overrides?.onAfterLoad?.preview,
|
|
||||||
onAfterError: overrides?.onAfterError?.preview,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
quality: 'original',
|
|
||||||
url: '/original.jpg',
|
|
||||||
onAfterLoad: overrides?.onAfterLoad?.original,
|
|
||||||
onAfterError: overrides?.onAfterError?.original,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('AdaptiveImageLoader', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('constructor', () => {
|
|
||||||
it('initializes with thumbnail URL set', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
expect(loader.status.urls.thumbnail).toBe('/thumbnail.jpg');
|
|
||||||
expect(loader.status.urls.preview).toBeUndefined();
|
|
||||||
expect(loader.status.urls.original).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('initializes all qualities as unloaded', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
expect(loader.status.quality.thumbnail).toBe('unloaded');
|
|
||||||
expect(loader.status.quality.preview).toBe('unloaded');
|
|
||||||
expect(loader.status.quality.original).toBe('unloaded');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('onStart', () => {
|
|
||||||
it('sets started to true', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
expect(loader.status.started).toBe(false);
|
|
||||||
loader.onStart('thumbnail');
|
|
||||||
expect(loader.status.started).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is a no-op after destroy', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
loader.destroy();
|
|
||||||
loader.onStart('thumbnail');
|
|
||||||
expect(loader.status.started).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('onLoad', () => {
|
|
||||||
it('sets quality to success and calls callbacks', () => {
|
|
||||||
const onUrlChange = vi.fn();
|
|
||||||
const onImageReady = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onUrlChange, onImageReady });
|
|
||||||
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
|
|
||||||
expect(loader.status.quality.thumbnail).toBe('success');
|
|
||||||
expect(onUrlChange).toHaveBeenCalledWith('/thumbnail.jpg');
|
|
||||||
expect(onImageReady).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls onAfterLoad callback', () => {
|
|
||||||
const onAfterLoad = vi.fn();
|
|
||||||
const qualityList = createQualityList({ onAfterLoad: { thumbnail: onAfterLoad } });
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList);
|
|
||||||
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
|
|
||||||
expect(onAfterLoad).toHaveBeenCalledWith(loader);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores load if URL is not set', () => {
|
|
||||||
const onImageReady = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onImageReady });
|
|
||||||
|
|
||||||
loader.onLoad('preview');
|
|
||||||
|
|
||||||
expect(loader.status.quality.preview).toBe('unloaded');
|
|
||||||
expect(onImageReady).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores load if a higher quality is already loaded', () => {
|
|
||||||
const onUrlChange = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onUrlChange });
|
|
||||||
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
loader.trigger('preview');
|
|
||||||
loader.onLoad('preview');
|
|
||||||
|
|
||||||
onUrlChange.mockClear();
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
|
|
||||||
expect(onUrlChange).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is a no-op after destroy', () => {
|
|
||||||
const onImageReady = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onImageReady });
|
|
||||||
|
|
||||||
loader.destroy();
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
|
|
||||||
expect(onImageReady).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('onError', () => {
|
|
||||||
it('sets quality to error and clears URL', () => {
|
|
||||||
const onError = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onError });
|
|
||||||
|
|
||||||
loader.onError('thumbnail');
|
|
||||||
|
|
||||||
expect(loader.status.quality.thumbnail).toBe('error');
|
|
||||||
expect(loader.status.urls.thumbnail).toBeUndefined();
|
|
||||||
expect(loader.status.hasError).toBe(true);
|
|
||||||
expect(onError).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls onAfterError callback', () => {
|
|
||||||
const onAfterError = vi.fn();
|
|
||||||
const qualityList = createQualityList({ onAfterError: { thumbnail: onAfterError } });
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList);
|
|
||||||
|
|
||||||
loader.onError('thumbnail');
|
|
||||||
|
|
||||||
expect(onAfterError).toHaveBeenCalledWith(loader);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is a no-op after destroy', () => {
|
|
||||||
const onError = vi.fn();
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), { onError });
|
|
||||||
|
|
||||||
loader.destroy();
|
|
||||||
loader.onError('thumbnail');
|
|
||||||
|
|
||||||
expect(onError).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('trigger', () => {
|
|
||||||
it('sets the URL for the quality', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
loader.trigger('preview');
|
|
||||||
|
|
||||||
expect(loader.status.urls.preview).toBe('/preview.jpg');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns true if URL is already set', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
expect(loader.trigger('thumbnail')).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns false when triggering a new quality', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
expect(loader.trigger('preview')).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('clears hasError when triggering', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
loader.onError('thumbnail');
|
|
||||||
expect(loader.status.hasError).toBe(true);
|
|
||||||
|
|
||||||
loader.trigger('preview');
|
|
||||||
expect(loader.status.hasError).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls imageLoader when provided', () => {
|
|
||||||
const imageLoader = vi.fn(() => vi.fn());
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), undefined, imageLoader);
|
|
||||||
|
|
||||||
loader.trigger('preview');
|
|
||||||
|
|
||||||
expect(imageLoader).toHaveBeenCalledWith(
|
|
||||||
'/preview.jpg',
|
|
||||||
expect.any(Function),
|
|
||||||
expect.any(Function),
|
|
||||||
expect.any(Function),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns false after destroy', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
loader.destroy();
|
|
||||||
|
|
||||||
expect(loader.trigger('preview')).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls onAfterError if URL is empty', () => {
|
|
||||||
const onAfterError = vi.fn();
|
|
||||||
const qualityList = createQualityList({ onAfterError: { preview: onAfterError } });
|
|
||||||
(qualityList[1] as { url: string }).url = '';
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList);
|
|
||||||
|
|
||||||
expect(loader.trigger('preview')).toBe(false);
|
|
||||||
expect(onAfterError).toHaveBeenCalledWith(loader);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('start', () => {
|
|
||||||
it('throws if no imageLoader is provided', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
expect(() => loader.start()).toThrow('Start requires imageLoader to be specified');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls imageLoader with thumbnail URL', () => {
|
|
||||||
const imageLoader = vi.fn(() => vi.fn());
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), undefined, imageLoader);
|
|
||||||
|
|
||||||
loader.start();
|
|
||||||
|
|
||||||
expect(imageLoader).toHaveBeenCalledWith(
|
|
||||||
'/thumbnail.jpg',
|
|
||||||
expect.any(Function),
|
|
||||||
expect.any(Function),
|
|
||||||
expect.any(Function),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('destroy', () => {
|
|
||||||
it('cancels all image URLs when no imageLoader', () => {
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList());
|
|
||||||
|
|
||||||
loader.destroy();
|
|
||||||
|
|
||||||
expect(cancelImageUrl).toHaveBeenCalledWith('/thumbnail.jpg');
|
|
||||||
expect(cancelImageUrl).toHaveBeenCalledWith('/preview.jpg');
|
|
||||||
expect(cancelImageUrl).toHaveBeenCalledWith('/original.jpg');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls destroy functions when imageLoader is provided', () => {
|
|
||||||
const destroyFn = vi.fn();
|
|
||||||
const imageLoader = vi.fn(() => destroyFn);
|
|
||||||
const loader = new AdaptiveImageLoader(createQualityList(), undefined, imageLoader);
|
|
||||||
|
|
||||||
loader.start();
|
|
||||||
loader.destroy();
|
|
||||||
|
|
||||||
expect(destroyFn).toHaveBeenCalledOnce();
|
|
||||||
expect(cancelImageUrl).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('progressive loading flow', () => {
|
|
||||||
it('thumbnail load triggers preview via onAfterLoad', () => {
|
|
||||||
const triggerSpy = vi.fn();
|
|
||||||
const qualityList = createQualityList({
|
|
||||||
onAfterLoad: {
|
|
||||||
thumbnail: (loader) => {
|
|
||||||
triggerSpy();
|
|
||||||
loader.trigger('preview');
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList);
|
|
||||||
|
|
||||||
loader.onLoad('thumbnail');
|
|
||||||
|
|
||||||
expect(triggerSpy).toHaveBeenCalledOnce();
|
|
||||||
expect(loader.status.urls.preview).toBe('/preview.jpg');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('thumbnail error triggers preview via onAfterError', () => {
|
|
||||||
const qualityList = createQualityList({
|
|
||||||
onAfterError: {
|
|
||||||
thumbnail: (loader) => loader.trigger('preview'),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const loader = new AdaptiveImageLoader(qualityList);
|
|
||||||
|
|
||||||
loader.onError('thumbnail');
|
|
||||||
|
|
||||||
expect(loader.status.urls.preview).toBe('/preview.jpg');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
import type { LoadImageFunction } from '$lib/actions/image-loader.svelte';
|
|
||||||
import { cancelImageUrl } from '$lib/utils/sw-messaging';
|
|
||||||
|
|
||||||
export type ImageQuality = 'thumbnail' | 'preview' | 'original';
|
|
||||||
|
|
||||||
export type ImageStatus = 'unloaded' | 'success' | 'error';
|
|
||||||
|
|
||||||
export type ImageLoaderStatus = {
|
|
||||||
urls: Record<ImageQuality, string | undefined>;
|
|
||||||
quality: Record<ImageQuality, ImageStatus>;
|
|
||||||
started: boolean;
|
|
||||||
hasError: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ImageLoaderCallbacks = {
|
|
||||||
onUrlChange?: (url: string) => void;
|
|
||||||
onImageReady?: () => void;
|
|
||||||
onError?: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type QualityConfig = {
|
|
||||||
url: string;
|
|
||||||
quality: ImageQuality;
|
|
||||||
onAfterLoad?: (loader: AdaptiveImageLoader) => void;
|
|
||||||
onAfterError?: (loader: AdaptiveImageLoader) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type QualityList = [
|
|
||||||
QualityConfig & { quality: 'thumbnail' },
|
|
||||||
QualityConfig & { quality: 'preview' },
|
|
||||||
QualityConfig & { quality: 'original' },
|
|
||||||
];
|
|
||||||
|
|
||||||
export class AdaptiveImageLoader {
|
|
||||||
private destroyFunctions: (() => void)[] = [];
|
|
||||||
private qualityConfigs: Record<ImageQuality, QualityConfig>;
|
|
||||||
private highestLoadedQualityIndex = -1;
|
|
||||||
private destroyed = false;
|
|
||||||
|
|
||||||
status = $state<ImageLoaderStatus>({
|
|
||||||
started: false,
|
|
||||||
hasError: false,
|
|
||||||
urls: { thumbnail: undefined, preview: undefined, original: undefined },
|
|
||||||
quality: { thumbnail: 'unloaded', preview: 'unloaded', original: 'unloaded' },
|
|
||||||
});
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly qualityList: QualityList,
|
|
||||||
private readonly callbacks?: ImageLoaderCallbacks,
|
|
||||||
private readonly imageLoader?: LoadImageFunction,
|
|
||||||
) {
|
|
||||||
this.qualityConfigs = {
|
|
||||||
thumbnail: qualityList[0],
|
|
||||||
preview: qualityList[1],
|
|
||||||
original: qualityList[2],
|
|
||||||
};
|
|
||||||
this.status.urls.thumbnail = qualityList[0].url;
|
|
||||||
}
|
|
||||||
|
|
||||||
start() {
|
|
||||||
if (!this.imageLoader) {
|
|
||||||
throw new Error('Start requires imageLoader to be specified');
|
|
||||||
}
|
|
||||||
|
|
||||||
this.destroyFunctions.push(
|
|
||||||
this.imageLoader(
|
|
||||||
this.qualityList[0].url,
|
|
||||||
() => this.onLoad('thumbnail'),
|
|
||||||
() => this.onError('thumbnail'),
|
|
||||||
() => this.onStart('thumbnail'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
onStart(_: ImageQuality) {
|
|
||||||
if (this.destroyed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.status.started = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
onLoad(quality: ImageQuality) {
|
|
||||||
if (this.destroyed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = this.qualityConfigs[quality];
|
|
||||||
|
|
||||||
if (!this.status.urls[quality]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const index = this.qualityList.indexOf(config);
|
|
||||||
if (index <= this.highestLoadedQualityIndex) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.highestLoadedQualityIndex = index;
|
|
||||||
this.status.quality[quality] = 'success';
|
|
||||||
this.callbacks?.onUrlChange?.(this.qualityConfigs[quality].url);
|
|
||||||
this.callbacks?.onImageReady?.();
|
|
||||||
|
|
||||||
config.onAfterLoad?.(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
onError(quality: ImageQuality) {
|
|
||||||
if (this.destroyed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = this.qualityConfigs[quality];
|
|
||||||
|
|
||||||
this.status.hasError = true;
|
|
||||||
this.status.quality[quality] = 'error';
|
|
||||||
this.status.urls[quality] = undefined;
|
|
||||||
this.callbacks?.onError?.();
|
|
||||||
|
|
||||||
config.onAfterError?.(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
trigger(quality: ImageQuality) {
|
|
||||||
if (this.destroyed) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = this.qualityConfigs[quality].url;
|
|
||||||
if (!url) {
|
|
||||||
this.qualityConfigs[quality].onAfterError?.(this);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.status.urls[quality]) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.status.hasError = false;
|
|
||||||
this.status.urls[quality] = url;
|
|
||||||
if (this.imageLoader) {
|
|
||||||
this.destroyFunctions.push(
|
|
||||||
this.imageLoader(
|
|
||||||
url,
|
|
||||||
() => this.onLoad(quality),
|
|
||||||
() => this.onError(quality),
|
|
||||||
() => this.onStart(quality),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy() {
|
|
||||||
this.destroyed = true;
|
|
||||||
if (this.imageLoader) {
|
|
||||||
for (const destroy of this.destroyFunctions) {
|
|
||||||
destroy();
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const config of Object.values(this.qualityConfigs)) {
|
|
||||||
cancelImageUrl(config.url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,19 +5,6 @@ export interface ContentMetrics {
|
|||||||
offsetY: number;
|
offsetY: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const scaleToCover = (
|
|
||||||
dimensions: { width: number; height: number },
|
|
||||||
container: { width: number; height: number },
|
|
||||||
): { width: number; height: number } => {
|
|
||||||
const scaleX = container.width / dimensions.width;
|
|
||||||
const scaleY = container.height / dimensions.height;
|
|
||||||
const scale = Math.max(scaleX, scaleY);
|
|
||||||
return {
|
|
||||||
width: dimensions.width * scale,
|
|
||||||
height: dimensions.height * scale,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const scaleToFit = (
|
export const scaleToFit = (
|
||||||
dimensions: { width: number; height: number },
|
dimensions: { width: number; height: number },
|
||||||
container: { width: number; height: number },
|
container: { width: number; height: number },
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
import { scaleToFit } from '$lib/utils/container-utils';
|
|
||||||
|
|
||||||
describe('scaleToFit', () => {
|
|
||||||
const tests = [
|
|
||||||
{
|
|
||||||
name: 'landscape image in square container',
|
|
||||||
dimensions: { width: 2000, height: 1000 },
|
|
||||||
container: { width: 500, height: 500 },
|
|
||||||
expected: { width: 500, height: 250 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'portrait image in square container',
|
|
||||||
dimensions: { width: 1000, height: 2000 },
|
|
||||||
container: { width: 500, height: 500 },
|
|
||||||
expected: { width: 250, height: 500 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'square image in square container',
|
|
||||||
dimensions: { width: 1000, height: 1000 },
|
|
||||||
container: { width: 500, height: 500 },
|
|
||||||
expected: { width: 500, height: 500 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'landscape image in landscape container',
|
|
||||||
dimensions: { width: 1600, height: 900 },
|
|
||||||
container: { width: 800, height: 600 },
|
|
||||||
expected: { width: 800, height: 450 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'portrait image in portrait container',
|
|
||||||
dimensions: { width: 900, height: 1600 },
|
|
||||||
container: { width: 600, height: 800 },
|
|
||||||
expected: { width: 450, height: 800 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'image matches container exactly',
|
|
||||||
dimensions: { width: 500, height: 300 },
|
|
||||||
container: { width: 500, height: 300 },
|
|
||||||
expected: { width: 500, height: 300 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'image smaller than container scales up',
|
|
||||||
dimensions: { width: 100, height: 50 },
|
|
||||||
container: { width: 400, height: 400 },
|
|
||||||
expected: { width: 400, height: 200 },
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const { name, dimensions, container, expected } of tests) {
|
|
||||||
it(`should handle ${name}`, () => {
|
|
||||||
expect(scaleToFit(dimensions, container)).toEqual(expected);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user