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.
This commit is contained in:
Mime Čuvalo 2024-07-02 11:32:43 +01:00 committed by GitHub
parent 031547749f
commit f66763371c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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)