Skip to content
This repository has been archived by the owner on May 27, 2024. It is now read-only.

Commit

Permalink
Merge pull request #46 from PsycleResearch/fix/multipart-images-loading
Browse files Browse the repository at this point in the history
fix: Multipart images loading
  • Loading branch information
mbaumanndev authored Dec 5, 2022
2 parents 17f58b6 + 005a81c commit 7ac0162
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@psycle/repsycle",
"version": "0.0.33",
"version": "0.0.34",
"description": "Psycle Research front-end toolkit",
"author": "Psycle Research",
"keywords": [
Expand Down
51 changes: 42 additions & 9 deletions src/draw-zone/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,49 @@ import { MAX_SCALE, SCALE_STEP } from './constants'
import { memoize } from 'lodash'

async function preloadImage(src: string): Promise<Size> {
const ev = await new Promise<Event>((resolve, reject) => {
const image = new Image()
image.onload = resolve
image.onerror = reject
image.src = src
return await new Promise<Size>((resolve, reject) => {
// Use an iframe as a workaround for multipart/x-mixed-replace images size compute
// An ordinary image would load the multipart/x-mixed-replace twice and increase payload size
const iframe = document.createElement('iframe')

iframe.onload = () => {
if (!iframe.contentWindow) {
reject('No content window')
iframe.remove()
} else {
const image = new Image()
iframe.contentWindow.document.body.appendChild(image)

image.onload = (ev) => {
const target = ev.target as HTMLImageElement
const { width, height } = target

image.remove()
iframe.remove()

resolve({ width, height })
}
image.onerror = () => {
reject('Failed to load image')
image.remove()
iframe.remove()
}
image.src = src
}
}

const html = `<body></body>`

if (typeof iframe.srcdoc !== 'undefined') {
iframe.srcdoc = html
} else if (iframe.contentWindow) {
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(html)
iframe.contentWindow.document.close()
}

document.body.appendChild(iframe)
})

const target = ev.target as HTMLImageElement
const { width, height } = target
return { width, height }
}

const preloadImageMemo = memoize(preloadImage)
Expand Down

0 comments on commit 7ac0162

Please sign in to comment.