Unverified Commit 208c4f44 authored by Daniel Tao's avatar Daniel Tao Committed by GitHub

fix(image): findClosestQuality returns 0 for low quality values (#89621)

Fixes #89620

Fix `findClosestQuality` returning `0` when the `quality` prop on
`<Image>` is set to a low value (e.g. `quality={1}`), which causes the
image optimization server to reject the request with a 400 error.

### Cause

The `reduce` call in `findClosestQuality` used `0` as its initial
accumulator. Since `0` is not a valid quality value (must be 1-100), it
would win the "closest" comparison for any `quality <= 37` with the
default `qualities: [75]` config. This produced `q=0` in the image URL,
which the server rejects.

### Fix Description

Changed the `reduce` initializer from `0` to `config.qualities[0]`. This
is safe because the early return above already handles the empty array
case, so `config.qualities[0]` is always defined when reached.

Added a unit test for `quality=1` with `qualities=[75]` to verify it
returns `75` instead of `0`.

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 35a46b15
...@@ -16,6 +16,6 @@ export function findClosestQuality( ...@@ -16,6 +16,6 @@ export function findClosestQuality(
} }
return config.qualities.reduce( return config.qualities.reduce(
(prev, cur) => (Math.abs(cur - q) < Math.abs(prev - q) ? cur : prev), (prev, cur) => (Math.abs(cur - q) < Math.abs(prev - q) ? cur : prev),
0 config.qualities[0]
) )
} }
...@@ -71,6 +71,18 @@ describe('findClosestQuality', () => { ...@@ -71,6 +71,18 @@ describe('findClosestQuality', () => {
input: [14, { qualities: [100, 10, 75, 15] }], input: [14, { qualities: [100, 10, 75, 15] }],
output: 15, // use closet input even when config is out of order output: 15, // use closet input even when config is out of order
}, },
{
input: [1, { qualities: [75] }],
output: 75, // low quality should not return 0
},
{
input: [4, { qualities: [5, 25] }],
output: 5, // ensure low quality still rounds up
},
{
input: [6, { qualities: [5, 25] }],
output: 5, // ensure low quality still rounds down
},
])('for quality $input expected $output', ({ input, output }) => { ])('for quality $input expected $output', ({ input, output }) => {
expect(findClosestQuality(...input)).toEqual(output) expect(findClosestQuality(...input)).toEqual(output)
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment