-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add aspectRatio to ProductSummaryImage
- Loading branch information
iaron
committed
Feb 4, 2020
1 parent
f0cc795
commit 9f0334a
Showing
2 changed files
with
110 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import { changeImageUrlSize } from './normalize' | ||
|
||
|
||
/** Parses ratio values into a multiplier to set the image height. | ||
* For example, turns "3:4" into 1.333, so the image height will be | ||
* 1.333 times its width. | ||
*/ | ||
const parseAspectRatio = (input) => { | ||
if (!input) { | ||
return null | ||
} | ||
if (typeof input === 'string') { | ||
if (input === 'auto') { | ||
return null | ||
} | ||
const separator = ':' | ||
const data = input.split(separator) | ||
if (data.length !== 2) { | ||
return null | ||
} | ||
|
||
const [ width, height ] = data | ||
const ratio = parseFloat(height) / parseFloat(width) | ||
|
||
if (typeof ratio !== 'number' || isNaN(ratio)) { | ||
return null | ||
} | ||
|
||
return ratio | ||
} | ||
|
||
if (typeof input === 'number') { | ||
return input | ||
} | ||
|
||
return null | ||
} | ||
|
||
export const imageUrl = (src, size, maxSize, aspectRatio) => { | ||
let width = size | ||
let height = 'auto' | ||
|
||
if (aspectRatio && aspectRatio !== 'auto') { | ||
height = size * (parseAspectRatio(aspectRatio) || 1) | ||
|
||
if (width > maxSize) { | ||
height = height / (width / maxSize) | ||
width = maxSize | ||
} | ||
|
||
if (height > maxSize) { | ||
width = width / (height / maxSize) | ||
height = maxSize | ||
} | ||
|
||
width = Math.round(width) | ||
height = Math.round(height) | ||
} else { | ||
width = Math.min(maxSize, width) | ||
} | ||
return changeImageUrlSize(src, width, height) | ||
} |