Derive aspect on the fly

This commit is contained in:
Dan Abramov
2024-11-01 02:12:00 +00:00
parent 56740a3d26
commit 412426bac3
+10 -11
View File
@@ -21,22 +21,21 @@ export function useImageAspectRatio({
src: string src: string
dimensions: Dimensions | undefined dimensions: Dimensions | undefined
}) { }) {
const [raw, setAspectRatio] = React.useState(() => { const [dims, setDims] = React.useState(
const dims = dimensions ?? imageSizes.get(src) () => dimensions ?? imageSizes.get(src),
return dims ? calc(dims) : undefined )
})
const [prevSrc, setPrevSrc] = React.useState(src) const [prevSrc, setPrevSrc] = React.useState(src)
if (src !== prevSrc) { if (src !== prevSrc) {
const dims = dimensions ?? imageSizes.get(src) setDims(dimensions ?? imageSizes.get(src))
setAspectRatio(dims ? calc(dims) : undefined)
setPrevSrc(src) setPrevSrc(src)
} }
let constrained: number | undefined let constrained: number | undefined
let max: number | undefined let max: number | undefined
let isCropped: boolean | undefined let isCropped: boolean | undefined
if (raw !== undefined) { if (dims !== undefined) {
const raw = calc(dims)
const ratio = 1 / 2 // max of 1:2 ratio in feeds const ratio = 1 / 2 // max of 1:2 ratio in feeds
constrained = Math.max(raw, ratio) constrained = Math.max(raw, ratio)
max = Math.max(raw, 0.25) // max of 1:4 in thread max = Math.max(raw, 0.25) // max of 1:4 in thread
@@ -45,15 +44,15 @@ export function useImageAspectRatio({
React.useEffect(() => { React.useEffect(() => {
let aborted = false let aborted = false
if (raw !== undefined) return if (dims !== undefined) return
imageSizes.fetch(src).then(newDim => { imageSizes.fetch(src).then(newDims => {
if (aborted) return if (aborted) return
setAspectRatio(calc(newDim)) setDims(newDims)
}) })
return () => { return () => {
aborted = true aborted = true
} }
}, [raw, setAspectRatio, src]) }, [dims, setDims, src])
return { return {
constrained, constrained,