🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(resource): paint a ThumbHash placeholder while library images load (#23747)
Arvin Xu2d1bf9b34312
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex d062a248ac0..b25212fea6f 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -809,6 +809,9 @@ importers:superjson:specifier: ^2.2.6version: 2.2.6+ thumbhash:+ specifier: ^0.1.1+ version: 0.1.1tldts:specifier: ^7.4.18version: 7.4.18@@ -7727,6 +7730,9 @@ packages:resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}+ resolution: {integrity: sha512-kH5pKeIIBPQXAOni2AiY/Cu/NKdkFREdpH+TLdM0g6WA7RriCv0kPLgP731ady67MhTAqrVG/4mnEeibVuCJcg==}+resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}@@ -15709,6 +15715,8 @@ snapshots:dependencies:any-promise: 1.3.0+ [email protected]: {}+dependencies:semver: 5.7.2diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.tsindex d49df0234a3..0e4149fb1a5 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -179,6 +179,11 @@ export const FileMetadataSchema = z.object({* consumers can group/reserve layout by orientation without recomputing*/ratio: z.number().optional(),+ /**+ * base64 ThumbHash of the image, recorded for images so consumers can paint a+ * blurred placeholder before the file loads+ */+ thumbhash: z.string().optional(),/*** intrinsic image width in pixels, recorded for images*/diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex 5950290155e..08e23b715b5 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -39,6 +39,7 @@"remark-gfm": "^4.0.1","remark-html": "^16.0.1","superjson": "^2.2.6",+ "thumbhash": "^0.1.1","tldts": "^7.4.18","tokenx": "^1.3.0","ua-parser-js": "^1.0.41",diff --git a/packages/utils/src/client/imageThumbhash.test.ts b/packages/utils/src/client/imageThumbhash.test.tsnew file mode 100644index 00000000000..4f82f6431fa--- /dev/null+++ b/packages/utils/src/client/imageThumbhash.test.ts@@ -0,0 +1,37 @@+import { rgbaToThumbHash } from 'thumbhash';+import { describe, expect, it } from 'vitest';++import { getImageThumbhash, thumbhashToDataUrl } from './imageThumbhash';++const solidHash = () => {+ const rgba = new Uint8Array(4 * 4 * 4).fill(200);+ return btoa(String.fromCodePoint(...rgbaToThumbHash(4, 4, rgba)));+};++describe('getImageThumbhash', () => {+ it('skips files that are not images', async () => {+ await expect(+ getImageThumbhash(new File(['x'], 'notes.txt', { type: 'text/plain' })),+ ).resolves.toBeUndefined();+ });++ it('skips data URIs that are not images', async () => {+ await expect(getImageThumbhash('data:text/plain;base64,eA==')).resolves.toBeUndefined();+ });++ it('resolves to undefined when the image cannot be decoded', async () => {+ await expect(+ getImageThumbhash(new File(['not a png'], 'broken.png', { type: 'image/png' })),+ ).resolves.toBeUndefined();+ });+});++describe('thumbhashToDataUrl', () => {+ it('decodes a base64 ThumbHash into a PNG data URL', () => {+ expect(thumbhashToDataUrl(solidHash())).toMatch(/^data:image\/png;base64,/);+ });++ it('returns undefined for a malformed hash', () => {+ expect(thumbhashToDataUrl('***')).toBeUndefined();+ });+});diff --git a/packages/utils/src/client/imageThumbhash.ts b/packages/utils/src/client/imageThumbhash.tsnew file mode 100644index 00000000000..f3e182a6213--- /dev/null+++ b/packages/utils/src/client/imageThumbhash.ts@@ -0,0 +1,55 @@+import { rgbaToThumbHash, thumbHashToDataURL } from 'thumbhash';++/** ThumbHash encodes images up to 100px on the longer side. */+const MAX_SIDE = 100;++const toBase64 = (bytes: Uint8Array) => btoa(String.fromCodePoint(...bytes));++const fromBase64 = (value: string) => Uint8Array.from(atob(value), (char) => char.codePointAt(0)!);++/**+ * Encodes an image — a File or a base64 data URI — as a base64 ThumbHash: a ~25-byte placeholder+ * that a viewer can paint before the image itself has loaded. Resolves to undefined for non-images+ * and for formats the browser cannot decode into a bitmap; callers treat the hash as best-effort.+ */+export const getImageThumbhash = async (source: File | string): Promise<string | undefined> => {+ if (+ typeof source === 'string'+ ? !source.startsWith('data:image/')+ : !source.type.startsWith('image/')+ )+ return undefined;++ try {+ const blob = typeof source === 'string' ? await (await fetch(source)).blob() : source;+ const bitmap = await createImageBitmap(blob);+ const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height));+ const width = Math.max(1, Math.round(bitmap.width * scale));+ const height = Math.max(1, Math.round(bitmap.height * scale));++ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ const context = canvas.getContext('2d');+ if (!context) {+ bitmap.close();+ return undefined;+ }+ context.drawImage(bitmap, 0, 0, width, height);+ bitmap.close();++ const { data } = context.getImageData(0, 0, width, height);+ return toBase64(rgbaToThumbHash(width, height, data));+ } catch {+ return undefined;+ }+};++/** Decodes a base64 ThumbHash into a PNG data URL, or undefined when the hash is malformed. */+export const thumbhashToDataUrl = (thumbhash: string): string | undefined => {+ try {+ return thumbHashToDataURL(fromBase64(thumbhash));+ } catch {+ return undefined;+ }+};diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsxindex 50139ac2f5f..e7f351cbd5f 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx@@ -10,13 +10,14 @@ import {} from '@lobehub/ui';import { isNull } from 'es-toolkit/compat';import { FileBoxIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { isChunkingSupported } from '@/libs/document-loaders/loaderType';import { fileManagerSelectors, useFileStore } from '@/store/file';import { densityVars } from '@/styles/densityVars';import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';+import { thumbhashToDataUrl } from '@/utils/client/imageThumbhash';import { formatSize } from '@/utils/format';import ChunksBadge from '../../ListView/ListItem/ChunkTag';@@ -196,6 +197,11 @@ const ImageFileItem = memo<ImageFileItemProps>(}) => {const { t } = useTranslation('components');const knownAspectRatio = readAspectRatio(metadata);+ const thumbhash = metadata?.thumbhash;+ const thumbhashUrl = useMemo(+ () => (typeof thumbhash === 'string' ? thumbhashToDataUrl(thumbhash) : undefined),+ [thumbhash],+ );const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading');// Falls back to a reserved box until the bitmap reports its own ratio.const [aspectRatio, setAspectRatio] = useState(knownAspectRatio ?? FALLBACK_ASPECT_RATIO);@@ -209,8 +215,22 @@ const ImageFileItem = memo<ImageFileItemProps>(return (<>- <div className={styles.imageWrapper} style={{ aspectRatio }}>- {!imageLoaded && (+ <div+ className={styles.imageWrapper}+ style={{+ aspectRatio,+ // Blurred preview from the ThumbHash recorded at upload: painted beneath the bitmap+ // so it shows while the image loads and stays under its fade-in.+ ...(thumbhashUrl &&+ status !== 'error' && {+ backgroundImage: `url(${thumbhashUrl})`,+ backgroundPosition: 'center',+ backgroundSize: 'cover',+ }),+ }}+ >+ {/* A ThumbHash already says "picture on its way"; the glyph is for boxes without one. */}+ {!imageLoaded && !(status === 'loading' && thumbhashUrl) && (<divclassName={cx(styles.placeholder, status === 'loading' && styles.placeholderLoading)}>diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.tsindex 7cfdcc46944..5545f32c99c 100644--- a/src/store/file/slices/upload/action.test.ts+++ b/src/store/file/slices/upload/action.test.ts@@ -8,6 +8,7 @@ import { fileService } from '@/services/file';import { uploadService } from '@/services/upload';import { getAudioDuration } from '@/utils/client/audioDuration';import { getImageDimensions } from '@/utils/client/imageDimensions';+import { getImageThumbhash } from '@/utils/client/imageThumbhash';import { useFileStore as useStore } from '../../store';@@ -29,6 +30,10 @@ vi.mock('@/utils/client/imageDimensions', () => ({getImageDimensions: vi.fn(),}));+vi.mock('@/utils/client/imageThumbhash', () => ({+ getImageThumbhash: vi.fn(),+}));+// Mock for sha256vi.mock('js-sha256', () => ({sha256: {@@ -67,6 +72,7 @@ beforeEach(() => {vi.mocked(handleFileUploadError).mockReturnValue(false);vi.mocked(fileTypeFromBlob).mockResolvedValue(undefined);vi.mocked(getAudioDuration).mockResolvedValue(undefined);+ vi.mocked(getImageThumbhash).mockResolvedValue(undefined);vi.spyOn(uploadService, 'releaseUpload').mockResolvedValue();});@@ -100,6 +106,7 @@ describe('FileUploadAction', () => {// Mock dependenciesvi.mocked(getImageDimensions).mockResolvedValue(mockDimensions);+ vi.mocked(getImageThumbhash).mockResolvedValue('HBkSHYSIeHiPiHh8eJd4eTN0EEQG');vi.spyOn(uploadService, 'uploadBase64ToS3').mockResolvedValue(mockUploadResult);vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);@@ -108,11 +115,16 @@ describe('FileUploadAction', () => {});expect(getImageDimensions).toHaveBeenCalledWith(base64Data);+ expect(getImageThumbhash).toHaveBeenCalledWith(base64Data);expect(uploadService.uploadBase64ToS3).toHaveBeenCalledWith(base64Data);expect(fileService.createFile).toHaveBeenCalledWith({fileType: mockUploadResult.fileType,hash: mockUploadResult.hash,- metadata: { ...mockUploadResult.metadata, ...mockDimensions },+ metadata: {+ ...mockUploadResult.metadata,+ ...mockDimensions,+ thumbhash: 'HBkSHYSIeHiPiHh8eJd4eTN0EEQG',+ },name: mockMetadata.filename,size: mockUploadResult.size,url: mockMetadata.path,@@ -231,6 +243,7 @@ describe('FileUploadAction', () => {const onStatusUpdate = vi.fn();vi.mocked(getImageDimensions).mockResolvedValue(mockDimensions);+ vi.mocked(getImageThumbhash).mockResolvedValue('HBkSHYSIeHiPiHh8eJd4eTN0EEQG');vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);const uploadToS3Spy = vi.spyOn(uploadService, 'uploadFileToS3');@@ -253,7 +266,11 @@ describe('FileUploadAction', () => {{fileType: mockFile.type,hash: 'mock-hash-value',- metadata: { ...mockExistingMetadata, ...mockDimensions },+ metadata: {+ ...mockExistingMetadata,+ ...mockDimensions,+ thumbhash: 'HBkSHYSIeHiPiHh8eJd4eTN0EEQG',+ },name: mockFile.name,size: mockFile.size,url: mockExistingMetadata.path, // Uses metadata.path when availablediff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.tsindex 2d601b2ec44..50787fe8cf2 100644--- a/src/store/file/slices/upload/action.ts+++ b/src/store/file/slices/upload/action.ts@@ -10,6 +10,7 @@ import type { StoreSetter } from '@/store/types';import type { UploadFileItem } from '@/types/files';import { getAudioDuration } from '@/utils/client/audioDuration';import { getImageDimensions } from '@/utils/client/imageDimensions';+import { getImageThumbhash } from '@/utils/client/imageThumbhash';import type { FileStore } from '../../store';import { audioMimeFromExtension } from '../chat/uploadGuard';@@ -120,8 +121,11 @@ export class FileUploadActionImpl {): Promise<UploadWithProgressResult | undefined> => {let uploadedPathname: string | undefined;try {- // Extract image dimensions from base64 data- const dimensions = await getImageDimensions(base64);+ // Extract image dimensions and the blurred placeholder from base64 data+ const [dimensions, thumbhash] = await Promise.all([+ getImageDimensions(base64),+ getImageThumbhash(base64),+ ]);const { metadata, fileType, size, hash } = await uploadService.uploadBase64ToS3(base64);uploadedPathname = metadata.path;@@ -129,7 +133,7 @@ export class FileUploadActionImpl {const res = await fileService.createFile({fileType,hash,- metadata: { ...metadata, ...dimensions },+ metadata: { ...metadata, ...dimensions, ...(thumbhash && { thumbhash }) },name: metadata.filename,size,url: metadata.path,@@ -168,8 +172,11 @@ export class FileUploadActionImpl {? getAudioDuration(normalizedFile).catch(() => undefined): undefined;- // 1. extract image dimensions if applicable- const dimensions = await getImageDimensions(normalizedFile);+ // 1. extract image dimensions and the blurred placeholder if applicable+ const [dimensions, thumbhash] = await Promise.all([+ getImageDimensions(normalizedFile),+ getImageThumbhash(normalizedFile),+ ]);// 2. check file hashconst hash = await hashFile(normalizedFile, abortController?.signal, (progress) => {@@ -248,6 +255,7 @@ export class FileUploadActionImpl {...fileMetadata,...metadata,...dimensions,+ ...(thumbhash && { thumbhash }),...(durationMs === undefined ? {} : { durationMs }),},name: normalizedFile.name,