-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(gatsby-transform-url): allow ar to be set as a string for fluid …
…images
- Loading branch information
1 parent
e1972f8
commit fa5eac8
Showing
3 changed files
with
68 additions
and
3 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import * as t from 'io-ts'; | ||
import * as R from 'ramda'; | ||
import { roundToDP } from './number'; | ||
interface AspectRatioBrand { | ||
readonly StringAspectRatio: unique symbol; | ||
} | ||
|
||
export const StringAspectRatio = t.brand( | ||
t.string, | ||
(v): v is t.Branded<string, AspectRatioBrand> => aspectRatioIsValid(v), | ||
'StringAspectRatio', | ||
); | ||
export type StringAspectRatio = t.TypeOf<typeof StringAspectRatio>; | ||
|
||
/** | ||
* Validates that an aspect ratio is in the format w:h. If false is returned, the aspect ratio is in the wrong format. | ||
*/ | ||
function aspectRatioIsValid(aspectRatio: string): boolean { | ||
if (typeof aspectRatio !== 'string') { | ||
return false; | ||
} | ||
|
||
return /^\d+(\.\d+)?:\d+(\.\d+)?$/.test(aspectRatio); | ||
} | ||
export const parseStringARParam = (ar: StringAspectRatio): number => | ||
R.pipe( | ||
(v: StringAspectRatio) => v.split(':') as [string, string], | ||
R.map((part) => parseFloat(part)), | ||
([width, height]) => width / height, | ||
(v) => roundToDP(3, v), | ||
)(ar); |
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,6 @@ | ||
import { curry } from 'ramda'; | ||
|
||
export const roundToDP = curry( | ||
(dp: number, num: number): number => | ||
Math.round(num * Math.pow(10, dp)) / Math.pow(10, dp), | ||
); |
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