Skip to content

Commit

Permalink
chore(image-shrink): add fallback test
Browse files Browse the repository at this point in the history
  • Loading branch information
nd0ut committed Mar 8, 2024
1 parent 7db3b63 commit 1deb1b2
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 7 deletions.
42 changes: 42 additions & 0 deletions packages/image-shrink/src/utils/render/fallback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/// <reference types="vite/client" />
import { describe, expect, it } from 'vitest'
import { fallback } from './fallback'
import { loadImageAsBlob } from '../../test/helpers/loadImageAsBlob'
import { imageLoader } from '../../utils/image/imageLoader'

describe('fallback', () => {
it('should work', async () => {
const originalFile = await loadImageAsBlob(
() => import('../../test/samples/2000x2000.jpeg')
)
const image = await imageLoader(URL.createObjectURL(originalFile))
URL.revokeObjectURL(image.src)

const canvas = await fallback({
img: image,
sourceW: image.width,
targetW: 100,
targetH: 100,
step: 0.71
})

expect(canvas.width).toBe(100)
})

it('should throw if not supported', async () => {
const originalFile = await loadImageAsBlob(
() => import('../../test/samples/2000x2000.jpeg')
)
const image = await imageLoader(URL.createObjectURL(originalFile))
URL.revokeObjectURL(image.src)

const promise = fallback({
img: image,
sourceW: image.width,
targetW: 65535 + 1,
targetH: 65535 + 1,
step: 0.71
})
expect(promise).rejects.toThrow('Not supported')
})
})
17 changes: 10 additions & 7 deletions packages/image-shrink/src/utils/render/fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,17 @@ export const fallback = ({
const steps = calcShrinkSteps({ sourceW, targetW, targetH, step })

return steps.reduce(
(chain, [w, h]) => {
(chain, [w, h], idx) => {
return chain.then((canvas) => {
return (
testCanvasSize(w, h)
.then(() => canvasResize(canvas, w, h))
// Here we assume that at least one step will be supported and HTMLImageElement will be converted to HTMLCanvasElement
.catch(() => canvas as unknown as HTMLCanvasElement)
)
return testCanvasSize(w, h)
.then(() => canvasResize(canvas, w, h))
.catch(() => {
if (idx === steps.length - 1) {
// If the last step is failed then we assume that we can't shrink the image at all
throw new Error('Not supported')
}
return canvas as unknown as HTMLCanvasElement
})
})
},
Promise.resolve(img as HTMLCanvasElement | HTMLImageElement)
Expand Down

0 comments on commit 1deb1b2

Please sign in to comment.