mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-06 00:32:26 -08:00
better detection, fallback, decompression limits
This commit is contained in:
1 parent
1c85c1b417
commit
0a2072437a
7 files changed
+306
-53
No files matched your search
@@ -1,10 +1,13 @@
|
||||
import type { ImgHTMLAttributes, PointerEvent, SyntheticEvent, WheelEvent } from 'react';
|
||||
import type { SyntheticEvent, WheelEvent } from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import FileSaver from 'file-saver';
|
||||
import { ImageViewer } from './ImageViewer';
|
||||
|
||||
const downloadMedia = vi.fn<(src: string) => Promise<Blob>>();
|
||||
const gestureMocks = vi.hoisted(() => ({
|
||||
onPointerDown: vi.fn<(event: React.PointerEvent) => void>(),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useImageGestures', () => ({
|
||||
useImageGestures: () => ({
|
||||
@@ -14,7 +17,7 @@ vi.mock('$hooks/useImageGestures', () => ({
|
||||
imageRef: { current: null },
|
||||
containerRef: { current: null },
|
||||
handleWheel: vi.fn<(event: WheelEvent) => void>(),
|
||||
onPointerDown: vi.fn<(event: PointerEvent) => void>(),
|
||||
onPointerDown: gestureMocks.onPointerDown,
|
||||
handleImageLoad: vi.fn<(event: SyntheticEvent<HTMLImageElement>) => void>(),
|
||||
setZoom: vi.fn<(next: number) => void>(),
|
||||
resetTransforms: vi.fn<() => void>(),
|
||||
@@ -61,9 +64,25 @@ describe('ImageViewer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock('$components/media', () => ({
|
||||
Image: ({ alt, ...props }: ImgHTMLAttributes<HTMLImageElement>) => <img alt={alt} {...props} />,
|
||||
}));
|
||||
vi.mock('$components/media', async () => {
|
||||
const { forwardRef } = await import('react');
|
||||
return {
|
||||
Image: forwardRef<
|
||||
HTMLImageElement | HTMLCanvasElement,
|
||||
React.ImgHTMLAttributes<HTMLImageElement> & { info?: { mimetype?: string } }
|
||||
>(({ alt, info, ...props }, ref) =>
|
||||
info?.mimetype === 'application/x-tgsticker' ? (
|
||||
<canvas
|
||||
aria-label={alt}
|
||||
{...(props as React.CanvasHTMLAttributes<HTMLCanvasElement>)}
|
||||
ref={ref as React.ForwardedRef<HTMLCanvasElement>}
|
||||
/>
|
||||
) : (
|
||||
<img alt={alt} {...props} ref={ref as React.ForwardedRef<HTMLImageElement>} />
|
||||
)
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
describe('ImageViewer', () => {
|
||||
it('renders the fullscreen image without crashing', () => {
|
||||
@@ -71,4 +90,21 @@ describe('ImageViewer', () => {
|
||||
|
||||
expect(screen.getByAltText('demo')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('starts viewer gestures from the rendered lottie canvas', () => {
|
||||
gestureMocks.onPointerDown.mockClear();
|
||||
render(
|
||||
<ImageViewer
|
||||
alt="animated sticker"
|
||||
src="https://example.com/sticker"
|
||||
info={{ mimetype: 'application/x-tgsticker' }}
|
||||
requestClose={() => {}}
|
||||
/>
|
||||
);
|
||||
|
||||
const canvas = screen.getByLabelText('animated sticker');
|
||||
expect(canvas.tagName).toBe('CANVAS');
|
||||
fireEvent.pointerDown(canvas);
|
||||
expect(gestureMocks.onPointerDown).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -322,6 +322,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
onTouchCancel={menu.triggerProps.onTouchCancel}
|
||||
>
|
||||
<MediaImage
|
||||
ref={imageRef}
|
||||
className={classNames(css.ImageViewerImg, isPixelated && css.ImageViewerImgPixelated)}
|
||||
draggable={false}
|
||||
data-gestures="ignore"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { createRef } from 'react';
|
||||
import { Image, sanitizeLottieJson } from './Image';
|
||||
import { Blob as NodeBlob } from 'node:buffer';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
@@ -64,6 +65,84 @@ describe('Image', () => {
|
||||
expect(rendered).toHaveAttribute('height', '123');
|
||||
});
|
||||
|
||||
it('forwards the canvas ref and pointer events for lottie images', async () => {
|
||||
const gzipped = Buffer.from(gzipSync(lottieJson)).toString('base64');
|
||||
const ref = createRef<HTMLImageElement | HTMLCanvasElement>();
|
||||
const onPointerDown = vi.fn<(event: React.PointerEvent<HTMLElement>) => void>();
|
||||
render(
|
||||
<Image
|
||||
ref={ref}
|
||||
src={`data:application/gzip;base64,${gzipped}`}
|
||||
aria-label="interactive lottie"
|
||||
onPointerDown={onPointerDown}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('interactive lottie').tagName).toBe('CANVAS');
|
||||
});
|
||||
const canvas = screen.getByLabelText('interactive lottie');
|
||||
fireEvent.pointerDown(canvas);
|
||||
|
||||
expect(canvas.tagName).toBe('CANVAS');
|
||||
await waitFor(() => expect(ref.current).toBe(canvas));
|
||||
expect(onPointerDown).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('probes an undeclared lottie only after native image decoding fails', async () => {
|
||||
const bytes = Uint8Array.from(gzipSync(lottieJson));
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValue(new Response(bytes, { headers: { 'content-length': `${bytes.length}` } }));
|
||||
render(<Image src="https://example.com/extensionless-media" alt="undeclared lottie" />);
|
||||
|
||||
const image = screen.getByAltText('undeclared lottie');
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
fireEvent.error(image);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('undeclared lottie').tagName).toBe('CANVAS');
|
||||
});
|
||||
expect(fetchSpy).toHaveBeenCalledOnce();
|
||||
fetchSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('aborts an in-flight lottie download when unmounted', async () => {
|
||||
let requestSignal: AbortSignal | undefined;
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((_input, init) => {
|
||||
requestSignal = init?.signal ?? undefined;
|
||||
return new Promise<Response>(() => {});
|
||||
});
|
||||
const { unmount } = render(
|
||||
<Image src="https://example.com/sticker.tgs" alt="loading lottie" />
|
||||
);
|
||||
|
||||
await waitFor(() => expect(requestSignal).toBeDefined());
|
||||
unmount();
|
||||
|
||||
expect(requestSignal?.aborted).toBe(true);
|
||||
fetchSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('rejects lottie data that exceeds the decompressed size limit', async () => {
|
||||
const oversizedJson = JSON.stringify({
|
||||
v: '5.11.0',
|
||||
padding: 'a'.repeat(8 * 1024 * 1024),
|
||||
});
|
||||
const gzipped = Buffer.from(gzipSync(oversizedJson)).toString('base64');
|
||||
render(
|
||||
<Image
|
||||
src={`data:application/gzip;base64,${gzipped}`}
|
||||
alt="oversized lottie"
|
||||
onError={() => {}}
|
||||
/>
|
||||
);
|
||||
|
||||
const image = screen.getByAltText('oversized lottie');
|
||||
await waitFor(() => expect(image).toHaveAttribute('src'));
|
||||
expect(image.tagName).toBe('IMG');
|
||||
});
|
||||
|
||||
it('forwards a candidate fallback error after detection fails', async () => {
|
||||
let errorTarget: EventTarget | null = null;
|
||||
const onError = vi.fn<(event: React.SyntheticEvent<HTMLImageElement>) => void>((event) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ComponentProps, ImgHTMLAttributes } from 'react';
|
||||
import type { ComponentProps, ForwardedRef, ImgHTMLAttributes, PointerEventHandler } from 'react';
|
||||
import { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import type { DotLottieReact as DotLottieReactComponent } from '@lottiefiles/dotlottie-react';
|
||||
@@ -7,18 +7,19 @@ import { isPixelatedRendering, settingsAtom } from '$state/settings';
|
||||
import * as css from './media.css';
|
||||
import type { IImageInfo } from '$types/matrix/common';
|
||||
|
||||
type ImageProps = ImgHTMLAttributes<HTMLImageElement> & {
|
||||
type ImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, 'onPointerDown'> & {
|
||||
info?: IImageInfo;
|
||||
mimeType?: string;
|
||||
disablePixelation?: boolean;
|
||||
pixelated?: boolean;
|
||||
onLottieLoad?: (canvas?: HTMLCanvasElement) => void;
|
||||
onLottieError?: () => void;
|
||||
onPointerDown?: PointerEventHandler<HTMLElement>;
|
||||
};
|
||||
|
||||
type LottieDotProps = Omit<
|
||||
ComponentProps<typeof DotLottieReactComponent>,
|
||||
'src' | 'alt' | 'loading'
|
||||
'src' | 'alt' | 'loading' | 'onPointerDown'
|
||||
>;
|
||||
type DotLottieInstance = Parameters<
|
||||
NonNullable<ComponentProps<typeof DotLottieReactComponent>['dotLottieRefCallback']>
|
||||
@@ -31,6 +32,11 @@ const DotLottieReact = lazy(() =>
|
||||
) as typeof DotLottieReactComponent;
|
||||
|
||||
const GZIPPED_LOTTIE_MIME = /^application\/(?:(?:x-)?gzip|x-tgsticker)(?:;|$)/i;
|
||||
const MAX_COMPRESSED_LOTTIE_BYTES = 1024 * 1024;
|
||||
const MAX_DECOMPRESSED_LOTTIE_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_LOTTIE_DIMENSION = 4096;
|
||||
const MAX_LOTTIE_FRAMES = 10_000;
|
||||
const MAX_LOTTIE_LAYERS = 1_000;
|
||||
const UNSAFE_LOTTIE_KEYS = new Set([
|
||||
'expression',
|
||||
'expressions',
|
||||
@@ -66,28 +72,109 @@ function isGzippedLottieCandidate(
|
||||
);
|
||||
}
|
||||
|
||||
async function loadBytes(src: string): Promise<Uint8Array | null> {
|
||||
async function readBytes(
|
||||
stream: ReadableStream<Uint8Array>,
|
||||
limit: number,
|
||||
signal: AbortSignal
|
||||
): Promise<Uint8Array> {
|
||||
const reader = stream.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
let completed = false;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
if (signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
// Stream chunks must be consumed sequentially to enforce the running byte limit.
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
completed = true;
|
||||
break;
|
||||
}
|
||||
size += value.byteLength;
|
||||
if (size > limit) throw new Error('Lottie data exceeds the size limit');
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
if (!completed) await reader.cancel().catch(() => undefined);
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(size);
|
||||
let offset = 0;
|
||||
chunks.forEach((chunk) => {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
});
|
||||
return bytes;
|
||||
}
|
||||
|
||||
async function loadBytes(src: string, signal: AbortSignal): Promise<Uint8Array | null> {
|
||||
const encoded = src.match(/^data:[^;,]*;base64,(.+)$/i)?.[1];
|
||||
if (encoded) {
|
||||
if (encoded.length > Math.ceil((MAX_COMPRESSED_LOTTIE_BYTES * 4) / 3) + 4) return null;
|
||||
return Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0));
|
||||
}
|
||||
|
||||
const response = await fetch(src, { credentials: 'include' });
|
||||
return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
|
||||
const response = await fetch(src, { credentials: 'include', signal });
|
||||
if (!response.ok || !response.body) return null;
|
||||
const contentLength = Number(response.headers.get('content-length'));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_COMPRESSED_LOTTIE_BYTES) return null;
|
||||
return readBytes(response.body, MAX_COMPRESSED_LOTTIE_BYTES, signal);
|
||||
}
|
||||
|
||||
async function resolveLottieDataUrl(src: string): Promise<string | null> {
|
||||
function hasSafeLottieComplexity(value: unknown): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || !('v' in value)) return false;
|
||||
const lottie = value as Record<string, unknown>;
|
||||
const width = Number(lottie.w);
|
||||
const height = Number(lottie.h);
|
||||
const firstFrame = Number(lottie.ip);
|
||||
const lastFrame = Number(lottie.op);
|
||||
if (
|
||||
(Number.isFinite(width) && (width <= 0 || width > MAX_LOTTIE_DIMENSION)) ||
|
||||
(Number.isFinite(height) && (height <= 0 || height > MAX_LOTTIE_DIMENSION)) ||
|
||||
(Number.isFinite(firstFrame) &&
|
||||
Number.isFinite(lastFrame) &&
|
||||
(lastFrame <= firstFrame || lastFrame - firstFrame > MAX_LOTTIE_FRAMES))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let layerCount = 0;
|
||||
const pending: unknown[] = [value];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (!current || typeof current !== 'object') continue;
|
||||
if (Array.isArray(current)) {
|
||||
pending.push(...current);
|
||||
continue;
|
||||
}
|
||||
Object.entries(current).forEach(([key, child]) => {
|
||||
if (key === 'layers' && Array.isArray(child)) {
|
||||
layerCount += child.length;
|
||||
}
|
||||
pending.push(child);
|
||||
});
|
||||
if (layerCount > MAX_LOTTIE_LAYERS) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function resolveLottieDataUrl(src: string, signal: AbortSignal): Promise<string | null> {
|
||||
try {
|
||||
const bytes = await loadBytes(src);
|
||||
const bytes = await loadBytes(src, signal);
|
||||
if (!bytes || bytes[0] !== 0x1f || bytes[1] !== 0x8b) return null;
|
||||
|
||||
const stream = new Blob([bytes.buffer as ArrayBuffer])
|
||||
.stream()
|
||||
.pipeThrough(new DecompressionStream('gzip'));
|
||||
const jsonText = await new Response(stream).text();
|
||||
const json = sanitizeLottieJson(JSON.parse(jsonText));
|
||||
const decompressed = await readBytes(stream, MAX_DECOMPRESSED_LOTTIE_BYTES, signal);
|
||||
const parsed = JSON.parse(new TextDecoder().decode(decompressed));
|
||||
if (!hasSafeLottieComplexity(parsed)) return null;
|
||||
const json = sanitizeLottieJson(parsed);
|
||||
const safeJsonText = JSON.stringify(json);
|
||||
return json && typeof json === 'object' && 'v' in json && safeJsonText
|
||||
return safeJsonText
|
||||
? `data:application/json;charset=utf-8,${encodeURIComponent(safeJsonText)}`
|
||||
: null;
|
||||
} catch {
|
||||
@@ -101,6 +188,8 @@ type LottieImageProps = LottieDotProps & {
|
||||
onLottieLoad?: (canvas?: HTMLCanvasElement) => void;
|
||||
onLottieError?: () => void;
|
||||
pixelated?: boolean;
|
||||
forwardedRef?: ForwardedRef<HTMLImageElement | HTMLCanvasElement>;
|
||||
onPointerDown?: PointerEventHandler<HTMLElement>;
|
||||
};
|
||||
|
||||
function LottieImage({
|
||||
@@ -110,6 +199,8 @@ function LottieImage({
|
||||
onLottieLoad,
|
||||
onLottieError,
|
||||
pixelated,
|
||||
forwardedRef,
|
||||
onPointerDown,
|
||||
...props
|
||||
}: Readonly<LottieImageProps>) {
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
@@ -117,27 +208,52 @@ function LottieImage({
|
||||
const pixelation = useRef(pixelated);
|
||||
callbacks.current = { onLottieLoad, onLottieError };
|
||||
pixelation.current = pixelated;
|
||||
const setForwardedRef = useCallback(
|
||||
(canvas: HTMLCanvasElement | null) => {
|
||||
if (typeof forwardedRef === 'function') forwardedRef(canvas);
|
||||
else if (forwardedRef) forwardedRef.current = canvas;
|
||||
},
|
||||
[forwardedRef]
|
||||
);
|
||||
useEffect(() => {
|
||||
const updateRef = () => {
|
||||
const canvas = wrapperRef.current?.querySelector('canvas') ?? null;
|
||||
if (canvas) setForwardedRef(canvas);
|
||||
};
|
||||
updateRef();
|
||||
const observer = new MutationObserver(updateRef);
|
||||
if (wrapperRef.current)
|
||||
observer.observe(wrapperRef.current, { childList: true, subtree: true });
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
setForwardedRef(null);
|
||||
};
|
||||
}, [setForwardedRef]);
|
||||
useEffect(() => {
|
||||
const canvas = wrapperRef.current?.querySelector('canvas');
|
||||
if (canvas) canvas.style.imageRendering = pixelated ? 'pixelated' : 'auto';
|
||||
}, [pixelated]);
|
||||
const handlePlayer = useCallback((player: DotLottieInstance) => {
|
||||
if (!player) return;
|
||||
let didLoad = false;
|
||||
const handleLoad = () => {
|
||||
if (didLoad) return;
|
||||
didLoad = true;
|
||||
(player.canvas as HTMLCanvasElement).style.imageRendering = pixelation.current
|
||||
? 'pixelated'
|
||||
: 'auto';
|
||||
callbacks.current.onLottieLoad?.(player.canvas as HTMLCanvasElement);
|
||||
};
|
||||
const handleError = () => callbacks.current.onLottieError?.();
|
||||
const handlePlayer = useCallback(
|
||||
(player: DotLottieInstance) => {
|
||||
if (!player) return;
|
||||
let didLoad = false;
|
||||
const handleLoad = () => {
|
||||
if (didLoad) return;
|
||||
didLoad = true;
|
||||
(player.canvas as HTMLCanvasElement).style.imageRendering = pixelation.current
|
||||
? 'pixelated'
|
||||
: 'auto';
|
||||
callbacks.current.onLottieLoad?.(player.canvas as HTMLCanvasElement);
|
||||
setForwardedRef(player.canvas as HTMLCanvasElement);
|
||||
};
|
||||
const handleError = () => callbacks.current.onLottieError?.();
|
||||
|
||||
player.addEventListener('load', handleLoad);
|
||||
player.addEventListener('loadError', handleError);
|
||||
if (player.isLoaded) handleLoad();
|
||||
}, []);
|
||||
player.addEventListener('load', handleLoad);
|
||||
player.addEventListener('loadError', handleError);
|
||||
if (player.isLoaded) handleLoad();
|
||||
},
|
||||
[setForwardedRef]
|
||||
);
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
@@ -145,6 +261,7 @@ function LottieImage({
|
||||
ref={wrapperRef}
|
||||
className={className}
|
||||
style={{ width: '100%', height: '100%', ...style }}
|
||||
onPointerDown={onPointerDown}
|
||||
>
|
||||
<DotLottieReact
|
||||
{...props}
|
||||
@@ -157,7 +274,7 @@ function LottieImage({
|
||||
);
|
||||
}
|
||||
|
||||
export const Image = forwardRef<HTMLImageElement, ImageProps>(
|
||||
export const Image = forwardRef<HTMLImageElement | HTMLCanvasElement, ImageProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
@@ -183,16 +300,18 @@ export const Image = forwardRef<HTMLImageElement, ImageProps>(
|
||||
source: string;
|
||||
resolved: string | null;
|
||||
}>();
|
||||
const [fallbackSource, setFallbackSource] = useState<string>();
|
||||
|
||||
const lottieProps = props as LottieDotProps;
|
||||
const isLottieCandidate = isGzippedLottieCandidate(
|
||||
const declaredLottieCandidate = isGzippedLottieCandidate(
|
||||
src,
|
||||
mimeType ?? info?.mimetype,
|
||||
typeof props.title === 'string' ? props.title : alt
|
||||
);
|
||||
const isLottieCandidate = declaredLottieCandidate || fallbackSource === src;
|
||||
const resolvedLottieSrc =
|
||||
isLottieCandidate && lottieResolution?.source === src
|
||||
? lottieResolution.resolved
|
||||
? (lottieResolution?.resolved ?? null)
|
||||
: isLottieCandidate
|
||||
? undefined
|
||||
: null;
|
||||
@@ -205,21 +324,23 @@ export const Image = forwardRef<HTMLImageElement, ImageProps>(
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const controller = new AbortController();
|
||||
|
||||
if (isLottieCandidate) {
|
||||
void resolveLottieDataUrl(src).then((result) => {
|
||||
if (!cancelled) {
|
||||
if (isLottieCandidate && src) {
|
||||
void resolveLottieDataUrl(src, controller.signal).then((result) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLottieResolution({ source: src, resolved: result });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
return () => controller.abort();
|
||||
}, [isLottieCandidate, src]);
|
||||
|
||||
useEffect(() => {
|
||||
setFallbackSource(undefined);
|
||||
}, [src]);
|
||||
|
||||
const shouldRenderLottie = typeof resolvedLottieSrc === 'string';
|
||||
|
||||
if (shouldRenderLottie) {
|
||||
@@ -232,6 +353,8 @@ export const Image = forwardRef<HTMLImageElement, ImageProps>(
|
||||
alt={alt}
|
||||
onLottieLoad={onLottieLoad}
|
||||
onLottieError={onLottieError}
|
||||
forwardedRef={ref}
|
||||
onPointerDown={onPointerDown}
|
||||
pixelated={
|
||||
!disablePixelation && (pixelated ?? isPixelatedRendering(pixelatedImageRendering, info))
|
||||
}
|
||||
@@ -251,9 +374,15 @@ export const Image = forwardRef<HTMLImageElement, ImageProps>(
|
||||
style={style}
|
||||
onLoad={onLoad}
|
||||
onPointerDown={onPointerDown}
|
||||
onError={onError}
|
||||
onError={(event) => {
|
||||
if (!declaredLottieCandidate && fallbackSource !== src) {
|
||||
setFallbackSource(src);
|
||||
return;
|
||||
}
|
||||
onError?.(event);
|
||||
}}
|
||||
{...props}
|
||||
ref={ref}
|
||||
ref={ref as ForwardedRef<HTMLImageElement>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export const useImageGestures = (active: boolean, step = 0.2, min = 0.1, max = 5
|
||||
const shouldResizeWithWindowRef = useRef(true);
|
||||
const [fitRatio, setFitRatio] = useState(1);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const imageRef = useRef<HTMLImageElement | null>(null);
|
||||
const imageRef = useRef<HTMLImageElement | HTMLCanvasElement | null>(null);
|
||||
|
||||
const setShouldResizeWithWindow = useCallback((next: boolean) => {
|
||||
shouldResizeWithWindowRef.current = next;
|
||||
@@ -229,13 +229,15 @@ export const useImageGestures = (active: boolean, step = 0.2, min = 0.1, max = 5
|
||||
if (
|
||||
!img || // Image not loaded
|
||||
!shouldResizeWithWindowRef.current || // Resizing disabled
|
||||
!img.naturalWidth ||
|
||||
!img.naturalHeight // Invalid image dimensions
|
||||
!(img instanceof HTMLCanvasElement ? img.width : img.naturalWidth) ||
|
||||
!(img instanceof HTMLCanvasElement ? img.height : img.naturalHeight) // Invalid dimensions
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const heightRatio = height / img.naturalHeight;
|
||||
const widthRatio = width / img.naturalWidth;
|
||||
const imageHeight = img instanceof HTMLCanvasElement ? img.height : img.naturalHeight;
|
||||
const imageWidth = img instanceof HTMLCanvasElement ? img.width : img.naturalWidth;
|
||||
const heightRatio = height / imageHeight;
|
||||
const widthRatio = width / imageWidth;
|
||||
const fitZoom = Math.min(heightRatio, widthRatio);
|
||||
|
||||
img.style.transition = 'none';
|
||||
|
||||
@@ -66,6 +66,15 @@ describe('TGS uploads', () => {
|
||||
expect(upload.type).toBe(FALLBACK_MIMETYPE);
|
||||
expect(isImageMimeType(upload.type)).toBe(false);
|
||||
});
|
||||
|
||||
it('does not treat an ordinary gzip archive as a TGS image', async () => {
|
||||
const archive = new File([tgsBytes], 'archive.tar.gz', { type: 'application/gzip' });
|
||||
const upload = await safeUploadFile(archive);
|
||||
|
||||
expect(await isTgsFile(archive)).toBe(false);
|
||||
expect(upload.type).toBe(FALLBACK_MIMETYPE);
|
||||
expect(isImageMimeType(upload.type)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mimeTypeToExt', () => {
|
||||
|
||||
@@ -109,8 +109,6 @@ const ALLOWED_BLOB_MIME_TYPES = new Set([
|
||||
export const FALLBACK_MIMETYPE = 'application/octet-stream';
|
||||
export const TGS_MIMETYPE = 'application/x-tgsticker';
|
||||
|
||||
const GZIP_MIME_TYPES = new Set(['application/gzip', 'application/x-gzip', TGS_MIMETYPE]);
|
||||
|
||||
export const isTgsMimeType = (mimeType: string): boolean =>
|
||||
mimeType.split(';', 1)[0]?.toLowerCase() === TGS_MIMETYPE;
|
||||
|
||||
@@ -118,8 +116,7 @@ export const isImageMimeType = (mimeType: string): boolean =>
|
||||
mimeType.toLowerCase().startsWith('image/') || isTgsMimeType(mimeType);
|
||||
|
||||
const isTgsCandidate = (file: File): boolean =>
|
||||
file.name.toLowerCase().endsWith('.tgs') ||
|
||||
GZIP_MIME_TYPES.has(file.type.split(';', 1)[0]?.toLowerCase() ?? '');
|
||||
file.name.toLowerCase().endsWith('.tgs') || isTgsMimeType(file.type);
|
||||
|
||||
export const isTgsFile = async (file: File): Promise<boolean> => {
|
||||
if (!isTgsCandidate(file)) return false;
|
||||
|
||||
Reference in new issue
Block a user