From f66763371cb7a55c60f4e3d552f476795a97229d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mime=20=C4=8Cuvalo?= Date: Tue, 2 Jul 2024 11:32:43 +0100 Subject: [PATCH] asset: targeted fix for loading the initial url quicker, before debouncing (#4058) This is a more surgical fix while these other diffs are being hashed out: https://github.com/tldraw/tldraw/pull/4045 and https://github.com/tldraw/tldraw/pull/4048 Problem was that we always waited a minimum of 500ms and we really should have a `leading: true` to our debounce. ### Change type - [x] `bugfix` - [ ] `improvement` - [ ] `feature` - [ ] `api` - [ ] `other` ### Release notes - Assets: fix artificial delay in showing an image. --- .../tldraw/src/lib/shapes/shared/useAsset.ts | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/tldraw/src/lib/shapes/shared/useAsset.ts b/packages/tldraw/src/lib/shapes/shared/useAsset.ts index dc78fd671..9b6f63580 100644 --- a/packages/tldraw/src/lib/shapes/shared/useAsset.ts +++ b/packages/tldraw/src/lib/shapes/shared/useAsset.ts @@ -1,5 +1,5 @@ import { TLAssetId, TLShapeId, useEditor, useValue } from '@tldraw/editor' -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' /** @internal */ export function useAsset(shapeId: TLShapeId, assetId: TLAssetId | null, width: number) { @@ -8,6 +8,11 @@ export function useAsset(shapeId: TLShapeId, assetId: TLAssetId | null, width: n const asset = assetId ? editor.getAsset(assetId) : null const culledShapes = editor.getCulledShapes() const isCulled = culledShapes.has(shapeId) + const didAlreadyResolve = useRef(false) + + useEffect(() => { + if (url) didAlreadyResolve.current = true + }, [url]) const shapeScale = asset && 'w' in asset.props ? width / asset.props.w : 1 // We debounce the zoom level to reduce the number of times we fetch a new image and, @@ -21,12 +26,15 @@ export function useAsset(shapeId: TLShapeId, assetId: TLAssetId | null, width: n if (isCulled) return let isCancelled = false - const timer = editor.timers.setTimeout(async () => { - const resolvedUrl = await editor.resolveAssetUrl(assetId, { - screenScale, - }) - if (!isCancelled) setUrl(resolvedUrl) - }, 500) + const timer = editor.timers.setTimeout( + async () => { + const resolvedUrl = await editor.resolveAssetUrl(assetId, { + screenScale, + }) + if (!isCancelled) setUrl(resolvedUrl) + }, + didAlreadyResolve.current ? 500 : 0 + ) return () => { clearTimeout(timer)